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 __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 __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 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, 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 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 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 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 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 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 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 collect(self,strategic = None ,statisticsProjectPath = None): """ 对于整体数据,缓存之前计算。对于指定策略,暂时只收集15日内数据,反映短期内变动情况。 收集统计数据 >> statistics.stock == testCase['stock'] >> statistics.collect() 收集指定策略统计数据 >> statistics.stock == testCase['stock'] >> statistics.collect(strategic = testCase['collectStrategic']) @param {list} strategic 符合策略的code list """ conf={} conf.update(self.conf) isCache = False data={} if strategic: #计算指定策略统计 allCode = strategic #符合指定策略的 code 可通过strategic[date][strategicName]读出 allDate = [] for i in range(0,conf.get("MIN_DATA_NUM",MIN_DATA_NUM)): date=Date.getDate(0-i,conf.get('date',Date.getDate())) allDate.append(date) else: #计算整体统计 isCache = True allDate = self.stock.allDate allCode = self.stock.allCode if isCache: #读取之前统计缓存 data = Reader.read(path = self.getDataPath(dataType = "cache")) for date in allDate: if date in data and date in allDate: allDate.remove(date) conf.update({ "date":self.date, "stock":self.stock, "allCode":allCode }) expression=Expression(conf) statisticsProjectPath = statisticsProjectPath or os.path.join(conf.get("SYS_HOME"),conf.get("STATISTICS_PROJECT_PATH")) expressions = expression.load(path = statisticsProjectPath) for date in allDate: result={} #初始化result变量,让result能在公式里直接使用,并且result[name]也能使用 for code in allCode: result[code]={} expression.execute(expression= conf.get("expressions",expressions), context = {"result":result,"date":date}) if not result: break; data[date]=result if isCache: Dumper.dump(path = self.getDataPath(dataType = "cache"),data =data) return data
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 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_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 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 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 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 _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 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 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 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 generate(e_degree=2, e_range=20, domain=S.Reals): from algebra.engine import Expression expression = "" for solution in Generator.solution(e_degree, e_range): expression += "(x+" + str(-solution) + ")*" expression = expression[0:-1] sexpr = expand(sympify(expression)) return Expression.pretty(str(sexpr))
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 __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 compute(self,strategic,statistics): """ 传入统计数据和模型数据,计算得出报告 >>> report.compute(strategic = case['strategic'] , statistics = case['statistics']) == testResult['compute'] True """ projectPath=os.path.join(self.conf.get("SYS_HOME"),self.conf.get("REPORTER_PROJECT_PATH",REPORTER_PROJECT_PATH)) expression=Expression(self.conf) expressions = expression.load(path=projectPath) result={} for func in expressions: result[func.get("name")]=[] expression.execute(expression= self.conf.get("expressions",expressions), context = {"result":result},conf = {"dataName":"statistics","data":statistics,"itemName" : "strategic"}) #format data self.data=self.getFullReporter(strategic = strategic,statistics = statistics ,report = result) return self.data
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 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 unifier_atom(expr1: Expression, expr2: Expression): if (expr2.isAtom()): expr1, expr2 = expr2, expr1 if (expr1 == expr2): return [] if (expr2.isVariable()): expr1, expr2 = expr2, expr1 if (expr1.isVariable()): if (expr1 in expr2): return None if (expr2.isAtom()): return [[expr1.expression[0], expr2.expression[0]]] else: return [[expr1.expression[0], expr2.expression.__str__()]] return None
def unifier(terms1: Expression, terms2: Expression): if (terms1.isAtom() or terms2.isAtom()): return unifier_atom(terms1, terms2) F1, T1 = terms1.separate() F2, T2 = terms2.separate() Z1 = unifier(F1, F2) if (Z1 == None): return None T1.substitute(Z1) T2.substitute(Z1) Z2 = unifier(T1, T2) if (Z2 == None): return None Z2 += Z1 return Z2
def leftMousePressedProgram(self, x, y): self.error = "" if(self.inRangeTabs(x, y)): return obj = self.dashboard.inRange(x, y) if(isinstance(obj, Print)): self.tmpDrag = Print(x, y) self.Draggable = True elif(isinstance(obj, ElseStatement)): self.tmpDrag = ElseStatement(x, y, do=[]) self.Draggable = True elif(isinstance(obj, ElifStatement)): self.tmpDrag = ElifStatement(x, y, do=[]) self.Draggable = True elif(isinstance(obj, IfStatement)): self.tmpDrag = IfStatement(x, y, do=[]) self.Draggable = True elif(isinstance(obj, ForLoop)): self.tmpDrag = ForLoop(x, y, do=[]) self.Draggable = True elif(isinstance(obj, WhileLoop)): self.tmpDrag = WhileLoop(x, y, do=[]) self.Draggable = True elif(isinstance(obj, Variable)): self.tmpDrag = Variable(x, y) self.Draggable = True elif(isinstance(obj, Return)): self.tmpDrag = Return(x, y) self.Draggable = True elif(isinstance(obj, Expression)): self.tmpDrag = Expression(x, y) self.Draggable = True else: if(self.highLighted != None): self.highLighted.selected = False self.tmpDrag = self.function[self.functionNum].inRange(x, y) if(self.tmpDrag != None): self.highLighted = self.tmpDrag self.highLighted.selected = True self.Draggable = True
def checkSyntax(self): test = self.input.lstrip() test = test.rstrip() stringOpen = False blockOpen = False expOpen = False blockOpenCounter = 0 blockCloseCounter = 0 expOpenCounter = 0 expCloseCounter = 0 expIndex = 0 guardIndex = 0 equals = False not_equals = False for x in range(0, len(test)): if (test[x] == '"'): if (stringOpen == False): stringOpen = True else: stringOpen = False if (test[x] == '{'): if(blockOpenCounter == 0): blockOpen = True blockOpenCounter += 1 if (test[x] == '}'): blockCloseCounter += 1 if (blockOpenCounter == blockCloseCounter): blockOpen = False if (test[x] == '('): if(expOpenCounter == 0): expOpen = True expOpenCounter += 1 if (test[x] == ')'): expCloseCounter += 1 if(expCloseCounter == expOpenCounter): expOpen = False if (stringOpen == False and blockOpen == False and expOpen == False): if (expIndex == 0 and ((test[x] == '=') or (test[x] == '#'))): if(test[x] == '='): equals = True if(test[x] == '#'): not_equals = True e1 = Expression(test[:x-1],self.getParent()) e1.setSyntaxOnly(self.syntax_only) expIndex = x+2 elif (test[x] == ','): if (expIndex == 0): print ("Missing expression in Guard-Command: " + test + "\nPlease check correct Syntax: expression ('='|'#') expression [',' guard]") return -1 e2 = Expression(test[expIndex:x]) e2.setSyntaxOnly(self.syntax_only) guardIndex = x+1 break if(expIndex == 0): print ("Missing '=' or '#' found in Guard-Command: " + test + "\nPlease check correct Syntax: expression ('='|'#') expression [',' guard]") return -1 if(guardIndex == 0): e2 = Expression(test[expIndex:],self.getParent()) e2.setSyntaxOnly(self.syntax_only) g = Guard("",self.getParent()) g.setSyntaxOnly(self.syntax_only) else: g = Guard(test[guardIndex:],self.getParent()) g.setSyntaxOnly(self.syntax_only) if not self.syntax_only: return (self.checkSemantic(e1,e2,g,equals,not_equals)) else: if(g.getInput() != ""): if (e1.checkSyntax() and e2.checkSyntax() and g.checkSyntax()): return 1 else: return -1 else: if (e1.checkSyntax() and e2.checkSyntax()): return 1 else: return -1
def generate_statement_list(param_node): node = param_node stmt_list = StmtList() while True: if node.get_type() == 'ident': left_expr = Expression(node.get_name()) left_expr.set_type(symbol_table.get(node.get_name())) left_expr.set_node_type(node.get_type()) assign_stmt = AssignStatement(left_expr) assign_name = node.get_child_nodes()[0].get_name() assign_stmt.set_name(assign_name) right_expr = evaluate_expression(node.get_child_nodes()[1]) assign_stmt.set_right_expr(right_expr) stmt_list.add_statement_to_list(assign_stmt) if (not right_expr.get_type_error()) and (left_expr.get_type() == right_expr.get_type()): AST.dot.edge(stmt_list.get_gv_name(), assign_stmt.get_gv_name()) AST.dot.edge(assign_stmt.get_gv_name(), left_expr.get_gv_name()) AST.dot.edge(assign_stmt.get_gv_name(), right_expr.get_gv_name()) assign_stmt.set_type(left_expr.get_type()) else: AST.dot.edge(stmt_list.get_gv_name(), assign_stmt.get_gv_name(), color='red') AST.dot.edge(assign_stmt.get_gv_name(), left_expr.get_gv_name(), color='red') AST.dot.edge(assign_stmt.get_gv_name(), right_expr.get_gv_name(), color='red') stmt_list.set_type_error(True) elif node.get_name() == 'while' or node.get_name() == 'if': child0 = node.get_child_nodes()[0] length = len(child0.get_child_nodes()) if length > 1: left_expr = evaluate_expression(child0) child = child0.get_child_nodes()[1] else: left_expr = Expression(child0.get_name()) left_expr.set_type(symbol_table.get(child0.get_name())) left_expr.set_node_type(child0.get_type()) child = child0.get_child_nodes()[0] compare_expr = Expression(child.get_name()) compare_expr.set_type('bool') right_expr = evaluate_expression(child.get_child_nodes()[0]) if (not left_expr.get_type_error()) and (not right_expr.get_type_error()) and (left_expr.get_type() == right_expr.get_type()): AST.dot.edge(compare_expr.get_gv_name(), left_expr.get_gv_name()) AST.dot.edge(compare_expr.get_gv_name(), right_expr.get_gv_name()) else: if (not left_expr.get_type_error()) and (not right_expr.get_type_error()) and (left_expr.get_type() != right_expr.get_type()): AST.dot.edge(compare_expr.get_gv_name(), left_expr.get_gv_name(), color='red') AST.dot.edge(compare_expr.get_gv_name(), right_expr.get_gv_name(), color='red') else: if left_expr.get_type_error(): AST.dot.edge(compare_expr.get_gv_name(), left_expr.get_gv_name(), color='red') else: AST.dot.edge(compare_expr.get_gv_name(), left_expr.get_gv_name()) if right_expr.get_type_error(): AST.dot.edge(compare_expr.get_gv_name(), right_expr.get_gv_name(), color='red') else: AST.dot.edge(compare_expr.get_gv_name(), right_expr.get_gv_name()) compare_expr.set_type_error(True) compare_expr.set_left_expr(left_expr) compare_expr.set_right_expr(right_expr) if node.get_name() == 'while': while_statement = WhileStatement(compare_expr) while_statement.set_name(node.get_name()) while_statement.set_node_type(node.get_type()) st_lst = generate_statement_list(node.get_child_nodes()[2]) while_statement.set_while_block_stmt_list(st_lst) stmt_list.add_statement_to_list(while_statement) if compare_expr.get_type_error() or st_lst.get_type_error(): AST.dot.edge(stmt_list.get_gv_name(), while_statement.get_gv_name(), color='red') if compare_expr.get_type_error(): AST.dot.edge(while_statement.get_gv_name(), compare_expr.get_gv_name(), color='red') else: AST.dot.edge(while_statement.get_gv_name(), compare_expr.get_gv_name()) if st_lst.get_type_error(): AST.dot.edge(while_statement.get_gv_name(), st_lst.get_gv_name(), color='red') else: AST.dot.edge(while_statement.get_gv_name(), st_lst.get_gv_name()) stmt_list.set_type_error(True) else: AST.dot.edge(stmt_list.get_gv_name(), while_statement.get_gv_name()) AST.dot.edge(while_statement.get_gv_name(), compare_expr.get_gv_name()) AST.dot.edge(while_statement.get_gv_name(), st_lst.get_gv_name()) else: if_statement = IfStatement(compare_expr) if_statement.set_name(node.get_name()) if_statement.set_node_type(node.get_type()) then_block = node.get_child_nodes()[2] else_block = node.get_child_nodes()[3].get_child_nodes()[0] then_lst = generate_statement_list(then_block) else_lst = generate_statement_list(else_block) if_statement.set_if_block_stmt_list(then_lst) if_statement.set_else_block_stmt_list(else_lst) stmt_list.add_statement_to_list(if_statement) if compare_expr.get_type_error() or then_lst.get_type_error() or else_lst.get_type_error(): AST.dot.edge(stmt_list.get_gv_name(), if_statement.get_gv_name(), color='red') if compare_expr.get_type_error(): AST.dot.edge(if_statement.get_gv_name(), compare_expr.get_gv_name(), color='red') else: AST.dot.edge(if_statement.get_gv_name(), compare_expr.get_gv_name()) if then_lst.get_type_error(): AST.dot.edge(if_statement.get_gv_name(), then_lst.get_gv_name(), color='red') else: AST.dot.edge(if_statement.get_gv_name(), then_lst.get_gv_name()) if else_lst.get_type_error(): AST.dot.edge(if_statement.get_gv_name(), else_lst.get_gv_name(), color='red') else: AST.dot.edge(if_statement.get_gv_name(), else_lst.get_gv_name()) stmt_list.set_type_error(True) else: AST.dot.edge(stmt_list.get_gv_name(), if_statement.get_gv_name()) AST.dot.edge(if_statement.get_gv_name(), compare_expr.get_gv_name()) AST.dot.edge(if_statement.get_gv_name(), then_lst.get_gv_name()) AST.dot.edge(if_statement.get_gv_name(), else_lst.get_gv_name()) elif node.get_name() == 'writeint': expr = evaluate_expression(node.get_child_nodes()[0]) statement = Statement(expr) statement.set_name(node.get_name()) stmt_list.add_statement_to_list(statement) if (not expr.get_type_error()) and (expr.get_type() == 'int'): AST.dot.edge(stmt_list.get_gv_name(), statement.get_gv_name()) AST.dot.edge(statement.get_gv_name(), expr.get_gv_name()) else: AST.dot.edge(stmt_list.get_gv_name(), statement.get_gv_name(), color='red') AST.dot.edge(statement.get_gv_name(), expr.get_gv_name(), color='red') stmt_list.set_type_error(True) else: break; length = len(node.get_child_nodes()) node = node.get_child_nodes()[length - 1] return stmt_list
def evaluate_expression(node): if node.get_name() == '(': length = len(node.get_child_nodes()) left_expr = evaluate_expression(node.get_child_nodes()[0]) if length == 3: child = node.get_child_nodes()[2] expr = Expression(child.get_name()) expr.set_node_type(child.get_type()) right_expr = evaluate_expression(child.get_child_nodes()[0]) expr.set_left_expr(left_expr) expr.set_right_expr(right_expr) if (not left_expr.get_type_error()) and (not right_expr.get_type_error()) and left_expr.get_type() == right_expr.get_type(): AST.dot.edge(expr.get_gv_name(), left_expr.get_gv_name()) AST.dot.edge(expr.get_gv_name(), right_expr.get_gv_name()) expr.set_type(left_expr.get_type()) else: if (not left_expr.get_type_error()) and (not right_expr.get_type_error()) and left_expr.get_type() != right_expr.get_type(): AST.dot.edge(expr.get_gv_name(), left_expr.get_gv_name(), color='red') AST.dot.edge(expr.get_gv_name(), right_expr.get_gv_name(), color='red') else: if left_expr.get_type_error(): AST.dot.edge(expr.get_gv_name(), left_expr.get_gv_name(), color='red') else: AST.dot.edge(expr.get_gv_name(), left_expr.get_gv_name()) if right_expr.get_type_error(): AST.dot.edge(expr.get_gv_name(), right_expr.get_gv_name(), color='red') else: AST.dot.edge(expr.get_gv_name(), right_expr.get_gv_name()) expr.set_type_error(True) return expr else: return left_expr else: left_expr = Expression(node.get_name()) if node.get_type() == 'num': left_expr.set_type('int') elif node.get_type() == 'bool': left_expr.set_type('bool') else: left_expr.set_type(symbol_table.get(node.get_name())) left_expr.set_node_type(node.get_type()) if len(node.get_child_nodes()) <= 0: return left_expr; child = node.get_child_nodes()[0] expr = Expression(child.get_name()) expr.set_node_type(child.get_type()) expr.set_left_expr(left_expr) child2 = child.get_child_nodes()[0] if len(child2.get_child_nodes()) > 0: right_expr = evaluate_expression(child2) else: right_expr = Expression(child2.get_name()) if child2.get_type() == 'num': right_expr.set_type('int') elif child2.get_type() == 'bool': right_expr.set_type('bool') else: right_expr.set_type(symbol_table.get(child2.get_name())) right_expr.set_node_type(child2.get_type()) if (not right_expr.get_type_error()) and (left_expr.get_type() == right_expr.get_type()): AST.dot.edge(expr.get_gv_name(), left_expr.get_gv_name()) AST.dot.edge(expr.get_gv_name(), right_expr.get_gv_name()) expr.set_type(left_expr.get_type()) else: if (not right_expr.get_type_error()) and (left_expr.get_type() != right_expr.get_type()): AST.dot.edge(expr.get_gv_name(), left_expr.get_gv_name(), color='red') AST.dot.edge(expr.get_gv_name(), right_expr.get_gv_name(), color='red') else: if right_expr.get_type_error(): AST.dot.edge(expr.get_gv_name(), right_expr.get_gv_name(), color='red') AST.dot.edge(expr.get_gv_name(), left_expr.get_gv_name()) expr.set_type_error(True) expr.set_right_expr(right_expr) return expr
class runVisualProgrammer(EventBasedAnimationClass): def leftMousePressed(self, event): x, y = (event.x_root - self.root.winfo_rootx(), event.y_root - self.root.winfo_rooty()) if(self.whichScreen == "program"): self.leftMousePressedProgram(x, y) str(self.function[self.functionNum]) elif(self.whichScreen == "start"): self.leftMousePressedStart(x, y) elif(self.whichScreen == "help1" or self.whichScreen == "help2"): self.leftMousePressedHelp(x, y) def leftMousePressedStart(self, x, y): if(self.cx-100<=x<=self.cx+100 and self.cy-5<=y<=self.cy+55): self.switchScreen("program") elif(self.cx-80<=x<=self.cx+80 and self.cy-20+100<=y<=self.cy+20+100): self.switchScreen("help1") def leftMousePressedHelp(self, x, y): self.initStartandSplash() if(self.helpScreenPos == 8): if(self.cx-100<=x<=self.cx+100 and self.cy+70<=y<=self.cy+130): self.switchScreen("program") if(50<=x<=200 and 50<=y<=80): if(self.whichScreen == "help1"): self.switchScreen("start") else: self.switchScreen("program") elif(0<=x<=self.backArrow.width() and self.cy-self.backArrow.height()/2 <=y<=self.cy+self.backArrow.height()/2): if(self.helpScreenPos > 0): self.helpScreenPos -= 1 elif(self.width-self.forwardArrow.width()<=x<=self.width and self.cy-self.forwardArrow.height()/2<=y<= self.cy+self.forwardArrow.height()/2): if(self.helpScreenPos < 8): self.helpScreenPos += 1 def leftMousePressedProgram(self, x, y): self.error = "" if(self.inRangeTabs(x, y)): return obj = self.dashboard.inRange(x, y) if(isinstance(obj, Print)): self.tmpDrag = Print(x, y) self.Draggable = True elif(isinstance(obj, ElseStatement)): self.tmpDrag = ElseStatement(x, y, do=[]) self.Draggable = True elif(isinstance(obj, ElifStatement)): self.tmpDrag = ElifStatement(x, y, do=[]) self.Draggable = True elif(isinstance(obj, IfStatement)): self.tmpDrag = IfStatement(x, y, do=[]) self.Draggable = True elif(isinstance(obj, ForLoop)): self.tmpDrag = ForLoop(x, y, do=[]) self.Draggable = True elif(isinstance(obj, WhileLoop)): self.tmpDrag = WhileLoop(x, y, do=[]) self.Draggable = True elif(isinstance(obj, Variable)): self.tmpDrag = Variable(x, y) self.Draggable = True elif(isinstance(obj, Return)): self.tmpDrag = Return(x, y) self.Draggable = True elif(isinstance(obj, Expression)): self.tmpDrag = Expression(x, y) self.Draggable = True else: if(self.highLighted != None): self.highLighted.selected = False self.tmpDrag = self.function[self.functionNum].inRange(x, y) if(self.tmpDrag != None): self.highLighted = self.tmpDrag self.highLighted.selected = True self.Draggable = True def leftMouseMoved(self, event): x, y = (event.x_root - self.root.winfo_rootx(), event.y_root - self.root.winfo_rooty()) if(self.whichScreen == "program"): if(self.Draggable): self.tmpDrag.move(x, y) def leftMouseReleased(self, event): e = "Wrong placement of Elif and Else Statements." if(self.whichScreen == "program"): x, y = (event.x_root - self.root.winfo_rootx(), event.y_root - self.root.winfo_rooty()) if(self.Draggable): if(x <= self.funcLine and y >= 85): tmp = self.function[self.functionNum].inRangeWithoutPop(x,y) if(isinstance(tmp, Nested)): tmp.addDo(self.tmpDrag) if(not self.checkElif(tmp)): self.removeElif(tmp) self.error += e else: self.function[self.functionNum].addDo(self.tmpDrag) if(not self.checkElif(self.function[self.functionNum])): self.removeElif(self.function[self.functionNum]) self.error += e self.tmpDrag, self.Draggable = None, False self.function[self.functionNum].processObj() tmpString = repr(self.function[self.functionNum]) fN = self.functionNum if(tmpString != self.undoList[fN][self.undoPosList[fN]]): self.undoList[fN] = self.undoList[fN][:self.undoPosList[fN]+1]\ + [tmpString] self.undoPosList[fN] = len(self.undoList[fN])-1 def onTimerFired(self): self.redrawAll() if(self.whichScreen == "help1" or self.whichScreen == "help2"): if(self.helpScreenPos == 3): self.timer += 1 if(self.timer == 230): self.demoVariable = Variable(1050, 200) self.demoIfStatment = IfStatement(1050, 240, do=[]) self.demoPrint = Print(880, 210) self.timer = 0 self.canvas.after(self.timerDelay, self.onTimerFired) elif(self.helpScreenPos == 4): self.timer += 1 if(self.timer == 200): self.demoIfStatment2 = IfStatement(1050, 240, do=[]) self.demoElifStatment = ElifStatement(1050, 280, do=[]) self.timer = 0 self.canvas.after(self.timerDelay, self.onTimerFired) else: self.canvas.after(self.timerDelay * 20, self.onTimerFired) def removeElif(self, tmp): for i in xrange(len(tmp.do)): if(tmp.do[i] is self.tmpDrag): tmp.do.pop(i) return def checkElif(self, tmp): pos = 0 while(pos < len(tmp.do)): if(type(tmp.do[pos]) == IfStatement): pos += 1 while(pos < len(tmp.do)): if(type(tmp.do[pos]) == ElifStatement): pos += 1 elif(type(tmp.do[pos]) == ElseStatement): pos += 1 break else: break elif(type(tmp.do[pos]) == ElifStatement or type(tmp.do[pos]) == ElseStatement): return False else: pos += 1 return True def inRangeTabs(self, x, y): for i in xrange(len(self.tabButtons)): if(self.tabButtons[i].inRange(x, y)): self.switchFunctions(i) return True if(len(self.tabButtons) > 1): for i in xrange(len(self.tabButtons)): if(self.tabButtons[i].inRangeClose(x, y)): self.function.pop(i) self.tabButtons.pop(i) self.undoList.pop(i) self.undoPosList.pop(i) if(i == self.functionNum): if (i <= len(self.tabButtons) - 1): self.switchFunctions(self.functionNum) else: self.functionNum = self.functionNum - 1 self.tabButtons[self.functionNum].selected = True else: if(i < self.functionNum): self.functionNum = self.functionNum - 1 else: self.functionNum = self.functionNum self.processTabs() return True return False def processTabs(self): x = 40 for i in xrange(len(self.tabButtons)): self.tabButtons[i].setXY(x, self.tabButtons[i].y) x += 70 def convertToPython(self): self.dashboard.displayCode(str(self.function[self.functionNum])) for i in xrange(len(self.tabButtons)): self.tabButtons[i].setName(self.function[i].funcName) self.runFunction.config(state='normal') def convertAllToPython(self): tmpString = "" for i in xrange(len(self.function)): tmpString += str(self.function[i]) + "\n" self.dashboard.displayCode(tmpString) for i in xrange(len(self.tabButtons)): self.tabButtons[i].setName(self.function[i].funcName) self.runFunction.config(state='normal') def runPython(self): code = self.dashboard.st.get("1.0",END) try: exec(code) Run(400, 500, code).run() except: self.error = "The code you have written is not in the right format." def switchScreen(self, screen): self.helpScreenPos = 0 if(screen == "program"): self.initMenu() elif(screen == "help2"): self.menu.entryconfig("File", state="disabled") self.menu.entryconfig("Help", state="disabled") self.whichScreen = screen if(screen == "help1" or screen == "help2"): self.onTimerFired() self.redrawAll() def switchFunctions(self, pos): self.tabButtons[self.functionNum].selected = False self.functionNum = pos self.tabButtons[self.functionNum].selected = True def newFunction(self): if(len(self.tabButtons) <= 10 and self.whichScreen == "program"): self.function.append(function(name="func"+str(self.count), do=[])) self.count += 1 if len(self.tabButtons) != 0: x, y = (self.tabButtons[-1].x + 70, self.tabButtons[-1].y) else: x, y = (40, 60) self.tabButtons.append(Tab(x, y, self.function[-1].funcName)) self.switchFunctions(len(self.function) - 1) self.undoList.append(["function(name='func',param=[],do=[])"]) self.undoPosList.append(0) self.redrawAll() def saveFunction(self): if(self.whichScreen == "program"): f = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt") if f is None: return text = repr(self.function[self.functionNum]) f.write(text) f.close() self.redrawAll() def openFunction(self): if(len(self.tabButtons) <= 10 and self.whichScreen == "program"): ftypes = [('Text Files', '*.txt')] dlg = tkFileDialog.Open(filetypes = ftypes) fl = dlg.show() if fl != '': text = self.readFile(fl) try: func = eval(eval(repr(text))) self.function.append(func) self.count += 1 if len(self.tabButtons) != 0: x, y=(self.tabButtons[-1].x + 70,self.tabButtons[-1].y) else: x, y = (40, 60) self.tabButtons.append(Tab(x,y,self.function[-1].funcName)) self.switchFunctions(len(self.function) - 1) self.undoList.append([text]) self.undoPosList.append(0) except: self.error = "Wrong file format to open." self.redrawAll() return None def readFile(self, filename): f = open(filename, "r") text = f.read() return text def drawDashboard(self): canvas = self.canvas canvas.create_image(0, 0, anchor="nw", image=self.background) canvas.create_line(self.funcLine, 0, self.funcLine, self.height, width=4, fill="gray") canvas.create_window(800, 290, window=self.convertButton, anchor="w") canvas.create_window(1000, 290,window=self.convertAllButton,anchor="w") canvas.create_window(1200, 290, window=self.runFunction, anchor="w") self.dashboard.draw(canvas) def drawFunction(self): self.function[self.functionNum].draw(self.canvas) def drawDrag(self): if(self.tmpDrag != None): self.tmpDrag.draw(self.canvas) def drawError(self): canvas = self.canvas canvas.create_text(self.funcLine/2, self.height-30, text=self.error, font="Arial 12 bold", fill="red") def drawProgram(self): canvas = self.canvas canvas.create_text(self.funcLine/2, 15, text="Workspace", font="Arial 18 bold") self.drawError() for i in xrange(len(self.tabButtons)): self.tabButtons[i].draw(canvas) def drawStart(self): canvas = self.canvas canvas.create_image(0, 0, anchor="nw", image=self.startBackground) canvas.create_text(self.cx, self.cy-200, text="Visual Programming", font="Arial 35 bold", fill="blue") canvas.create_text(self.cx, self.cy-150, text="Language", font="Arial 35 bold", fill="blue") canvas.create_text(self.cx, self.cy-75, text="by: Richard Huang", font="Arial 20 bold", fill="black") buttonW, buttonH = 100, 30 canvas.create_rectangle(self.cx-buttonW, self.cy-buttonH+25, self.cx+buttonW, self.cy+buttonH+25, fill="green") canvas.create_text(self.cx, self.cy+25, text="Start Programming!", font="Arial 15 bold") buttonW, buttonH = 80, 20 canvas.create_rectangle(self.cx-buttonW, self.cy-buttonH+100, self.cx+buttonW, self.cy+buttonH+100, fill="red") canvas.create_text(self.cx, self.cy+100, text="Tutorial", font="Arial 12 bold") def redrawAll(self): canvas = self.canvas canvas.delete(ALL) if(self.whichScreen == "start"): self.drawStart() elif(self.whichScreen == "program"): self.drawDashboard() self.drawFunction() self.drawDrag() self.drawProgram() elif(self.whichScreen == "help1" or self.whichScreen == "help2"): HelpScreen.drawHelp(self) def initDashBoard(self): dashPrint = Print(self.width - 8*self.size, 60) dashForLoop = ForLoop(self.width - 8*self.size, 115) dashWhileLoop = WhileLoop(self.width - 8*self.size,170) dashExpression = Expression(self.width - 8*self.size,215) dashReturn = Return((self.funcLine+self.width)/2,250) dashVariable = Variable(self.width - 3*self.size, 50) dashIfStatement = IfStatement(self.width - 3*self.size, 95) dashElifStatement = ElifStatement(self.width - 3*self.size, 150) dashElseStatement = ElseStatement(self.width - 3*self.size, 205) self.dashboard = dashboard(self.width, self.height) self.dashboard.addLabel(dashPrint) self.dashboard.addLabel(dashIfStatement) self.dashboard.addLabel(dashElifStatement) self.dashboard.addLabel(dashForLoop) self.dashboard.addLabel(dashVariable) self.dashboard.addLabel(dashWhileLoop) self.dashboard.addLabel(dashReturn) self.dashboard.addLabel(dashElseStatement) self.dashboard.addLabel(dashExpression) def initMenu(self): self.menu = Menu(self.root) self.filemenu = Menu(self.menu, tearoff=0) self.filemenu2 = Menu(self.menu, tearoff=0) self.filemenu.add_command(label="New", command=self.newFunction) self.filemenu.add_command(label="Open", command=self.openFunction) self.filemenu.add_command(label="Save", command=self.saveFunction) self.filemenu2.add_command(label="Help", command=(lambda:self.switchScreen("help2"))) self.menu.add_cascade(label="File", menu=self.filemenu) self.menu.add_cascade(label="Help", menu=self.filemenu2) self.root.config(menu=self.menu) def initStartandSplash(self): self.startBackground = PhotoImage(file="pics\start_background.gif") self.background = PhotoImage(file="pics\\background.gif") self.backArrow = PhotoImage(file="pics\\back_arrow.gif") self.backArrow = self.backArrow.subsample(2,2) self.forwardArrow = PhotoImage(file="pics\\forward_arrow.gif") self.forwardArrow = self.forwardArrow.subsample(2,2) self.programScreenShot = PhotoImage(file="pics\\program_screenshot.gif") self.programScreenShot2=PhotoImage(file="pics\\program_screenshot2.gif") self.programScreenShot3=PhotoImage(file="pics\\program_screenshot3.gif") self.programScreenShot4=PhotoImage(file="pics\\program_screenshot4.gif") self.programScreenShot5=PhotoImage(file="pics\\program_screenshot5.gif") self.demoVariable = Variable(1050, 200) self.demoIfStatment = IfStatement(1050, 240, do=[]) self.demoIfStatment2 = IfStatement(1050, 240, do=[]) self.demoElifStatment = ElifStatement(1050, 280) self.demoPrint = Print(880, 210) self.timer = 0 def undo(self): fN = self.functionNum if(self.undoPosList[fN] > 0): self.undoPosList[fN] -= 1 self.function[fN] = eval(self.undoList[fN][self.undoPosList[fN]]) self.redrawAll() def redo(self): fN = self.functionNum if(self.undoPosList[fN] < len(self.undoList[fN]) - 1): self.undoPosList[fN] += 1 self.function[fN] = eval(self.undoList[fN][self.undoPosList[fN]]) self.redrawAll() def initAnimation(self): self.x = -1 self.y = -1 self.size = 50 self.root.title("Visual Programming Language") self.error = "" self.count = 1 self.cx, self.cy = self.width/2, self.height/2 self.funcLine = self.cx + 100 self.functionNum = 0 self.function = [function(do=[])] self.undoList = [["function(name='func',param=[],do=[])"]] self.undoPosList = [0] self.Draggable = False self.tmpDrag = None self.initDashBoard() self.highLighted = None self.whichScreen = "start" self.convertButton = Button(self.canvas, text="Convert to Python", command=self.convertToPython) self.convertAllButton = Button(self.canvas, text="Convert All to Python", command=self.convertAllToPython) self.runFunction = Button(self.canvas, text="Run Python Code", command=self.runPython, state=DISABLED) self.tabButtons = [Tab(40,40, self.function[0].funcName)] self.tabButtons[0].selected = True self.initStartandSplash() self.helpScreenPos = 0 self.root.bind('<Control-n>', (lambda x:self.newFunction())) self.root.bind('<Control-o>', (lambda x:self.openFunction())) self.root.bind('<Control-s>', (lambda x:self.saveFunction())) self.root.bind('<Control-z>', (lambda x:self.undo())) self.root.bind('<Control-y>', (lambda x:self.redo()))
def compile(self): #Includes i = 0 while True: if i > len(self.sourceCode)-1: break if self.sourceCode[i].startswith("include"): line = self.sourceCode[i] line = line[len("include"):] filename = self.sourceCode[i].split(" ")[1] self.includeFile(filename,i) del self.sourceCode[i] i -= 1 i += 1 #Extract functions and compile for i in range(len(self.sourceCode)): if i >= len(self.sourceCode): break if self.sourceCode[i].startswith("function "): funname,argslist = getNameAndArgs(self.sourceCode[i]) startLoc = i depthCount = 1 while True: startLoc += 1 line = self.sourceCode[startLoc] if line.startswith("if ") or line.startswith("while "): depthCount += 1 elif line.startswith("end"): depthCount -= 1 if depthCount == 0: break functionLines = self.sourceCode[i+1:startLoc] functionCode = self.compileFunctionBody(functionLines) prepFC = [] argslist.reverse() for item in argslist: prepFC.append("STORE %s" % item) prepFC.extend(functionCode) self.sourceCode[i:startLoc+1] = [] self.funbytecode[funname] = (argslist,prepFC) #Mark all other statement/end pairs stateStack = [] controlEnter = ['if ','while '] for i in range(len(self.sourceCode)): for controlWord in controlEnter: if self.sourceCode[i].startswith(controlWord): stateStack.append((i,)) if self.sourceCode[i].startswith("end"): if len(stateStack[-1]) == 1: litem = stateStack.pop() self.controlPairs.append((litem[0],i)) #Bytecode generation loop for i in range(len(self.sourceCode)): #Handle bound lines self.getBinding(i) #Classify line of source code assign = False for j in range(1,len(self.sourceCode[i])-1): if self.sourceCode[i][j] == "=": if self.sourceCode[i][j+1] != "=": if self.sourceCode[i][j-1] != "=": assign = True printing = False if self.sourceCode[i].startswith("printugly!"): printing = True readinput = False if self.sourceCode[i].startswith("input!"): readinput = True commenting = False if self.sourceCode[i].startswith("#"): commenting = True ifstatement = False if self.sourceCode[i].startswith("if "): ifstatement = True whilestatement = False if self.sourceCode[i].startswith("while "): whilestatement = True returnstatement = False if self.sourceCode[i].startswith("return"): returnstatement = True #Emit bytecodes if printing: line = self.sourceCode[i] line = line[10:] expr = Expression(line) expr.parse() self.bytecode += expr.getBytecode() self.bytecode += ["PRINT"] elif readinput: line = self.sourceCode[i] line = line[5:] expr = Expression(line) expr.parse() self.bytecode += expr.getBytecode() self.bytecode += ["INPUT " + self.sourceCode[i].split(" ")[1]] elif assign: line = self.sourceCode[i].split("=",1) targetSymbol = line[0].strip() expression = line[1].strip() if symbolIsValid(targetSymbol): expr = Expression(expression) expr.parse() self.bytecode += expr.getBytecode() self.bytecode += ["STORE " + targetSymbol] else: raise Exception("Compiler - invalid symbol") elif commenting: pass elif ifstatement: expr = Expression(self.sourceCode[i][3:]) expr.parse() self.bytecode += expr.getBytecode() ctrlPair = None for j in range(len(self.controlPairs)): if self.controlPairs[j][0] == i: ctrlPair = self.controlPairs[j] if not ctrlPair: raise Exception("Compiler - no matching end") self.bytecode += ["JUMPIFNOT {}".format(ctrlPair[1])] elif whilestatement: expr = Expression(self.sourceCode[i][6:]) expr.parse() self.bytecode += expr.getBytecode() ctrlPair = None for j in range(len(self.controlPairs)): if self.controlPairs[j][0] == i: ctrlPair = self.controlPairs[j] if not ctrlPair: raise Exception("Compiler - no matching end") self.bytecode += ["JUMPIFNOT {}".format(ctrlPair[1])] self.bindDefine.append((ctrlPair[1], "JUMP {}".format(ctrlPair[0]))) elif returnstatement: if self.sourceCode[i][6:].strip(): expr = Expression(self.sourceCode[i][6:]) expr.parse() self.bytecode += expr.getBytecode() self.bytecode += ["JUMPOLDCONTEXT"] elif not self.sourceCode[i].startswith("end"): expr = Expression(self.sourceCode[i]) expr.parse() self.bytecode += expr.getBytecode() self.bytecode.append("MARKLINE {}".format(i+1)) self.bytecode += ["TERM"] #Append function codes unmarkCode = [code for code in self.bytecode if not code.startswith("MARK")] for tup in self.funbytecode.keys(): self.funStart[tup] = len(unmarkCode) self.bytecode += self.funbytecode[tup][1] #Calculate jump targets for i in range(len(self.bytecode)): line = self.bytecode[i] if line.startswith("JUMPNEWCONTEXT"): target = line.split()[1] target = target.replace("+","") lineNumber = self.funStart[target] self.bytecode[i] = "JUMPNEWCONTEXT %s" % lineNumber for i in range(len(self.bytecode)): line = self.bytecode[i] if line.startswith("JUMP") and ( not line.startswith("JUMPOLDCONTEXT")) and ( not line.startswith("JUMPNEWCONTEXT")): s = line.split() oldTarget = s[1] for j in range(len(self.bytecode)): line2 = self.bytecode[j] if line2.startswith("MARKLINE"): s2 = line2.split() if s2[1] == oldTarget: newTarget = j-1 break s[1] = str(newTarget) self.bytecode[i] = ' '.join(s) i = -1 while True: i += 1 try: line = self.bytecode[i] except IndexError: break if line.startswith("MARKLINE"): del self.bytecode[i] for j in range(i,len(self.bytecode)): line2 = self.bytecode[j] if line2.startswith("JUMPIF"): lsl = line2.split() lsl[1] = str(int(lsl[1])-1) line2 = ' '.join(lsl) self.bytecode[j] = line2 i -= 1
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 __init__(self, LexNode, operator=None, left=None, right=None): Expression.__init__(self, LexNode, operator, left, right) self._setOperation(operator)