def main(): Brother = Variable() print("Find relations:") for l1 in brother("Hillary", Brother): print("Hillary has brother", Brother.getValue(), ".") print("Check if it is square:") for l1 in squaredRectangle(10, 10): print("10 by 10 rectangle is square.") print("Make it square:") Width = Variable() Height = Variable() for l1 in Width.unify(10): for l2 in squaredRectangle(Width, Height): print("A square of width", Width.getValue(), "has height", Height.getValue(), ".") print("Make it square before we know the width:") for l1 in squaredRectangle(Width, Height): for l2 in Width.unify(10): print("A square of width", Width.getValue(), "has height", Height.getValue(), ".") print("Get one match:") for l1 in anyBrother("Hillary", Brother): print("Hillary has a brother", Brother.getValue(), ".") for l1 in anyBrother("Bill", Brother): print("Bill has a brother", Brother.getValue(), ".") print("Use cut for negation:") for l1 in noBrother("Hillary"): print("Hillary has no brother.") for l1 in noBrother("Chelsea"): print("Chelsea has no brother.")
class ATestEvent(Event): identifier = "test_event" log_target_variable = "order" order_language = Variable(name="Order Language", type=Language) just_some_text = Variable(name="Just Some Text", type=Text) order = Variable(name="Order", type=Model("E-Commerce.Order"))
def isValidAssign(self, line): hasType = False #print("line is: ", line) if line[0] == '$': hasType = True if line[-1] != ';': pass # raise Exception('No semicolon.') else: if expression[0].isdigit(): type = expression[1] if '*' in type: type = '$P' size = expression[0] elif expression[1].isdigit(): type = expression[0] if '*' in type: type = '$P' size = expression[1] self.heapDict[self.heapNum] = [Variable.Variable('-', type, None, self.scope) for i in range(int(size))] self.heapNum += 1 if flag == 1: #assign obj = self.varDicts[-1][name] obj.value = self.heapNum - 1 obj.type = '$P' obj.scope = self.scope else: #declare obj = Variable.Variable(name, '$P', self.heapNum - 1, self.scope) self.varDicts[-1][name.strip('*')] = obj return self.heapNum - 1
def __addActionToScript(self, type): if type == "assign": self.__thisVariableList.__adduniqueitem__( variable.Variable("driver", "", "")) self.__thisVariableList.__adduniqueitem__( variable.Variable("url", "", "http://gmail.com")) # self.__thisScript.__additem__(assnode.AssignNode("", "")) elif type == "if-else": self.__thisScript.__additem__(ifnode.IfNode("", "", "")) elif type == "node-base": self.__thisScript.__additem__(nodebase.NodeBase("", "test_func1")) elif type == "test_func1": self.__thisScript.__additem__( nodebase.NodeBase("node-base1", "test_func1")) elif type == "test_func2": self.__thisScript.__additem__( nodebase.NodeBase("node-base2", "test_func2")) elif type == "open_chrome": self.__thisScript.__additem__( nodebase.NodeBase("node-base1", "open_chrome")) elif type == "open_gmail": self.__thisScript.__additem__( nodebase.NodeBase("node-base2", "open_gmail")) elif type == "message-box": self.__thisScript.__additem__( nodebase.NodeBase("node-base2", "message_box")) return
def add_action_to_script(self, type): if type == "assign": self.variablelist.__adduniqueitem__(variable.Variable( "driver", "")) self.variablelist.__adduniqueitem__( variable.Variable("url", "http://gmail.com")) #self.mainscript.__additem__(assnode.AssignNode("abc", "123")) elif type == "if-else": self.mainscript.__additem__(ifnode.IfNode("", "", "")) elif type == "node-base": self.mainscript.__additem__(nodebase.NodeBase("", "test_func1")) elif type == "test_func1": self.mainscript.__additem__( nodebase.NodeBase("node-base1", "test_func1")) elif type == "test_func2": self.mainscript.__additem__( nodebase.NodeBase("node-base2", "test_func2")) elif type == "open_chrome": self.mainscript.__additem__( nodebase.NodeBase("node-base1", "open_chrome")) elif type == "open_gmail": self.mainscript.__additem__( nodebase.NodeBase("node-base2", "open_gmail")) elif type == "message-box": self.mainscript.__additem__( nodebase.NodeBase("node-base2", "message_box")) elif type == "group": self.mainscript.__additem__( nodegroup.NodeGroup("node-group1", "group1")) return
class RegistrationReceived(Event): identifier = "registration_received" name = _("Registration Received") customer = Variable(_("Customer"), type=Model("E-Commerce.Contact")) customer_email = Variable(_("Customer Email"), type=Email) activation_url = Variable(_("Activation URL"), type=URL, required=False) user_is_active = Variable(_("Is User Active"), type=Boolean)
def applyOperator(op, v1, v2): if op in operators: #print("types: ", (v1.type), v2.type) if v1.type == '$I' or v1.type == '$B': #print("evaluating", (str(v2.value)+op+str(v1.value))) return Variable.Variable(None, opReturns[op], castMap[v1.type](eval(str(v2.value)+op+str(v1.value))), None) elif v1.type == '$S': return Variable.Variable(None, opReturns[op], castMap[v1.type](eval("'"+str(v2.value)+"'"+op+"'"+str(v1.value)+"'")), None)
def main(): YP.assertFact(Atom.a("brother"), \ [Atom.a("Hillary"), Atom.a("Hugh")]) YP.assertFact(Atom.a("brother"), \ [Atom.a("Hillary"), Atom.a("Tony")]) YP.assertFact(Atom.a("brother"), \ [Atom.a("Bill"), Atom.a("Roger")]) Brother = Variable() print "Using dynamic assert:" for l1 in YP.matchDynamic \ (Atom.a("brother"), \ [Atom.a("Hillary"), Brother]): print "Hillary has brother", \ Brother.getValue() prologCode = \ "uncle(Person, Uncle) :- \n" + \ " parent(Person, Parent), \n" + \ " brother(Parent, Uncle). \n" print "# Compiled code:" compileAndWrite(prologCode) prologCode = \ ":- import('', [parent/2]). \n" + \ "uncle(Person, Uncle) :- \n" + \ " parent(Person, Parent), \n" + \ " brother(Parent, Uncle). \n" print "# Calling an imported function:" compileAndWrite(prologCode) prologCode = \ "parent('Chelsea', 'Hillary'). \n" + \ "parent('Chelsea', 'Bill'). \n" + \ \ "uncle(Person, Uncle) :- \n" + \ " parent(Person, Parent), \n" + \ " brother(Parent, Uncle). \n" print "# Calling a locally-defined function:" compileAndWrite(prologCode) prologCode = \ ":- import('', [parent/2]). \n" + \ "uncle(Person, Uncle) :- \n" + \ " Goal = parent(Person, Parent), \n" + \ " Goal, \n" + \ " brother(Parent, Uncle). \n" print "# Calling a dynamic goal:" compileAndWrite(prologCode) print "Calling compiled code having a dynamic goal:" Person = Variable() Uncle = Variable() for l1 in uncle(Person, Uncle): print Person.getValue(), "has uncle", \ Uncle.getValue()
def main(): print "Return a list of 2 elements:" List = Variable() for l1 in makeList("a", "b", List): print "List =", List.getValue() print "Unify two lists:" Second = Variable() for l1 in makeList("x", Second, ListPair("x", ListPair("y", Atom.NIL))): print "The second element is", Second.getValue()
def compileAndWrite(prologCode): YP.tell(sys.stdout) YP.see(YP.StringReader(prologCode)) TermList = Variable() PseudoCode = Variable() for l1 in parseInput(TermList): for l2 in makeFunctionPseudoCode \ (TermList, PseudoCode): convertFunctionPython(PseudoCode) YP.seen()
class RefundCreated(Event): identifier = "refund_created" name = _("Refund Created") order = Variable(_("Order"), type=Model("E-Commerce.Order")) customer_email = Variable(_("Customer Email"), type=Email) customer_phone = Variable(_("Customer Phone"), type=Phone) language = Variable(_("Language"), type=Language) payment_status = Variable(_("Order Payment Status"), type=Enum(PaymentStatus))
def queens3(UnplacedQs, SafeQs, Qs): UnplacedQs1 = Variable() Q = Variable() for l1 in selectq(Q, UnplacedQs, UnplacedQs1): for l2 in notHasAttack(Q, SafeQs): for l3 in queens3(UnplacedQs1, ListPair(Q, SafeQs), Qs): yield False for l1 in YP.unify(UnplacedQs, Atom.NIL): for l2 in YP.unify(Qs, SafeQs): yield False
def selectq(X, Arg2, Arg3): for l1 in ListPair(X, Arg3).unify(Arg2): yield False Y = Variable() Ys = Variable() Zs = Variable() for l1 in ListPair(Y, Ys).unify(Arg2): for l2 in ListPair(Y, Zs).unify(Arg3): for l3 in selectq(X, Ys, Zs): yield False
def test_variables(): # phi1, phi2 : Formule print("TEST DE LA METHODE get_variables") phi1 = Et(Variable("a1"), Ou(Non(Variable("A1")), Variable("a2"))) print("phi1 =", phi1.str_prefixe()) print("V(phi1) =", phi1.get_variables()) print("V(phi1) =", phi1.str_variables()) phi2 = ParseFormule.exec("et(a, ou(B, non(=>(bot, A))))") print("phi2 =", phi2.str_prefixe()) print("V(phi2) =", phi2.get_variables()) print("V(phi2) =", phi2.str_variables())
def uncle(Person, Uncle): Goal = Variable() Parent = Variable() for l1 in YP.unify \ (Goal, Functor2 \ (Atom.a("parent", Atom.a("")), \ Person, Parent)): for l2 in YP.getIterator \ (Goal, getDeclaringClass()): for l3 in YP.matchDynamic \ (Atom.a("brother"), [Parent, Uncle]): yield False
def queens3(UnplacedQs, SafeQs, Qs): UnplacedQsListPair = YP.getValue(UnplacedQs) if isinstance(UnplacedQsListPair, ListPair): UnplacedQs1 = Variable() Q = Variable() for l1 in selectq(Q, UnplacedQsListPair, UnplacedQs1): if not (isinstance(SafeQs, ListPair) and hasAttack(Q.getValue(), SafeQs)): for l2 in queens3(UnplacedQs1, ListPair(Q, SafeQs), Qs): yield False else: for l1 in Qs.unify(SafeQs): yield False
def attack3(X, N, Arg3): Y = Variable() for l1 in ListPair(Y, Variable()).unify(Arg3): if YP.getValue(X) == Y.getValue() + YP.getValue(N): yield False if YP.getValue(X) == Y.getValue() - YP.getValue(N): yield False Ys = Variable() N1 = Variable() for l1 in ListPair(Variable(), Ys).unify(Arg3): for l2 in N1.unify(YP.getValue(N) + 1): for l3 in attack3(X, N1, Ys): yield False
def test_interpretations(): # interp : Interpretation # phi : Formule print("TEST SUR LES INTERPRETATIONS") phi = ParseFormule.exec("et(a, non(ou(b, c)))") print("phi =", phi.str_prefixe()) interp = Interpretation(["a", "b", "c"]) print("interp =", interp, "satisfait-elle phi ?", interp.satisfait(phi)) interp.ajV(Variable("b")) print("interp =", interp, "satisfait-elle phi ?", interp.satisfait(phi)) interp.ajV(Variable("a")) print("interp =", interp, "satisfait-elle phi ?", interp.satisfait(phi)) interp.ajF(Variable("b")) print("interp =", interp, "satisfait-elle phi ?", interp.satisfait(phi))
def mallocParser(self, flag, name, expression, type): #print("expr", expression) hasDigit = False for char in expression: if char.isdigit(): #print("found digit") hasDigit = True break expression = expression.replace('malloc', '') expression = expression.replace('(', '') expression = expression.replace(')', '') expression = expression.replace('sizeof', '') expression = expression.replace(' ', '') expression = expression.split('*') struct = {} if not hasDigit: #not found digit size = 1 type = expression[0] if type in self.structDict.keys(): size = len(self.structDict[type]) for fieldName in self.structDict[type].keys(): struct[fieldName] = Variable.Variable( '-', self.structDict[type][fieldName], None, self.scope) else: if expression[0].isdigit(): type = expression[1] if '*' in type: type = '$P' size = expression[0] elif expression[1].isdigit(): type = expression[0] if '*' in type: type = '$P' size = expression[1] for i in range(int(size)): struct[str(i)] = Variable.Variable('-', type, None, self.scope) self.heapDict[self.heapNum] = struct self.heapNum += 1 if flag == 1: #assign obj = self.varDicts[-1][name.strip('*')] obj.value = self.heapNum - 1 obj.type = '$P' obj.scope = self.scope else: #declare print('name', name) obj = Variable.Variable( str(name).strip('*'), '$P', self.heapNum - 1, self.scope) self.varDicts[-1][str(name).strip('*')] = obj return self.heapNum - 1
def test_str_prefixe(): # phi, psi, mu : Formule print("TEST D'INSTANCIATIONS DE FORMULES ET DE str_prefixe") phi = Et(Variable("a"), Ou(Variable("b"), Variable("c"))) print("phi =", phi.str_prefixe()) a = Variable("a") b = Variable("b") psi = Non(a) psi = OuEx(a, b) psi = Implique(a, b) psi = Ou(Non(a), b) psi = Non(OuEx(Implique(a, b), Ou(Non(a), b))) print("psi =", psi.str_prefixe()) mu = EquivalentA(Non(top), bot) print("mu =", mu.str_prefixe())
def fromstring(string): # initialise return string lambdastring = '' # collect index pairs for every parenthesis or print error if expression is invalid for s in enumerate(string, start=1): # find parentheses indices try: parentheses_locs = find_parentheses(s) indexpairs = sorted([(k, v) for k, v in parentheses_locs.items()]) # parentheses do not match except IndexError as e: print(str(e)) # check if the expression is valid for i in range(len(string)): if string[i] not in varchars: raise NameError # define indices of the last pair of parentheses (for the 'N' term) # the N-term in the application (M N) has parentheses around the expression as well (i.e. N = (N')) rpair = indexpairs[-1][1] lpair = indexpairs[-1][0] # application if there is a space before left bracket paired with second-to-last right bracket if len(indexpairs) < 2 and string[lpair - 1] == ' ': lambdastring = Application.Application.frstring(string) # abstraction if there is a lambda right after the left parenthesis elif string[lpair + 1] == LambdaTerm.lam: lambdastring = Abstraction.Abstraction.frstring(string) # if it is not an Application nor an Abstraction, it is a Variable; remove the outer brackets first else: lambdastring = Variable.Variable(lambdastring[1:-1]) return lambdastring
def createVariables(): vars = [] for i in range(0, len(widgets)): row = widgets[i] if isinstance(row[0], tk.Entry): vars.append([row[0].get(), []]) else: break for x in range(2, len(row)): if isinstance(row[x], tk.Entry): if row[x].get() == "lambda": vars[i][1].append("\u03BB") else: vars[i][1].append(row[x].get()) ret = [] for x in range(0, len(vars)): ret.append(Variable(vars[x][0], vars[x][1])) return ret
class AlertLimitReached(Event): cache_key_fmt = "stock_alert_%s_%s" identifier = "alert_limit_reached" name = _("Alert Limit Reached") supplier = Variable(_("Supplier"), type=Model("E-Commerce.Supplier")) product = Variable(_("Product"), type=Model("E-Commerce.Product")) supplier_email = Variable(_("Supplier Email"), type=Email, required=False) shop_email = Variable(_("Shop Email"), type=Email, required=False) dispatched_last_24hs = Variable( _("Fired in the last 24 hours?"), type=Boolean, help_text=_( "This will be True if this event was already dispatched " "in the last 24 hours for the same product and supplier. " "This is useful to prevent sending identical notifications in a short " "period of time." ) ) def __init__(self, **variable_values): cache_key = self.cache_key_fmt % (variable_values["supplier"].pk, variable_values["product"].pk) last_dispatch_time = cache.get(cache_key) if last_dispatch_time: last_dispatch = int((time() - last_dispatch_time) / 60 / 60) variable_values["dispatched_last_24hs"] = (last_dispatch < 24) else: variable_values["dispatched_last_24hs"] = False super(AlertLimitReached, self).__init__(**variable_values) def run(self, shop): cache_key = self.cache_key_fmt % (self.variable_values["supplier"].pk, self.variable_values["product"].pk) # do not run this if the last dispatch was < 1 minute last_dispatch_time = cache.get(cache_key) if last_dispatch_time and time() - last_dispatch_time < 60: return cache.set(cache_key, time(), timeout=(60 * 60 * 24)) super(AlertLimitReached, self).run(shop=shop)
def main(): startTime = perf_counter() nAnswers = 0 Qs = Variable() for l1 in queens(11, Qs): nAnswers += 1 finishTime = perf_counter() print("Optimized queens:", (finishTime - startTime), "seconds,", nAnswers, "answers")
def rangeList(M, N, List): if YP.getValue(M) >= YP.getValue(N): for l1 in YP.unify(List, ListPair(N, Atom.NIL)): yield False else: Tail = Variable() for l1 in rangeList(YP.getValue(M) + 1, YP.getValue(N), Tail): for l2 in YP.unify(List, ListPair(M, Tail)): yield False
def main(): startTime = clock() nAnswers = 0 Qs = Variable() for l1 in queens(11, Qs): nAnswers += 1 finishTime = clock() print "Naive queens:", (finishTime - startTime), "seconds,", \ nAnswers, "answers"
def rangeList(M, N, List): if M >= N: for l1 in List.unify(ListPair(N, Atom.NIL)): yield False else: Tail = Variable() for l1 in rangeList(M + 1, N, Tail): for l2 in List.unify(ListPair(M, Tail)): yield False
class OrderStatusChanged(Event): identifier = "order_status_changed" name = _("Order Status Changed") order = Variable(_("Order"), type=Model("E-Commerce.Order")) customer_email = Variable(_("Customer Email"), type=Email) customer_phone = Variable(_("Customer Phone"), type=Phone) shop_email = Variable(_("Shop Email"), type=Email) shop_phone = Variable(_("Shop Phone"), type=Phone) old_status = Variable(_("Old Status"), type=Model("E-Commerce.OrderStatus")) new_status = Variable(_("New Status"), type=Model("E-Commerce.OrderStatus")) language = Variable(_("Language"), type=Language)
def get_constants_variables(self): while True: try: number_of_constants = int(input("How many measured variables: ")) except ValueError as e: print(e) continue break for const in range(number_of_constants): self.known_variables.append(Variable())
def __intepret_defvar(self, arguments, instruction_order): self.__check_instruction_arguments_count(arguments, 1, instruction_order) argument = arguments[1] if argument.get_type() != "var": print("Argument must be type of var in instruction with order " + str(instruction_order), file=sys.stderr) exit(32) self.__check_variable_name(argument) variable = Variable.Variable() variable_name, frame = self.__split_variable(argument.get_value()) variable.set_name(variable_name) self.__memory_manager.add_variable(variable, frame)