class Consultor(object): """Clase que implementa el mecanismo de consultas a la base de conocimientos usando Prolog""" def __init__(self, consulta): self.consultor = Prolog() self.consultor.consult(os.path.join(settings.MEDIA_ROOT, 'colombianCrush.pl').replace('\\','/')) self.consulta = consulta self.resultado = [] def buscarSugerencia(self): """Genera la respuesta a la consulta de una sugerencia de movimiento para el jugador""" return self._validarConsulta(self.consultor.query("buscarSugerencia(X, " + self.consulta + ")")) def buscarPosibilidad(self): """Genera la respuesta a la consulta de una posibilidad de destruccion de figuras""" return self._validarConsulta(self.consultor.query("buscarPosibilidad(X, " + self.consulta + ")")) def _validarConsulta(self, consulta): """Metodo interno que extrae el menor valor obtenido de Prolog al consultar la base de conocimiento""" for valor in consulta: self.resultado.append(valor["X"]) if len(self.resultado)>PASIVO: return min(self.resultado) else: return PASIVO
def exprToType(e: Expression, with_lib=True) -> str: p = Prolog() p.consult('types.pl') builtins = "[" + ",".join([ "[null,arrow(list(X), bool)]", "[hd,arrow(list(Y), Y)]", "[tl,arrow(list(Z), list(Z))]", ]) + "]" if (with_lib): withLib = Let("map", fileToNano("nano/tests/map.ml"), Let("foldl", fileToNano("nano/tests/foldl.ml"), e)) else: withLib = e ast = withLib.toProlog() results = list(p.query("typeof(%s,%s,T)" % (builtins, ast))) if (len(results) < 1): print("Type error for: %s" % str(e)) return "Type Error" else: # print("Typed to %s" % results[0]['T']) return results[0]['T']
def manejador(): if request.method == "POST": json = request.get_json() peticion = json["queryResult"]["queryText"] palabras = peticion.split() respuesta = "" if palabras[0].lower() == "cursos" or palabras[0].lower() == "curso": if palabras[1] in CATEGORIAS: p = Prolog() p.consult("cursos.pl") for solution in p.query("curso(X,Y,Z," + palabras[1] + ")"): respuesta += "curso: " + solution[ "X"] + " instuctor: " + solution[ "Y"] + " plataforma: " + solution["Z"] + "\n" else: respuesta = "no se encontro la categoria" else: p = Prolog() p.consult("cursos.pl") query = "" query += palabras[0] + "(" if len(palabras[1:]) >= 1: for palabra in palabras[1:]: query += palabra + "," query += query[:-1] + ")" for solution in p.query(query): for var in solution: respuesta += " var: " + var respuesta += "\n" else: respuesta = "No entendi tu pregunta, trata escribiendo \"cursos\" y una categoria" return jsonify({"fulfillmentText": respuesta}) return "hi"
class PrologDecisionModule: def __init__(self): self.prolog = Prolog() prolog_path = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'model/prolog')) self.prolog.consult(os.path.join(prolog_path, 'load.pl')) def start_game(self): init_pos = list(self.prolog.query("init_state")) def humanOffer(self, offer, emoFace, emoVoice): response = list( self.prolog.query( "humanOffers({}, {}, {}, RobotOffer, RobotDecision)".format( offer, emoFace, emoVoice)))[0] info = { "offer": response["RobotOffer"], "decision": "accepted" if response["RobotDecision"] > 0 else "declined" } return info def humanDecides(self, agreed): decision = "yes" if agreed else "no" response = list(self.prolog.query( "humanDecides({})".format(decision)))[0]
class Connector: def __init__(self, file): self.file = file self.prolog = Prolog() self.board = None self.prolog.consult(file) def setBoard(self,board): tranformedBoard = [] for i in board: for j in i: tranformedBoard.append(j) self.board = tranformedBoard def addRule(self, rule): self.prolog.assertz(rule) def command(self, cmd): return self.prolog.query(cmd) def getMove(self, direction): if direction == 'up': return list(self.prolog.query('move(' + str(self.board) + ',u, New)')) elif direction == 'down': return list(self.prolog.query('move(' + str(self.board) + ',d, New)')) elif direction == 'left': return list(self.prolog.query('move(' + str(self.board) + ',l, New)')) elif direction == 'right': return list(self.prolog.query('move(' + str(self.board) + ',r, New)')) def aiMove(self, board, depth): self.setBoard(board) return list( self.prolog.query('aigame(' + str(self.board) + ',' + str(depth) + ',Move)'))
class ConnectProlog(ConnectLivestatus): """As it is senseless to call Prolog without starting a connection to Nagios/Icinga, this module does it.""" def __init__(self): prolog=None ConnectLivestatus.__init__(self) self.prolog=Prolog() self.prolog.consult('vanyad.pl')
def load_knowledge(): prolog = Prolog() current_dir = os.path.dirname(os.path.realpath(__file__)) kb_path = os.path.join(current_dir, 'kb/kb.pl') print(f'Loading knowledge base: {kb_path}') prolog.consult(kb_path) return prolog
def prolog_query(query_string): prolog = Prolog() prolog.consult("knowledge.pl") results = [] for res in prolog.query(query_string): results.append(res) return results
def moveBlack(move): global chessTable if move == 'O-O': chessTable = makemove(5, 8, 7, 8) chessTable = makemove(8, 8, 6, 8) return True if move == 'O-O-O': chessTable = makemove(5, 8, 3, 8) chessTable = makemove(1, 8, 4, 8) return True player = 2 Piece, FromColumn, FromRow, ToRow, ToColumn, eat = generateQuery(move, player % 2) step = generateStep(Piece, player, FromRow, FromColumn, ToRow, ToColumn) string = "problem(Answer, " + str.lower(str(Piece)) + ", " + str(vectorTable(chessTable)) + ", " + str( FromColumn) + ", " + str(FromRow) + ", " + str(ToColumn) + ", " + str(ToRow) + ", " + str(step) + ", " + str( str.lower(str(eat)[0])) + ")" prolog = Prolog() prolog.consult("test.pl") print(move) print(Piece, FromRow, FromColumn, ToRow, ToColumn) print(string) if bool(list(prolog.query(string))[0]['Answer']) or list(prolog.query(string))[0]['Answer'][0] == '_': chessTable = makemove(FromColumn, FromRow, ToRow, ToColumn) print('true') print() print() return bool(list(prolog.query(string))[0]['Answer'])
def getrecetaTipo(): #se consuige la informacin del JSON de entrada request_data = request.get_json() nombreIn = request_data['nombre'] tipoIn = request_data['tipo'] pasosIn = request_data['pasos'] ingredienteIn = request_data['ingredientes'] fotoIn = request_data['foto'] listaJson = [] prolog = Prolog() prolog.consult("conocimientos.pl") for soln in prolog.query("receta(A," + tipoIn + ",C,D,E)"): listaPasos = "" listaIngredientes = "" for paso in soln["C"]: listaPasos += paso.value + "," for ingrediente in soln["D"]: listaIngredientes += ingrediente.value + "," listaJson.append({ "nombre": soln["A"], "tipo": tipoIn, "pasos": listaPasos, "ingredientes": listaIngredientes, "foto": soln["E"][0].value }) #listaJson.append(jsonify(nombre=soln["A"],tipo = soln["B"],pasos = soln["C"][0].value,ingredientes = soln["D"][0].value,foto=soln["E"][0].value)) return Response(json.dumps(listaJson), mimetype='application/json')
def get_advice(board, player): prolog = Prolog() prolog.consult(KnowledgeBase.PATH) moves = [(soln['X'], soln['Y'], soln['PredName']) for soln in prolog.query( KnowledgeBase.GIVE_PLAYER_ADVICE_PREDICATE.format(player, board))] return moves
def autoexit(self, node): #exit at nearest exit (use prolog) if(node not in self.unavaible_park): return [] heuristic_exit_list = [] heuristic_list = [] exit_node = 0 heuristic_list = self.graph.getHeuristic(node + 1) for i in heuristic_list: if (int(i.split(':')[0][1:])-1 in self.exit): heuristic_exit_list.append(i) f = open("exit.pl","w") fact_list = "" for fact in heuristic_exit_list: fact_buffer = fact.split(':') if(int(fact_buffer[0][1:]) - 1 in self.exit): fact_list += ('exit(' + fact_buffer[0] + ',' + fact_buffer[1] + ').\n') f.write(fact_list) f.close() if fact_list == "": return [] p = Prolog() p.consult("exit.pl") p.consult("utility.pl") result = p.query("exitnode(" + str(['n' + str(x+1) for x in self.exit]).replace('\'',"") + ",Result).") exit_node = str(list(result)[0]['Result']) self.avaible_park.append(node) self.unavaible_park.remove(node) path_list = self.getPath(node ,int(exit_node[1:]) - 1,'exit') return path_list
def getreceta(): listaJson = [] prolog = Prolog() #se consulta la base de conocimientos de prologStatement prolog.consult("conocimientos.pl") for soln in prolog.query("receta(A,B,C,D,E)"): listaPasos = "" listaIngredientes = "" listaFotos = "" for paso in soln["C"]: listaPasos += paso.value + "," for ingrediente in soln["D"]: listaIngredientes += ingrediente.value + "," for foto in soln["E"]: listaFotos += foto.value + "," listaJson.append({ "nombre": soln["A"], "tipo": soln["B"], "pasos": listaPasos, "ingredientes": listaIngredientes, "foto": listaFotos }) #listaJson.append(jsonify(nombre=soln["A"],tipo = soln["B"],pasos = soln["C"][0].value,ingredientes = soln["D"][0].value,foto=soln["E"][0].value)) return Response(json.dumps(listaJson), mimetype='application/json')
def checkWin(self, joueur): if(self.plateau.count(0) < 18): prolog=Prolog() prolog.consult("ia/minmax.pl") if list(prolog.query("joueurGagnant(" + str(self.plateau) + ","+str(joueur._id)+")")): return True return False
class GamePL(object): def __init__(self): self.prolog = Prolog() self.prolog.consult("pl/GameDatabase.pl") self.prolog.consult("pl/GameLogic.pl") def nuevoJugador(self, name): None def actualizaPuntuacion(self, jugador, puntos): None def borrarMemoria(self): None def getPuntuacion(self, jugador): None def getCategorias(self): return self.prolog.query("categoria(Categoria, Descripcion)") def getPreguntas(self): return self.prolog.query("pregunta(Numero, Pregunta, Categoria, Puntos)") def getRespuestas(self): return self.prolog.query("respuesta(Numero, Respuesta)")
def pathplan(start, end): prolog = Prolog() prolog.consult('a_star_4.0.pl') startlist = start.split('+') len_start = len(startlist) endlist = end.split('+') len_end = len(endlist) if len_start == 3 and len_end == 3: qqq = "once(path_plan1(" + startlist[0] + "," + startlist[ 1] + "," + startlist[2] + "," + endlist[0] + "," + endlist[ 1] + "," + endlist[2] + ",Coorlist))" for result in prolog.query(qqq): path = result["Coorlist"] print path elif len_start == 3 and len_end == 1 and end == 'last_starter': qqq = "once(path_plan3(" + startlist[0] + "," + startlist[ 1] + "," + startlist[2] + ",last_starter,Coorlist))" for result in prolog.query(qqq): path = result["Coorlist"] print path else: qqq = "once(path_plan2(" + startlist[0] + "," + startlist[ 1] + "," + startlist[2] + "," + end + ",Coorlist))" for result in prolog.query(qqq): path = result["Coorlist"] print path
def symptoms(self, answers): questions = [ "¿Tiene tos? (y/n)", "¿Tiene escalofrios? (y/n)", "¿Ha tenido diarrea? (y/n)", "¿Tiene dolor de garganta? (y/n)", "¿Ha tenido dolores musculares? (y/n)", "¿Tiene dolor de cabeza? (y/n)", "¿Ha tenido fiebre de 38° o mas? (y/n)", "¿Ha tenido dificultad para respirar? (y/n)", "¿Ha sentido cansancio/debilidad? (y/n)", "¿Ha viajado en los ultimos 14 dias? (y/n)", "¿Ha visitado areas infectadas por Covid 19? (y/n)", "¿Visitó o ha cuidado pacientes con Covid 19? (y/n)", ] p = Prolog() p.consult("knowledge_base.pl") pts = [] suma = 0 for x in range(0, len(questions)): q = "puntos(Pts, '" + questions[x] + "' , " + answers[x] + ")" pts = list(p.query(q)) suma += pts[0]["Pts"] q = "sugerencia(Variable, " + str(suma) + ")" return list(p.query(q))
class KnowledgeBase: def __init__(self, file_path="kb.pl"): self.prolog = Prolog() self.prolog.consult(file_path) def Pick(self, occupation: str, age: int, prev_accidents: int, car_model: int) -> Set[Tuple[int, str, str, int, float, str]]: INSURANCE_ID, INSURANCE_TYPE, INSURANCE_COVERAGE, \ INSURANCE_DURATION, INSURANCE_PRICE, INSURANCE_PRICE_RANGE = \ Variable(), Variable(), Variable(), Variable(), Variable(), Variable() fpick = Functor("pick", 10) query = Query( fpick(occupation, age, prev_accidents, car_model, INSURANCE_ID, INSURANCE_TYPE, INSURANCE_COVERAGE, INSURANCE_DURATION, INSURANCE_PRICE, INSURANCE_PRICE_RANGE)) results = set() while query.nextSolution(): results.add( (INSURANCE_ID.value, str(INSURANCE_TYPE.value), str(INSURANCE_COVERAGE.value), INSURANCE_DURATION.value, INSURANCE_PRICE.value, str(INSURANCE_PRICE_RANGE.value))) query.closeQuery() return results
def build_model(self, examples): pl = Prolog() pl.consult(self.subtle_path) pl.consult(self.glgg_path) for example in examples: pl.assertz(example[:-1]) return pl
def queryWhatWeKnow(prologFile): prolog = Prolog() prolog.consult(prologFile) variables = ['X','Y','Z','W','A','B'] varCount = 0 varDict = {} print("Reading in knowledge from " + prologFile + "...") curQuery = raw_input("Please input the sentence (no punctuation) you want the logical form for (enter nothing to quit):\n") while(curQuery != ''): sent = curQuery.strip().split() result = prolog.query('s(X,' + str(sent) + ',[]),beta_reduce(X,Z)') try: curRes = dict(list(result)[0])["Z"] except IndexError: print("This information is not present in knowledge file\n") else: tmpVars = curRes.split('G') for curVar in range(1, len(tmpVars)): curVar = '_G' + tmpVars[curVar][:3] if(curVar not in varDict): varDict[curVar] = variables[varCount] varCount +=1 for repVar in varDict: curRes = curRes.replace(repVar, varDict[repVar]) print("The logical form of \"" + curQuery + "\" is " + curRes + "\n") curQuery = raw_input("Please input the sentence (no punctuation) you want the logical form for (enter nothing to quit):\n")
def query_prolog(): print("I am working ###################################") prolog = Prolog() prolog.consult("prolog/main.pl") for res in prolog.query("once(dispatcher(Schedule, Tardiness))"): parse_graph(res['Schedule'])
def can_win_in_one_move(board, player='x'): prolog = Prolog() prolog.consult(os.path.join('..', KnowledgeBase.PATH)) moves = [(soln['X'], soln['Y']) for soln in prolog.query( KnowledgeBase.CAN_WIN_IN_ONE_MOVE_PREDICATE.format(player, board))] return moves
def implications_prolog(self, requirements, base_req, restaurants): """ Makes a Prolog query based on the requirements of the user. Returns the corresponding restaurants as a pandas array, like in extract_info. @param requirements: list of requirements that should hold. These correspond to the Prolog functors' syntax, apart from the spaces. @param base_req: list containing the three basic requirements: area, foodtype and pricerange. May be partial/empty. @param restaurants: Pandas array containing all restaurants still under consideration. """ prolog = Prolog() prolog.consult("data/implications.pl") # Let's build a query that Prolog can understand prolog_query = ''.join([fact + "(X)," for fact in base_req]) prolog_query += "(X),".join(requirements) + "(X)." prolog_query = prolog_query.replace(' ', '_') # Send to Prolog! answer = list(prolog.query(prolog_query)) # We only used one variable answer = [x['X'] for x in answer] # Capitalize and replace underscores by spaces answer = [' '.join([word.capitalize() for word in x.split('_')]) for x in answer] return restaurants.loc[restaurants["restaurantname"].isin(answer)]
def index(request, table): import MySQLdb as db conn = db.connect(host='localhost', user='******', passwd='prologpass', db='prolog_test') cursor = conn.cursor() cursor.execute('SELECT * FROM `children`') result = cursor.fetchall() prolog = Prolog() for row in result: prolog.assertz("father("+ row[1] +","+ row[2] +")") prolog.consult('family') prolog.assertz("father(michael,john)") prolog.assertz("father(michael,gina)") father = list(prolog.query("father(Y, X)")) #return HttpResponse(response, mimetype="application/xml") t = loader.get_template('index/select.html') c = RequestContext(request, {'table': table, 'father': father}) return HttpResponse( t.render(c), mimetype="application/xml" )
def read_specification(): prolog = Prolog() prolog.consult("9. main.pl") if os.path.exists("RuleML.json"): os.remove("RuleML.json") s0 = 'start()' for y in list(prolog.query(s0)): print('start') str3 = "" file = open("specification.txt", "r") for line in file: str1 = "readt([['" + line + "']])" print(str1) for y in list(prolog.query(str1)): print('yes') str1 = "" str2 = "" str3 = "" s1 = 'end()' for y in list(prolog.query(s1)): print('end') if os.path.exists("lexicon.pl"): os.remove("lexicon.pl") s2 = 'store_lexicon(lexicon)' for y in list(prolog.query(s2)): print(y) file.close()
def opponent_can_build_double_3_threat(board, player='o'): prolog = Prolog() prolog.consult(os.path.join('..', KnowledgeBase.PATH)) moves = [(soln['X'], soln['Y']) for soln in prolog.query(KnowledgeBase.OPPONENT_CAN_BUILD_DOUBLE_3_THREAD_PREDICATE .format(player, board))] return moves
def park(self, node): #park nearest exit (use prolog) if (self.avaible_park == []): return [] heuristic_exit_list = [] park_node = 0 for i in self.exit: heuristic_exit_list += self.graph.getHeuristic(i + 1) f = open("park.pl", "w") fact_list = "" for fact in heuristic_exit_list: fact_buffer = fact.split(':') if (int(fact_buffer[0][1:]) - 1 in self.avaible_park): fact_list += ('park(' + fact_buffer[0] + ',' + fact_buffer[1] + ').\n') f.write(fact_list) f.close() if fact_list == "": return [] p = Prolog() p.consult("park.pl") p.consult("utility.pl") result = p.query("parknode(" + str(['n' + str(x + 1) for x in self.avaible_park]).replace('\'', "") + ",Result).") park_node = str(list(result)[0]['Result']) #update avaible and unavbaible park list path_list = self.getPath(node, int(park_node[1:]) - 1, 'enter') self.avaible_park.remove(int(park_node[1:]) - 1) self.unavaible_park.append(int(park_node[1:]) - 1) return path_list
class PrologWrapper(): def __init__(self, fileName = "MainLP.pl"): self.__fileName = fileName pathFile = "{}/NLID/KernelModule/{}".format(os.getcwd(), fileName) self.__prologModule = Prolog() self.__prologModule.consult(pathFile) """ @detalii: interact will execute the entryPoint in prolog script @parameters: None @returns: results(dict) - result of the prolog """ def interact(self): result = self.__prologModule.query("entryPoint(OutputDict)") result = list(result)[0]['OutputDict'] dictResult = {} values = re.findall(r"\'[^\']*\'", result) keys = re.findall(r"\[([A-Za-z0-9_]+)\]", result) for i in range(len(keys)): # add error value if keys[i].startswith("ERROR_"): dictResult[keys[i]] = "{}/{}".format(ERROR_CODES[keys[i]], values[i][1:]) dictResult[keys[i]] = values[i][1:-1] return dictResult def rawInteract(self): result = self.__prologModule.query("entryPoint(OutputDict)") result = list(result)[0]['OutputDict'] return result
def do_GET(self): prolog = Prolog() prolog.consult('familia.pl') self.send_response(200) self.end_headers() lista = list(prolog.query("familiarde(X,Y)")) myjson = json.dumps(lista) self.wfile.write(bytes(myjson, "utf-8"))
def opponentCanWinInOneMove(board, player='o'): prolog = Prolog() prolog.consult(os.path.join('..', KnowledgeBase.PATH)) moves = [(soln['X'], soln['Y']) for soln in prolog.query( KnowledgeBase.OPPONENT_CAN_WIN_IN_ONE_MOVE_PREDICATE.format( player, board))] return moves
def get_best_price(): SubDistrict = request.json['sub_district'] CurrentMonth = time.localtime(time.time()).tm_mon prolog = Prolog() prolog.consult('src/engine.pl') rule = "bestPriceRice(Rice, RiceType, SellPlace, "+SubDistrict+", Humidity, Price, PhotoPeriod, HarvestingSeason, "+str(CurrentMonth)+")" re_list = list(prolog.query(rule)) return jsonify(re_list)
def get_schema(): prolog = Prolog() prolog.consult('engine.pl') prolog.assertz('raining("Bangkok")') rule = "can_growing(P1, 'GROW1')." re_list = list(prolog.query(rule)) # return "hello" return jsonify(re_list)
def opponentCanBuildFree4(board, player='o'): prolog = Prolog() prolog.consult(os.path.join('..', KnowledgeBase.PATH)) moves = [(soln['X'], soln['Y']) for soln in prolog.query( KnowledgeBase.OPPONENT_CAN_BUILD_FREE_4_PREDICATE.format( player, board))] return moves
def canBuildDouble3Threat(board, player='x'): prolog = Prolog() prolog.consult(os.path.join('..', KnowledgeBase.PATH)) moves = [(soln['X'], soln['Y']) for soln in prolog.query( KnowledgeBase.CAN_BUILD_DOUBLE_3_THREAD_PREDICATE.format( player, board))] return moves
def test_swipl(self): from pyswip import Prolog from reloop.languages.rlp.logkb import PrologKB prolog = Prolog() prolog.consult("../examples/RLP/maxflow_swipl.pl") logkb = PrologKB(prolog) # BlockGrounding not supported yet grounder = RecursiveGrounder(logkb) solver = CvxoptSolver() model = maxflow_example.maxflow(grounder, solver) self.assertEqual(model, 0, "SWI-Prolog Recursive Failed")
def main(): letters = "S E N D M O R Y".split() prolog = Prolog() sendmore = Functor("sendmore") prolog.consult("money.pl") X = Variable() call(sendmore(X)) r = X.value for i, letter in enumerate(letters): print(letter, "=", r[i]) print("That's all...")
def query_hyp_in_event_db(hyp, event_db_file): prolog = Prolog() str2num_file = '/home/csunix/visdata/cofriend/sandeep/Dropbox/code/my_code/trunk/python/cofriend/str2num.pl' prolog.consult(str2num_file) print 'Reading event database ...' all_prolog_modules = pickle.load(open(event_db_file)) (modeh, modeb) = all_prolog_modules['modes'] pos_ex = all_prolog_modules['pos_ex'] test_pos_ex = all_prolog_modules['test_pos_ex'] pos_prolog_modules = all_prolog_modules['pos'] neg_prolog_modules = all_prolog_modules['neg'] test_prolog_modules = all_prolog_modules['test'] pos_event_dbs = [] neg_event_dbs = [] print 'Asserting pos prolog modules ...' for vid in pos_prolog_modules: for i in xrange(len(pos_prolog_modules[vid])): pos_prolog_module = pos_prolog_modules[vid][i][0] pos_prolog_blanket = pos_prolog_modules[vid][i][1] pos_event_dbs.append(pos_prolog_module) assert_blanket_to_prolog_str_int(pos_prolog_blanket, prolog, pos_prolog_module) print 'Asserting neg prolog modules ...' for vid in neg_prolog_modules: for i in xrange(len(neg_prolog_modules[vid])): neg_prolog_module = neg_prolog_modules[vid][i][0] neg_prolog_blanket = neg_prolog_modules[vid][i][1] neg_event_dbs.append(neg_prolog_module) assert_blanket_to_prolog_str_int(neg_prolog_blanket, prolog, neg_prolog_module) print 'num of pos: ' + repr(len(pos_event_dbs)) print 'num of neg: ' + repr(len(neg_event_dbs)) print 'Querying in pos prolog modules ...' t0 = time.clock() print time.asctime() for i in xrange(100000): pos_cover = hyp.pyswip_covers(prolog, pos_event_dbs, True, False, neg=0) print time.asctime() pos_eval_time = (time.clock() - t0) print 'Querying in neg prolog modules ...' t0 = time.clock() print time.asctime() for i in xrange(100000): neg_cover = hyp.pyswip_covers(prolog, neg_event_dbs, True, False, neg=1) print time.asctime() neg_eval_time = (time.clock() - t0) print pos_eval_time print neg_eval_time
def test_issue_Unicode_consult(self): """ Unicode support """ from pyswip import Prolog Prolog.consult('unicode.pl') result = list(Prolog.query('мать(Мать,Ребенок)')) k = len(result) self.assertEqual(k, 2) result = list(Prolog.query('дочь(света,саша)')) self.assertEqual(result, []) result = list(Prolog.query('дочь(света,аня)')) self.assertNotEqual(result, [])
def query_hyp_in_video_db(hyps, video_db): prolog = Prolog() str2num_file = '/home/csunix/visdata/cofriend/sandeep/Dropbox/code/my_code/trunk/python/cofriend/str2num.pl' prolog.consult(str2num_file) print 'Asserting the database ...' assert_blanket_to_prolog_str_int(video_db, prolog, 'vid_db') result = {} for event in hyps: result[event] = [] print 'Querying in the video for event: ' + event for hyp in hyps[event]: pos_cover = hyp.pyswip_covers(prolog, [('vid_db',video_db)], True, False, neg=0) result[event].append(pos_cover) return result
def main(): prolog = Prolog() prolog.consult("coins.pl") count = int(input("How many coins (default: 100)? ") or 100) total = int(input("What should be the total (default: 500)? ") or 500) coins = Functor("coins", 3) S = Variable() q = Query(coins(S, count, total)) i = 0 while q.nextSolution(): ## [1,5,10,50,100] s = zip(S.value, [1, 5, 10, 50, 100]) print(i, end=" ") for c, v in s: print("%dx%d" % (c,v), end=" ") print() i += 1 q.closeQuery()
def main(): mod = sys.argv[1] what = sys.argv[2] who = sys.argv[3] find = False prolog = Prolog() prolog.consult(mod) for soln in prolog.query("%s(X,%s)" % (what, who)): if what == 'pere' : print soln["X"], "est le %s de %s" % (what, who) else : print soln["X"], "est la %s de %s" % (what, who) find = True if not find: print "Je suis désolé, je ne dispose pas des informations requise pour vous répondre. Souhaitez-vous que jeffectue une recherche sur Internet"
def solveSudoku(sudokuString): print "in solve" answerString = "" prolog = Prolog() prolog.consult('sudokusolver.pl') queryString = "Puzzle = [" + sudokuString + "], Puzzle = [A,B,C,D,E,F,G,H,I], sudoku([A,B,C,D,E,F,G,H,I]). " #queryString = queryS res = list(prolog.query(queryString, maxresult=1)) print res if not res: #results is empty return "Invalid Sudoku" else: final = [] cols = ["A","B","C","D","E","F","G","H","I"] for col in cols: final.append(" ".join(map( str,res[0][col]))) return "<br>".join(final)
class Bridge: def __init__(self): self.prolog = Prolog() self.prolog.consult('facts.pl') self.prolog.consult('logic/agent.pl') def best_action(self): actions = list(self.prolog.query('best_action(Action, Arg1, Arg2)', maxresult=1)) if len(actions) > 0: return actions[0] else: return None def assertz(self, what): return list(self.prolog.query("assertz(%s)" % what)) def retract(self, what): return list(self.prolog.query("retract(%s)" % what)) def retractall(self, what): return list(self.prolog.query("retractall(%s)" % what)) def assert_perceptions(self, perceptions, x, y): for p in perceptions.keys(): self.retract("percept_%s(%d, %d)" % (p, x, y)) if perceptions[p] == True: self.assertz("percept_%s(%d, %d)" % (p, x, y)) def assert_on(self, x, y): self.retractall('on(X, Y)') self.retract('visited(%d, %d)' % (x, y)) self.assertz('on(%d, %d)' % (x, y)) self.assertz('visited(%d, %d)' % (x, y)) self.retract('connex(%d, %d)' % (x, y)) self.assertz('connex(%d, %d)' % (x, y)) def assert_energy(self, e): self.retractall('energy(E)') self.assertz('energy(%d)' % e) def assert_attacked(self, x, y): self.assertz('attacked(%d, %d)' % (x, y))
def index(): bs = BaseHandler() dt = None sol2 = None error = None form = HelpForm() if form.validate_on_submit(): bsg = bs.big_suggest(str(form.quiz.data)) sol2 = bs.find_elements(bsg) try: from pyswip import Prolog prolog = Prolog() prolog.consult("kb.txt") # prolog.assertz("father(michael,gina)") # prolog.assertz("father(michael,john)") dt = list(prolog.query("elements(X)")) # sol2 = list(prolog.query("battery(hot,X)")) except Exception,e: error = e traceback.print_exc()
def find_elements(self,long_string): elements = [] solution = [] arr = long_string.strip().split(" ") arr_len = len(arr) from pyswip import Prolog prolog = Prolog() prolog.consult("kb.txt") for x in xrange(arr_len): q = list(prolog.query("elements(%s)"%arr[x])) if len(q) > 0: s = list(prolog.query("problem(%s,X)"%arr[x])) kw = [x['X'] for x in s] for k in kw: if arr.__contains__(k): solution.append(list(prolog.query("solution(%s,Y)"%k))) for h in solution: if len(h) > 0: for j in h: elements.append(j['Y']) return elements
def pathplan(start,end): prolog = Prolog() prolog.consult('a_star_4.0.pl') startlist=start.split('+') len_start=len(startlist) endlist=end.split('+') len_end=len(endlist) if len_start==3 and len_end==3 : qqq = "once(path_plan1(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ "," + endlist[0] + "," + endlist[1]+ "," + endlist[2] + ",Coorlist))" for result in prolog.query(qqq): path = result["Coorlist"] print path elif len_start==3 and len_end==1 and end=='last_starter' : qqq = "once(path_plan3(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ ",last_starter,Coorlist))" for result in prolog.query(qqq): path = result["Coorlist"] print path else : qqq = "once(path_plan2(" + startlist[0] + "," + startlist[1]+ "," + startlist[2]+ "," + end + ",Coorlist))" for result in prolog.query(qqq): path = result["Coorlist"] print path
from pyswip import Prolog #Importa libreria para crear puente de python-prolog prolog=Prolog()#Puente entre python-prolog prolog.consult("progra.pl")#Consulta la base de conocimientos def convertir_underscore(palabra): nueva="" for letra in palabra: if letra=="_": nueva=nueva+" " else: nueva=nueva+letra return nueva def convertir_espacios(palabra): nueva="" for letra in palabra: if letra==" ": nueva=nueva+"_" else: nueva=nueva+letra return nueva def buscar_restaurante(nombre): nombre=convertir_espacios(nombre) restaurante=list(prolog.query("restaurante("+nombre+",Tipo,Ubicacion)")) print restaurante,"\n" def buscar_restaurante_tipo(tipo): tipo=convertir_espacios(tipo) restaurante_tipo=list(prolog.query("restaurante(Nombre,"+tipo+",Ubicacion)")) print restaurante_tipo,"\n"
def question_finder(question, ans): p = Prolog() p.consult('/home/jordanhudgens/code/coderprofile/survey/knowledgebase.pl') # When placed on server, be sure to change this path!!!! # Question 1: Type of Projects Desired to Learn if question == "What type of projects do you want to learn how to build?": p.dynamic('projectdesired/1') ## To account for going back p.retractall('projectdesired(_)') ## To account for going back if ans == "iPhone App": p.assertz('projectdesired(iphoneapp)') if ans == "Android App": p.assertz('projectdesired(androidapp)') if ans == "Web Application": p.assertz('projectdesired(webapp)') if ans == "Front End Website Development": p.assertz('projectdesired(frontend)') if ans == "just programming": p.assertz('projectdesired(generalprogramming)') # Question 2: Budget if question == "What is your budget?": p.dynamic('budget/1') ## To account for going back p.retractall('budget(_)') ## To account for going back if ans == "$0": p.assertz('budget(0)') if ans == "$50-$250": p.assertz('budget(250)') if ans == "$251-$500": p.assertz('budget(500)') if ans == "$501-$1000": p.assertz('budget(1000)') if ans == "$1001-$1500": p.assertz('budget(1500)') if ans == "$1501+": p.assertz('budget(1000000)') # Question 3: Level of Education if question == "What is the highest level of education you've completed?": p.dynamic('education/1') ## To account for going back p.retractall('education(_)') ## To account for going back if ans == "High School": p.assertz('education(highschool)') if ans == "Associates": p.assertz('education(associates)') if ans == "Bachelors": p.assertz('education(bachelors)') if ans == "Graduate": p.assertz('education(graduate)') # Question 4: Programming Experience if question == "What programming experience do you have?": p.dynamic('experience/1') ## To account for going back p.retractall('experience(_)') ## To account for going back if ans == "None": p.assertz('experience(none)') if ans == "Low": p.assertz('experience(low)') if ans == "Intermediate": p.assertz('experience(intermediate)') if ans == "Extensive": p.assertz('experience(extensive)') # Question 5: Learning Priority if question == "What's more of a priority for you to learn?": p.dynamic('priority/1') ## To account for going back p.retractall('priority(_)') ## To account for going back if ans == "Theory of coding": p.assertz('priority(theory)') if ans == "Real life projects": p.assertz('priority(practical)') # Question 6: Employment Status if question == "Are you currently employed full time?": p.dynamic('employment/1') ## To account for going back p.retractall('employment(_)') ## To account for going back if ans == "Yes": p.assertz('employment(fulltime)') if ans == "No": p.assertz('employment(none)') # Question 7: Weekly Time Dedication if question == "How many hours can you dedicate to learning each week?": p.dynamic('hoursfree/1') ## To account for going back p.retractall('hoursfree(_)') ## To account for going back if ans == "5": p.assertz('hoursfree(5)') if ans == "6-10": p.assertz('hoursfree(10)') if ans == "11-20": p.assertz('hoursfree(20)') if ans == "21-30": p.assertz('hoursfree(30)') if ans == "31-40": p.assertz('hoursfree(40)') if ans == "40+": p.assertz('hoursfree(168)') # Question 8: Feature Driven Developer if question == "Do you like to see the potential features you're going to build before learning how to implement them?": p.dynamic('featuredriven/1') ## To account for going back p.retractall('featuredriven(_)') ## To account for going back if ans == "Yes (I prefer to watch first)": p.assertz('featuredriven(true)') if ans == "No (I want to start coding right away)": p.assertz('featuredriven(false)') # Question 9: Mentor Driven Developer if question == "Do you like working out problems with experts or do you prefer working out issues on your own?": p.dynamic('mentor/1') ## To account for going back p.retractall('mentor(_)') ## To account for going back if ans == "I would prefer to work with an expert": p.assertz('mentor(mentordriven)') if ans == "I like working issues out on my own": p.assertz('mentor(notmentordriven)') # Question 10: Audience if question == "What type of audience do you want to develop for? I want to build: ": p.dynamic('targetaudience/1') ## To account for going back p.retractall('targetaudience(_)') ## To account for going back if ans == "Business applications": p.assertz('targetaudience(business)') if ans == "Games": p.assertz('targetaudience(games)') if ans == "Social apps": p.assertz('targetaudience(socialapps)') if ans == "eCommerce": p.assertz('targetaudience(ecommerce)') if ans == "No audience - just programming theory": p.assertz('targetaudience(programmingtheory)') # Question 11: Competitive if question == "Does testing your coding skills against other developers appeal to you?": p.dynamic('competitive/1') ## To account for going back p.retractall('competitive(_)') ## To account for going back if ans == "Yes": p.assertz('competitive(iscompetitive)') if ans == "No": p.assertz('competitive(notcompetitive)') # Question 12: High Speed Internet Status if question == "Do you have access to high speed internet?": p.dynamic('highspeedinternet/1') ## To account for going back p.retractall('highspeedinternet(_)') ## To account for going back if ans == "Yes": p.assertz('highspeedinternet(highspeed)') if ans == "No": p.assertz('highspeedinternet(lowspeed)') # Question 13: Code Motivation if question == "Why do you want to learn to code?": p.dynamic('motivation/1') ## To account for going back p.retractall('motivation(_)') ## To account for going back if ans == "Build my own project": p.assertz('motivation(project)') if ans == "Learn a new hobby": p.assertz('motivation(hobby)') if ans == "Improve for my current job": p.assertz('motivation(job)') # Question 14: Machine Type if question == "What type of computer do you have to work on?": p.dynamic('machine/1') ## To account for going back p.retractall('machine(_)') ## To account for going back if ans == "Mac": p.assertz('machine(mac)') if ans == "Windows": p.assertz('machine(windows)') if ans == "Linux": p.assertz('machine(linux)') # Question 15: Timeframe for Learning if question == "What is your timeframe?": p.dynamic('timeframe/1') ## To account for going back p.retractall('timeframe(_)') ## To account for going back if ans == "< 30 days": p.assertz('timeframe(30)') if ans == "31-90 days": p.assertz('timeframe(90)') if ans == "91+ days": p.assertz('timeframe(365)')
from pyswip import Prolog import cgi, cgitb prolog = Prolog() prolog.consult("../data/mod2.pl") prolog.assertz("variety(tkm12,rice)") result = prolog.query("season(When),days(Give),avgyield(Gives),feat(With),places(Where)").next() print "Content-type: text/html\n\n"; print '<html>'; print '<head>'; print '<meta name="author" content="Kay Vogelgesang">'; print '<link href="/xampp/xampp.css" rel="stylesheet" type="text/css">'; print '</head>'; print "<body>" print "%s." % result["When"] print "%s" %result["Give"] print "%s." % result["Gives"] print "%s." % result["With"] print "%s." % result["Where"] print "</body></html>";
if args.module: module = args.module else: module = 'cosmos' #raise "Required --module flag." #Prolog Query i = 0 if args.n: n = int(args.n) else: n = float('inf') #p.consult(module+'.pl') p.consult('cosmos.pl') pl_query = None if args.q: q = args.q query = p.query("cosmos_env(T),catch(cosmos_run_query(T,\""+q+"\",X,_,\""+module+'\",_),E,X=E)') answer=next(query) pl_query = answer['X'] else: q = 'main(x)' # run cosmos file if args.f: filename = args.f s='cosmos_env(T),catch(cosmos_run_file(T,"'+filename+'",X),E,X=E)' print(s) query = p.query(s)
class ManejoProlog: #Definición de la función constructora. #E: dirección del código de prolog. #S: ninguna #R: ninguna def __init__(self, texto): try: #Validación de que archivo exista. archivo = open(texto, "r") archivo.close self.direccion = texto #Se define el atributo con la dirección del código de prolog. self.cargarConocimientos() #Se cargan los conocimientos del código. self.error = False except: archivo = open("Recetas.pl", "w") #Creación de uno nuevo. archivo.write("buscarIngrediente(Nombre,Ingrediente) :- receta(Nombre,Y,Z), recetaIngrediente(Nombre,Ingrediente).\nbuscarPaso(Nombre,Paso) :- receta(Nombre,Y,Z), recetaPaso(Nombre,Paso).\nbuscarReceta(V,W,X,Y,Z) :- receta(V,W,X), buscarIngrediente(V,Y), buscarPaso(V,Z).\nreceta(pizza, boga, italiana).\nrecetaIngrediente(pizza, queso).\nrecetaIngrediente(pizza, jamon).\nrecetaPaso(pizza, poner_cosas).\nrecetaPaso(pizza, calentar).\nrecetaPaso(pizza, partir).\n") archivo.close() self.direccion = "Recetas.pl" #Se define el atributo con la dirección del código de prolog. self.cargarConocimientos() #Se cargan los conocimientos del código. self.error = True #Definición de la función que crea una nueva regla. #E: texto con el código de prolog. #S: ninguna #R: ninguna(método llamado internamente) def nuevaRegla(self, datosReceta): datos = [] datos.append('\nreceta({},{},{}).'.format(datosReceta[0], datosReceta[1], datosReceta[2])) for i in datosReceta[3]: datos.append('\nrecetaIngrediente({},{}).'.format(datosReceta[0],i)) for i in datosReceta[4]: datos.append('\nrecetaPaso({},{}).'.format(datosReceta[0],i)) print datosReceta print datos archivo = open(self.direccion, "a") for i in datos: archivo.write(i) archivo.close() self.cargarConocimientos() #Definición de la función que lee el código de prolog y carga cada línea en una lista #E: ninguna. #S: lista con cada línea del código fuente de prolog. #R: ninguna. def leer(self): archivo = open(self.direccion, "r") lineas = archivo.readlines() archivo.close() return lineas #Función que borra una receta. #E: nombre de la receta por borrar. #S: ninguna. #R: ninguna. def borrarReceta(self, receta): lineas = self.leer() contador = 0 a= "receta("+receta+"," b= "recetaIngrediente("+receta+"," c= "recetaPaso("+receta+"," final = [] for i in lineas: #Se recorre el código de prolog en busca de la receta. print i + '=' + a print i + '=' + b print i + '=' + c if (i.startswith("receta("+receta+",") or i.startswith("recetaIngrediente("+receta+",") or i.startswith("recetaPaso("+receta+",")): #Se verifica que la receta sea igual a la ingresada. #lineas.pop(contador) #Se elimina de la lista contador += 1 else: final.append(i) contador += 1 archivo = open(self.direccion, "w") #Se reescribe el archivo con la receta eliminada. for i in final: archivo.write(i) archivo.close() self.cargarConocimientos() box.showinfo("Éxito", "La receta se ha borrado con éxito.") #Función que actualiza alguna receta. #E: lista con las posiciones a modificar y todos los datos de la receta (dato vacío si no se va a modificar y nombre de la receta siempre estará). #Ejemplo: # Se tiene una receta(pizza, giovanni, italiana, queso, calentar) # Se desea cambiar solamente el dato de 'giovanni'(autor) y 'queso'(ingredientes) por 'giussepe' y 'jamón'. # Los datos de entrada serían: posiciones = [1,3], datos = ['pizza', 'giussepe', '', 'jamon', ''] #S: ninguna. #R: ninguna. def actualizarReceta(self, posiciones, datos): lineas = self.leer() contador = 0 iterador1 = 0 iterador2 = 0 for i in lineas: #Se recorre el código de prolog en busca de la receta a actualizar if (i.startswith("receta("+datos[0]+",")): #Se verifica que la receta sea igual a la que se desee cambiar lineas[contador] = self.actualizarReceta_aux(posiciones, datos, i[7:-3]) #Se sustituye la línea con el resultado de la función auxiliar. contador += 1 elif (i.startswith("recetaIngrediente("+datos[0]+",") and (3 in posiciones)): lineas[contador] = self.actualizarRecetaListas(3, datos, i[18:-3], iterador1) ## if (iterador1<len(datos[3]) and not(lineas[contador+1].startswith("recetaIngrediente("+datos[0]+","))): ## ## for i in datos[3][iterador1:]: ## ## lineas.insert(contador, "recetaIngrediente({},{}).\n".format(datos[0], i)) ## contador += 1 ## ## elif (iterador1==len(datos[3]) and (lineas[contador+1].startswith("recetaIngrediente("+datos[0]+","))): ## ## while(lineas[contador].startswith("recetaPaso("+datos[0]+",")): ## ## lineas.pop[contador] ## ## else: ## contador += 1 iterador1 += 1 elif (i.startswith("recetaPaso("+datos[0]+",") and (4 in posiciones)): lineas[contador] = self.actualizarRecetaListas(4, datos, i[11:-3], iterador2) contador += 1 iterador2 += 1 ## print lineas[contador] ## print "datos: " ## print datos ## print "iterador2:" ## print iterador2 ## print "len(datos[4]):" ## print datos[4] ## print lineas[contador+1] ## if (iterador2<len(datos[4]) and not(lineas[contador+1].startswith("recetaPaso("+datos[0]+","))): ## ## for i in datos[4][iterador2:]: ## ## lineas.insert(contador, "recetaIngrediente({},{}).\n".format(datos[0], i)) ## contador += 1 ## ## elif(iterador2==len(datos[4]) and (lineas[contador+1].startswith("recetaPaso("+datos[0]+","))): ## ## while(lineas[contador].startswith("recetaPaso("+datos[0]+",")): ## ## lineas.pop(contador) ## ## else: ## ## contador += 1 ## iterador2 += 1 ## else: contador += 1 archivo = open(self.direccion, "w") #Se reescribe el archivo con los nuevos datos. for i in lineas: archivo.write(i) archivo.close() self.cargarConocimientos() box.showinfo("Éxito", "La receta se ha actualizado con éxito.") #Función auxiliar que se encarga de actualizar los datos. #E: lista de las posiciones por modificar, datos por cambiar, datos originales. #Continuando el ejemplo: #datos = ['pizza', 'giussepe', '', 'jamon', ''] #posiciones = [1,3] #original = 'pizza, giovanni, italiana, queso, calentar' #S: línea de código prolog con los nuevos valores. #R: ninguna. def actualizarReceta_aux(self, posiciones, datos, original): separacion = original.split(",") #Se hace una lista con los datos viejos. Continuando el ejemplo anterior: #Se obtiene separacion = ['pizza', 'giovanni', 'italiana', 'queso', 'calentar'] (DATOS ORIGINALES) print "separacion:"+str(separacion) print "datos:"+str(datos) for i in posiciones: #Se recorre la lista con las posiciones de la lista separacion por cambiar. print "i: "+str(i) if i<3: separacion[i] = datos[i] #Se cambia la posición obtenida en la lista posiciones, con la misma posición de la lista datos. #Se cambiaría la posición separacion[1] = datos[1] ('giussepe') y luego separacion[3] = datos[3] ('jamon') return "receta({},{},{}).\n".format(separacion[0], separacion[1], separacion[2]) def actualizarRecetaListas(self, pos, datos, original, iterador): separacion = original.split(",") print "separacion: "+str(separacion) print " iterador: "+str(iterador) separacion[1] = datos[pos][iterador] if pos == 3: return "recetaIngrediente({},{}).\n".format(separacion[0], separacion[1]) #Se retorna la nueva línea de código prolog. else: return "recetaPaso({},{}).\n".format(separacion[0], separacion[1]) #Función que se encarga de cargar los conocimientos. #E: ninguna. #S: código prolog cargado. #R: ninguna. def cargarConocimientos(self): self.prolog = None #Se elimina la base de conocimientos anterior self.prolog = Prolog() #Se abre nuevamente prolog self.prolog.consult(self.direccion) #Se carga el código con la dirección obtenida anteriormente
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # S E N D # M O R E # + ------- # M O N E Y # # So, what should be the values of S, E, N, D, M, O, R, Y # if they are all distinct digits. from pyswip import Prolog letters = "S E N D M O R Y".split() prolog = Prolog() prolog.consult("money.pl") for result in prolog.query("sendmore(X)"): r = result["X"] for i, letter in enumerate(letters): print letter, "=", r[i] print "That's all..."
def Confirm(request, uuid): p = Prolog() p.consult('/home/jordanhudgens/code/coderprofile/survey/knowledgebase.pl') for soln in p.query("projectdesired(X)."): projectdesired = soln["X"] for soln in p.query("education(X)."): educationlevel = soln["X"] for soln in p.query("experience(X)."): programmingexperience = soln["X"] for soln in p.query("priority(X)."): learningpriority = soln["X"] for soln in p.query("employment(X)."): employmentstatus = soln["X"] for soln in p.query("featuredriven(X)."): featuredriven = soln["X"] for soln in p.query("mentor(X)."): mentordriven = soln["X"] for soln in p.query("targetaudience(X)"): audience = soln["X"] for soln in p.query("competitive(X)."): competitive = soln["X"] for soln in p.query("highspeedinternet(X)."): internetstatus = soln["X"] for soln in p.query("motivation(X)."): motivation = soln["X"] for soln in p.query("machine(X)."): machine = soln["X"] for soln in p.query("budget(X)."): budget = soln["X"] for soln in p.query("hoursfree(X)."): hoursfree = soln["X"] for soln in p.query("timeframe(X)."): timeframe = soln["X"] # Will need to be changed to data structure that can hold multiple values classSuggested = [] classURL = [] for soln in p.query("classSuggestion(X)."): ## ************** CHANGE PROLOG TERMS TO LINKS *************** ## if soln["X"] == "thinkfulfrontend": soln["X"] = "<span class='logoBorder'><img src='http://columbus.startupweekend.org/files/2013/07/Thinkful-Logo-Medium-300x60.png' width='100px'></span><p><a href='http://www.thinkful.com/' target='_blank'>Thinkful - Front End Development</a>: Build eight sleek and interactive websites with HTML, CSS, and JavaScript. Learn web development and apply UX design principles to create user-friendly products. Learn faster from expert developers through one-on-one online sessions.</p>" if soln["X"] == "thinkfulpython": soln["X"] = "<span class='logoBorder'><img src='http://columbus.startupweekend.org/files/2013/07/Thinkful-Logo-Medium-300x60.png' width='100px'></span><p><a href='http://www.thinkful.com/' target='_blank'>Thinkful - Python Web Development</a>: Program back-end web applications with Flask and deploy to Heroku. Learn object-oriented programming and use test driven development to produce reliable, maintainable code. Learn faster from expert developers through one-on-one online sessions." if soln["X"] == "thinkfulruby": soln["X"] = "<span class='logoBorder'><img src='http://columbus.startupweekend.org/files/2013/07/Thinkful-Logo-Medium-300x60.png' width='100px'></span><p><a href='http://www.thinkful.com/' target='_blank'>Thinkful - Ruby on Rails Web Development</a>: Build full-stack web apps using the popular framework Ruby on Rails - the quickest and most powerful way to build web apps. Launch a clone of Wikipedia from scratch and dive into the Twitter codebase. Learn faster from expert developers through one-on-one online sessions." if soln["X"] == "thinkfulios": soln["X"] = "<span class='logoBorder'><img src='http://columbus.startupweekend.org/files/2013/07/Thinkful-Logo-Medium-300x60.png' width='100px'></span><p><a href='http://www.thinkful.com/' target='_blank'>Thinkful - iOS Mobile App Development</a>: Build and launch iOS 7 and iOS 8 apps from scratch. You will learn to program in Swift and to use Xcode to build apps for the iPhone and iPad. By the end of the course, you will submit your work to the Apple App Store! Learn faster from expert developers through one-on-one online sessions.</p>" if soln["X"] == "blocror": soln["X"] = "<span class='logoBorder'><img src='http://static.squarespace.com/static/51ca1de9e4b04a2426bf6398/t/52d89fe0e4b0281856c67553/1389928416329/205329v1-max-250x250.jpg' width='100px'></span><p><a href='https://www.bloc.io/web-development' target='_blank'>Bloc - Ruby on Rails Web Development</a>: Working with an experienced mentor three times per week you will ship real web apps including versions of Wikipedia, Google Analytics, and Digg. Build a Wiki-as-a-service (SaaS) app that uses the Stripe API for payment processing. Implement email logic and social networking functionality as you build your own Digg social bookmarking app. And strengthen client-side skills as you build an analytics app with a back-end reporting dashboard. For your last two weeks, you and your mentor will work on a capstone project of your choice. This project will tie together and showcase the skills that you have learned as part of the course.</p>" if soln["X"] == "blocfrontend": soln["X"] = "<span class='logoBorder'><img src='http://static.squarespace.com/static/51ca1de9e4b04a2426bf6398/t/52d89fe0e4b0281856c67553/1389928416329/205329v1-max-250x250.jpg' width='100px'></span><p><a href='https://www.bloc.io/front-end-development' target='_blank'>Bloc - Front End Development</a>: Working with an experienced mentor three times per week you will learn frontend frameworks and libraries including jQuery, AngularJS, and JavaScript testing frameworks. For your last two weeks, you and your mentor will work on a capstone project of your choice. This project will tie together and showcase the skills that you have learned as part of the course.</p>" if soln["X"] == "blocandroid": soln["X"] = "<span class='logoBorder'><img src='http://static.squarespace.com/static/51ca1de9e4b04a2426bf6398/t/52d89fe0e4b0281856c67553/1389928416329/205329v1-max-250x250.jpg' width='100px'></span><p><a href='https://www.bloc.io/android' target='_blank'>Bloc - Android Mobile App Development</a>: Working with an experienced mentor three times per week you will choose from a menu of apps to build, each one designed to reinforce and build upon your Android developer skills. Dive deeper into APIs and integrations with Flurry Analytics, in-app purchases, and Google AdMob in-app advertising. As a capstone project, you will choose an app idea of your own to build. To complete the capstone, design, develop, test, and launch this app to the Google Play store.</p>" if soln["X"] == "blocois": soln["X"] = "<span class='logoBorder'><img src='http://static.squarespace.com/static/51ca1de9e4b04a2426bf6398/t/52d89fe0e4b0281856c67553/1389928416329/205329v1-max-250x250.jpg' width='100px'></span><p><a href='https://www.bloc.io/ios' target='_blank'>Bloc - iOS Mobile App Development</a>: Working with an experienced mentor three times per week you will choose from a menu of apps to build, each one designed to reinforce and build upon your iOS developer skills. Build your first iPad app. Integrate Apple tools like Maps, Game Center, and Auto Layout to make your app beautiful, reliable, and fun. As a capstone project, you will choose an app idea of your own to build. To complete the capstone, design, develop, test, and submit this app to the App Store.</p>" if soln["X"] == "codementorpython": soln["X"] = "<span class='logoBorder'><img src='http://cdn.geekwire.com/wp-content/uploads/codementor-logo-2.png' width='100px'></span><p><a href='https://www.codementor.io/learn-python-online' target='_blank'>CodeMentor - Python Web Development</a>: Our experienced mentors can teach Python for beginners, and you have an opportunity to learn PYTHON programming quickly if you have never programmed at all or never programmed in this language before. Of course, more advanced training can provide PYTHON help for experienced programmers too.</p>" if soln["X"] == "codementorror": soln["X"] = "<span class='logoBorder'><img src='http://cdn.geekwire.com/wp-content/uploads/codementor-logo-2.png' width='100px'></span><p><a href='https://www.codementor.io/learn-ruby-on-rails-online' target='_blank'>CodeMentor - Ruby on Rails Web Development</a>: Codementor has top Ruby on Rails experts from all over the world to help you learn Ruby on Rails online. Our experts can help learners of all skill levels, from beginners tackling early challenges to experienced developers who need help on specific problems.</p>" if soln["X"] == "codementorios": soln["X"] = "<span class='logoBorder'><img src='http://cdn.geekwire.com/wp-content/uploads/codementor-logo-2.png' width='100px'></span><p><a href='https://www.codementor.io/learn-ios-development' target='_blank'>CodeMentor - iOS Mobile App Development</a>: Codementor provides iOS expert help to help you learn iOS development more effectively. Whether you're creating a brand new native app or using technologies such as PhoneGap, Codementor can help you learn iPhone app development and build projects faster with live 1:1 help.</p>" if soln["X"] == "codementorandroid": soln["X"] = "<span class='logoBorder'><img src='http://cdn.geekwire.com/wp-content/uploads/codementor-logo-2.png' width='100px'></span><p><a href='https://www.codementor.io/learn-android-development' target='_blank'>CodeMentor - Android Mobile App Development</a>: Codementor provides Android expert help to help you learn Android development more effectively: java, android layout, eclipse, listview, android intent, android fragments, android listview, and more. Learning Android Development to create native mobile apps in Java or with technologies such as PhoneGap can be challenging if you're doing this alone. Codementor helps you learn Android programming with live 1:1 help and build projects faster.</p>" if soln["X"] == "codementorfrontend": soln["X"] = "<span class='logoBorder'><img src='http://cdn.geekwire.com/wp-content/uploads/codementor-logo-2.png' width='100px'></span><p><a href='https://www.codementor.io/learn-html' target='_blank'>CodeMentor - Front End Development</a>: Learning HTML is the starting point for most website creators. Sure, tutorials can get you up and running, but advanced concepts are much easier to grasp with the help of a good teacher. Codementor has top HTML tutors from all over the world to help you learn HTML online.</p>" if soln["X"] == "codechef": soln["X"] = "<span class='logoBorder'><img src='http://www.logogalleria.com/wp-content/uploads/2009/09/codechef.jpg' width='100px'></span><p><a href='http://www.codechef.com/' target='_blank'>CodeChef - Competitive Coding Challenges</a>: Prepare your self for various kinds of programming challenges by solving practice problems of varying difficulty. Compete against other techies in our monthly programming contests, gain recognition and win cool stuff. Coding contests begin on the first of every month.</p>" if soln["X"] == "codecademyhtml": soln["X"] = "<span class='logoBorder'><img src='http://cdn.appstorm.net/web.appstorm.net/files/2011/10/codecademy_logo.png' width='100px'></span><p><a href='http://www.codecademy.com/tracks/web' target='_blank'>Codecademy - HTML Training Track</a>: Learn the building blocks of web development with HTML and CSS, and create your own website by the end of the course.</p>" if soln["X"] == "codecademyjquery": soln["X"] = "<span class='logoBorder'><img src='http://cdn.appstorm.net/web.appstorm.net/files/2011/10/codecademy_logo.png' width='100px'></span><p><a href='http://www.codecademy.com/tracks/jquery' target='_blank'>Codecademy - jQuery Training Track</a>: jQuery uses JavaScript to easily build interactive websites. Learn animation, events and DOM manipulation.</p>" if soln["X"] == "codecademyror": soln["X"] = "<span class='logoBorder'><img src='http://cdn.appstorm.net/web.appstorm.net/files/2011/10/codecademy_logo.png' width='100px'></span><p><a href='http://www.codecademy.com/tracks/ruby' target='_blank'>Codecademy - Ruby Programming Track</a>: Ruby is a powerful yet beginner-friendly language used for professional web apps all over the world. Learn the syntax and complete exercises.</p>" if soln["X"] == "codecademypython": soln["X"] = "<span class='logoBorder'><img src='http://cdn.appstorm.net/web.appstorm.net/files/2011/10/codecademy_logo.png' width='100px'></span><p><a href='http://www.codecademy.com/tracks/python' target='_blank'>Codecademy - Python Programming Track</a>: Learn the fundamentals of programming to build web apps and manipulate data.</p>" if soln["X"] == "codecademyphp": soln["X"] = "<span class='logoBorder'><img src='http://cdn.appstorm.net/web.appstorm.net/files/2011/10/codecademy_logo.png' width='100px'></span><p><a href='http://www.codecademy.com/tracks/php' target='_blank'>Codecademy - PHP Programming Track</a>: Go through PHP programming exercises and solve programming problems.</p>" if soln["X"] == "codeschoolror": soln["X"] = "<span class='logoBorder'><img src='https://d1tijy5l7mg5kk.cloudfront.net/assets/press_kit/logo-full-text-8f831675b0a894d991d720c532651ec6.png' width='100px'></span><p><a href='https://www.codeschool.com/paths/ruby' target='_blank'>CodeSchool - Ruby on Rails Development</a>: Master your Ruby skills and increase your Rails street cred by learning to build dynamic, sustainable applications for the web.</p>" if soln["X"] == "codeschoolfrontend": soln["X"] = "<span class='logoBorder'><img src='https://d1tijy5l7mg5kk.cloudfront.net/assets/press_kit/logo-full-text-8f831675b0a894d991d720c532651ec6.png' width='100px'></span><p><a href='https://www.codeschool.com/paths/html-css' target='_blank'>CodeSchool - Front End Development</a>: Learn the fundamentals of design, front-end development, and crafting user experiences that are easy on the eyes.</p>" if soln["X"] == "codeschoolios": soln["X"] = "<span class='logoBorder'><img src='https://d1tijy5l7mg5kk.cloudfront.net/assets/press_kit/logo-full-text-8f831675b0a894d991d720c532651ec6.png' width='100px'></span><p><a href='https://www.codeschool.com/paths/ios' target='_blank'>CodeSchool - iOS Mobile App Development</a>: Try your hand at building iOS applications for iPhone and iPad mobile devices. Learn the basics of iOS development and bring your app ideas to life.</p>" if soln["X"] == "rubymonk": soln["X"] = "<span class='logoBorder'><img src='https://dy0ao1dkujg1a.cloudfront.net/assets/layouts/rubymonk-menu-logo-e3705b4511769c85dcb07be28c871daa.png' width='100px'></span><p><a href='https://rubymonk.com/' target='_blank'>Ruby Monk - Ruby Programming Training</a>: Free, interactive tutorials to help you discover Ruby idioms, in your browser.</p>" if soln["X"] == "treehousefrontend": soln["X"] = "<span class='logoBorder'><img src='http://yourlocalamerica.com/wp-content/uploads/2013/11/Treehouse-Logo-Mark.png' width='100px'></span><p><a href='http://teamtreehouse.com/library/topic:html' target='_blank'>Team Treehouse - Front End Development</a>: HyperText Markup Language (HTML) forms the structural layer of web pages. No matter what kind of website or application you want to build, this is a language you need to understand.</p>" if soln["X"] == "treehouseror": soln["X"] = "<span class='logoBorder'><img src='http://yourlocalamerica.com/wp-content/uploads/2013/11/Treehouse-Logo-Mark.png' width='100px'></span><p><a href='http://teamtreehouse.com/library/topic:ruby' target='_blank'>Team Treehouse - Ruby on Rails Development</a>: Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.</p>" if soln["X"] == "treehousephp": soln["X"] = "<span class='logoBorder'><img src='http://yourlocalamerica.com/wp-content/uploads/2013/11/Treehouse-Logo-Mark.png' width='100px'></span><p><a href='http://teamtreehouse.com/library/topic:php' target='_blank'>Team Treehouse - PHP Web Development</a>: Learn how to build a full eCommerce shop with step by step videos and exercises. PHP is a widely-used general-purpose scripting language that is especially suited for Web Development and can be embedded into HTML.</p>" if soln["X"] == "treehouseandroid": soln["X"] = "<span class='logoBorder'><img src='http://yourlocalamerica.com/wp-content/uploads/2013/11/Treehouse-Logo-Mark.png' width='100px'></span><p><a href='http://teamtreehouse.com/library/topic:android' target='_blank'>Team Treehouse - Android Mobile App Development</a>: Android is the mobile operating system used on more devices around the world than any other platform. Learn how to create Android apps using Java and the powerful development tools available from Google.</p>" if soln["X"] == "treehouseios": soln["X"] = "<span class='logoBorder'><img src='http://yourlocalamerica.com/wp-content/uploads/2013/11/Treehouse-Logo-Mark.png' width='100px'></span><p><a href='http://teamtreehouse.com/library/topic:ios' target='_blank'>Team Treehouse - iOS Mobile App Development</a>: iOS is the powerful operating system that powers iPhones and iPads. Learn the language, tools and frameworks to build interactive apps on the iOS platform.</p>" if soln["X"] == "udacitypython1": soln["X"] = "<span class='logoBorder'><img src='http://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Udacity_Logo.svg/396px-Udacity_Logo.svg.png' width='100px'></span><p><a href='https://www.udacity.com/course/cs101' target='_blank'>Udacity - Intro to Python Web Development</a>: In this introductory course, you will learn and practice key computer science concepts by building your own versions of popular web applications. You will learn Python, a powerful, easy-to-learn, and widely used programming language, and you will explore fundamental computer science concepts, as you build your own search engine and social network.</p>" if soln["X"] == "udacitypython2": soln["X"] = "<span class='logoBorder'><img src='http://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Udacity_Logo.svg/396px-Udacity_Logo.svg.png' width='100px'></span><p><a href='https://www.udacity.com/course/cs253' target='_blank'>Udacity - Intermediate Python Web Development</a>: In this intermediate course, Steve Huffman will teach you everything he wished he knew when he started building Reddit and, more recently, Hipmunk, as a lead engineer. Starting from the basics of how the web works, this course will walk you through core web development concepts such as how internet and browsers fit together, form validations, databases, APIs, integrating with other websites, scaling issues, and more; all of which form part of the knowledge it takes to build a web application of your own.</p>" if soln["X"] == "udacityfrontend": soln["X"] = "<span class='logoBorder'><img src='http://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Udacity_Logo.svg/396px-Udacity_Logo.svg.png' width='100px'></span><p><a href='https://www.udacity.com/course/ud248' target='_blank'>Udacity - Front End Development</a>: Ten minutes into this class you will make your own completely personalized version of the insanely addictive game 2048. Even if you've never coded before. Pretty cool, no? You will do this by making small (but important) modifications to the source code for the original 2048 game. If this sounds intimidating, don't worry. We'll teach you the basics of HTML and CSS and how they interact with Javascript (don't worry if that sentence doesn't mean anything to you yet. It will soon).</p>" if soln["X"] == "javaposse": soln["X"] = "<span class='logoBorder'><img src='http://www.mindviewinc.com/Conferences/JavaPosseRoundup/JavaPosseLogoSmall.png.png' width='100px'></span><p><a href='http://javaposse.com/' target='_blank'>Java Posse - Java and Android Podcasts</a>: News, Interviews, Opinions, and General Mayhem focused on the java community.</p>" if soln["X"] == "stackexchange": soln["X"] = "<span class='logoBorder'><img src='http://cdn.sstatic.net/stackexchange/img/logos/se/se-logo.png' width='100px'></span><p><a href='http://blog.stackoverflow.com/category/podcasts/' target='_blank'>StackExchange - Programming Podcasts</a>: General programming discussions.</p>" if soln["X"] == "hansel": soln["X"] = "<span class='logoBorder'><img src='http://www.hanselminutes.com/images/logo.png' width='100px'></span><p><a href='http://www.hanselminutes.com/' target='_blank'>Hansel Minutes - Programming Podcasts</a>: I'm a teacher. I speak all over to whoever will listen. I have written code that you've used. I've been blogging for over a decade and podcasting for about half that. I speak, code, write, empower, promote, braid, learn and listen - usually not in that order.</p>" if soln["X"] == "twittv": soln["X"] = "<span class='logoBorder'><img src='http://twit.tv/files/imagecache/coverart-feed/coverart/sn300.jpg' width='100px'></span><p><a href='http://twit.tv/sn' target='_blank'>Team Twit.tv - Programming Podcasts</a>: Steve Gibson, the man who coined the term spyware and created the first anti-spyware program, creator of Spinrite and ShieldsUP, discusses the hot topics in security today with Leo Laporte. Records live every Tuesday at 1:00pm PT/4:00pm ET.</p>" if soln["X"] == "thechangelog": soln["X"] = "<span class='logoBorder'><img src='http://static.squarespace.com/static/4fb1327fe4b037aee8691be3/t/5192b877e4b05340711c3bf4/1368569977503/cover-1.jpg' width='100px'></span><p><a href='http://thechangelog.com/podcast/' target='_blank'>The Change Log - Open Source Podcasts</a>: Discussions focused on the open source code community.</p>" if soln["X"] == "phptownhall": soln["X"] = "<span class='logoBorder'><img src='https://www.drupal.org/files/project-images/php.png' width='100px'></span><p><a href='http://phptownhall.com/' target='_blank'>PHP Town Hall - PHP Programming Podcasts</a>: Phil, Ben and a super-star guest answer questions and talk about current events in the PHP world.</p>" if soln["X"] == "rubyrogues": soln["X"] = "<span class='logoBorder'><img src='https://www.drupal.org/files/project-images/php.png' width='100px'></span><p><a href='http://rubyrogues.com/' target='_blank'>Ruby Rogues - Ruby Programming Podcasts</a>: In depth coverage of the Ruby Programming language community.</p>" if soln["X"] == "udemyrorbiz": soln["X"] = "<span class='logoBorder'><img src='https://udemyimages-a.akamaihd.net/course/480x270/119262_c783_2.jpg' width='100px'></span><p><a href='https://www.udemy.com/comprehensive-ruby-on-rails' target='_blank'>Edutechional - Ruby on Rails Business Application Development</a>: This course that will walk you step by step through every skill you will need to become a full stack web developer, and I do it by showing you how to build an actual production application. Starting completely from scratch I explain how to setup your environment, create the application, build in advanced features and finally deploy to the web!</p>" if soln["X"] == "udemyfrontend1": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/web-development-tutorials' target='_blank'>Stone River eLearning - Front End Development</a>: The design and structure of this course follows elite college curriculum. You will begin by learning the basics of each programming language and technology web developers use, and you will be creating real life projects with every new skill you learn so you're getting the entire finished puzzle instead of just pieces that you have to put together yourself.</p>" if soln["X"] == "udemyphp1": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/become-a-certified-web-developer' target='_blank'>LearnToProgram.TV - PHP Web Development</a>: Learn What It Takes to Code Dynamic, Professional Websites and Web Apps From The Comfort of Your Own Home. Our course starts teaching basic coding principles and develops your coding skills in a variety of languages from beginner through to advanced. Here it is, once and for all, a complete guide that will take you from novice to web developer.</p>" if soln["X"] == "udemyandroid1": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/learn-by-doing-android-for-beginners' target='_blank'>Ragunath Jawahar - Android Mobile App Development</a>: From the Developer of over 100 Android Applications and 6 Open Source Android Libraries.</p>" if soln["X"] == "udemyios1": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/iosdevelopment' target='_blank'>The App Dojo - iOS Mobile App Development</a>: I'll teach you how to make iPhone apps with this complete iOS development tutorial. You'll learn how to create apps using the same tools and techniques used to make the top apps in The App Store.</p>" if soln["X"] == "udemyios2": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/the-complete-ios-7-course-learn-by-building-14-apps' target='_blank'>John Nichols - iOS Mobile App Development</a>: Our iOS Bootcamp teaches the tools needed to develop iPhone and iPad applications for iOS7. Along our journey, we will learn the syntax of Objective-C, the language used to develop for iOS, as well as important design patterns and best practices. By the end of the course, you should be able to understand and recreate many of the features seen on popular iOS applications and extend that knowledge to making apps of your own.</p>" if soln["X"] == "udemyios4": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/swift-learn-apples-new-programming-language-by-examples' target='_blank'>Rick Walter - iOS Mobile App Development</a>: Swift is a multi-paradigm programming language developed by Apple for use with iOS and OS X. Designed to replace Objective C, work began on Swift in 2010 and the first mobile app was debuted in June 2014 at the Worldwide Developers Conference. Despite its goal of replacing Objective C, Swift is capable of working alongside the more dated Objective C language while using the Cocoa and Cocoa Touch frameworks.</p>" if soln["X"] == "udemyios5": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/projects-in-ios' target='_blank'>Eduonix Learning Solutions - iOS Mobile App Development</a>: This is a course for all programmers who will like to build on their iOS knowledge and create actual apps for the App store. This course assumes basic iOS programming knowledge but is still ideal for beginners as we are covering the APIs in detail before using them to build the projects.</p>" if soln["X"] == "udemyrorsoc": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/create-and-deploy-a-web-app-in-3-hours' target='_blank'>Tiago Martins - Ruby on Rails Social App Development</a>: This course will teach you how to combine Ruby on Rails and Facebook Connect to create a sleek final product that harnesses the power of Facebook to attract new users.</p>" if soln["X"] == "udemyios6": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/learn-ios-programming-the-basics' target='_blank'>Eduonix Learning Solutions - Intro to iOS Mobile App Development</a>: This iOS course is aimed to provide a through and clear understanding of the iOS programming. We start with basic Hello world for iOS and cover the most important topics which will provide you a firm base to build your iOS Apps. This lecture uses the latest IOS SDK and uses an example based approach to teaching. We have kept the learning curve simple and focus is on conceptual learning rather than just teaching how to use a particular API. After completing the course you will understand the principle behind the API patterns and why a particular control behaves the way it does.</p>" if soln["X"] == "udemyfrontend2": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/webdevelopment101_html' target='_blank'>Brian Gorman - Front End Development</a>: This course is an overview of the HTML web programming standard. The course is intended for those who have never done anything with HTML or web pages and would like to build this basic knowledge for starting a career as a web developer or for learning how to program HTML for web pages. By no means will you be a world class UI developer at the end of this course, but you will have the basic understanding of building pages with HTML and HTML5, and at the end of the course you'll gain knowledge about where to go next to further your front-end web development skills.</p>" if soln["X"] == "udemygames1": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/learn-c-game-development' target='_blank'>Luka Horvat - C++ Game Development</a>: Learn C++ game development is a course I made for everyone who knows how to program, but doesn't know where to start with game development. The course teaches you how to use the SFML library for C++, to start working with graphics, events and sound to create a 2D game. Everything is done step by step with the help of videos, so it's easy to follow along and learn. At the end of the course you will know what you need for game programming and will be able to start making your own games.</p>" if soln["X"] == "udemygames2": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/responsive-html5-theme-development' target='_blank'>Lamin Sanneh - HTML5 Game Development</a>: In this course, using direct approaches, I will teach how to build such websites. This is a very focussed course and I intentionally removed unnecessary material which I believe only distracts students from what they need to know. I know this from experience, and hence the reason the course is not that long. So lean back , relax and come along this exciting journey which is responsive web design.</p>" if soln["X"] == "udemyphp2": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/php-programming-basics' target='_blank'>Stone River eLearning - PHP Web Application Development</a>: In this course we cover the very basics of PHP programming, then move on to more complex topics while still making sure the course is easy to understand for those who have never programmed before.</p>" if soln["X"] == "udemyfrontend3": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/learn-to-build-beautiful-html5-and-css3-websites-in-1-month' target='_blank'>Ryan Bonhardt - Front End Development</a>: You will learn how to build your first website within 1 week with all the basics of HTML and CSS. Then we expand and add upon that knowledge with more advanced HTML and CSS as we build our second site together. To top it off we repeat this process with smaller lessons and within one month you will have a complete knowledge and ability to build startup quality websites FAST.</p>" if soln["X"] == "udemyfrontend4": soln["X"] = "<span class='logoBorder'><img src='https://www-udemy-com.global.ssl.fastly.net/static/images/v4/logo.jpg' width='100px'></span><p><a href='https://www.udemy.com/android-programming-for-beginners' target='_blank'>Mark Lassoff - Android Mobile App Development</a>: While this is a course for beginners, to be successful you need to know the basics of Java. The course will review the more complex Java used in the Android ecosystem, but you should understand Java Basics-- Variables, Loops, Functions, Conditionals should be enough.</p>" if soln["X"] == "khangames1": soln["X"] = "<span class='logoBorder'><img src='https://www.intellectualrevolution.tv/wp-content/uploads/Khan-Academy-Logo.jpg' width='100px'></span><p><a href='https://www.khanacademy.org/computing/cs/programming' target='_blank'>Khan Academy - Intro to Game Development</a>: In these tutorials, you'll learn how to use the JavaScript language and the ProcessingJS library to create fun drawings and animations. If you've never programmed before, start here to learn how!</p>" if soln["X"] == "khangames2": soln["X"] = "<span class='logoBorder'><img src='https://www.intellectualrevolution.tv/wp-content/uploads/Khan-Academy-Logo.jpg' width='100px'></span><p><a href='https://www.khanacademy.org/computing/cs/programming-games-visualizations' target='_blank'>Khan Academy - Game Development</a>: Now that you know how to program in JavaScript and make basic drawings and animations, how could you use that knowledge to make games and visualizations?</p>" if soln["X"] == "khangames3": soln["X"] = "<span class='logoBorder'><img src='https://www.intellectualrevolution.tv/wp-content/uploads/Khan-Academy-Logo.jpg' width='100px'></span><p><a href='https://www.khanacademy.org/computing/cs/programming-natural-simulations' target='_blank'>Khan Academy - Intermediate Game Development</a>: Learn how to use JavaScript, ProcessingJS, and mathematical concepts to simulate nature in your programs. These tutorials are a derivative of 'The Nature of Code' book by Daniel Shiffman (natureofcode.com)</p>" if soln["X"] == "codeplayer": soln["X"] = "<span class='logoBorder'><img src='http://auroraiannino.be/wp-content/uploads/2014/01/thecodeplayer0.jpg' width='100px'></span><p><a href='http://thecodeplayer.com/' target='_blank'>CodePlayer - Front End Development</a>: Video style walkthroughs showing cool stuff being created from scratch.</p>" if soln["X"] == "hardwaypython1": soln["X"] = "<span class='logoBorder'><img src='http://auroraiannino.be/wp-content/uploads/2014/01/thecodeplayer0.jpg' width='100px'></span><p><a href='http://learnpythonthehardway.org' target='_blank'>Learn Python the Hard Way - Python Programming Manual</a>: Read by 1.5 million people a year to learn the basics of programming, Learn Python The Hard Way is the most successful beginner programming book on the market.</p>" if soln["X"] == "hardwaypython1": soln["X"] = "<span class='logoBorder'><img src='http://auroraiannino.be/wp-content/uploads/2014/01/thecodeplayer0.jpg' width='100px'></span><p><a href='http://learnpythonthehardway.org' target='_blank'>Learn Python the Hard Way - Python Programming Video Series</a>: Read by 1.5 million people a year to learn the basics of programming, Learn Python The Hard Way is the most successful beginner programming book on the market. For $29.95 you get a complete beginner programming course with 1.7GB of Video, a PDF and ePub, and no ads on the web site." if soln["X"] == "railscasts": soln["X"] = "<span class='logoBorder'><img src='http://geekhmer.github.io/images/logo_rails_casts.png' width='100px'></span><p><a href='http://railscasts.com/' target='_blank'>Railscasts - Ruby on Rails Web Development</a>: The topics target the intermediate Rails developer, but beginners and experts will get something out of it as well. A Pro option is also available containing more screencasts each week.</p>" ## *************************** END *************************** ## classSuggested.append(soln["X"]) email = settings.support_email return render(request, 'confirm.html', {'uuid':uuid, "email": email, 'projectdesired':projectdesired, 'educationlevel':educationlevel, 'programmingexperience':programmingexperience, 'learningpriority':learningpriority, 'employmentstatus':employmentstatus, 'featuredriven':featuredriven, 'mentordriven':mentordriven, 'audience':audience, 'competitive':competitive, 'internetstatus':internetstatus, 'motivation':motivation, 'machine':machine, 'budget':budget, 'hoursfree':hoursfree, 'timeframe':timeframe, 'classSuggested':classSuggested, 'classURL':classURL})
class se(Singleton): band = True def __init__(self): if self.band: self.prolog = Prolog() if not os.path.isfile('recetas.pl'): print "Generando Recetas..." self.cargarRecetas() print "Cargando Recetas..." self.prolog.consult('recetas.pl') print "Cargando Querys..." self.prolog.consult('querys.pl') self.band = False else: print "Ya se cargo" def cargarRecetas(self): recetario = open("recetas.pl", "w") header = """%====================\n% BASE DE HECHOS\n%====================\n""" recetario.write(header) # Cargar ingredientes en la Base de Conocimiento headerIng = """\n%--------------------\n% Ingredientes\n%--------------------\n""" recetario.write(headerIng) listaIngredientes = Ingrediente.objects.values_list('nombre',flat=True) bufferIng = ["ingrediente('"+x.encode('utf-8')+"').\n" for x in listaIngredientes] recetario.writelines(bufferIng) # Cargar Categorias en la Base de Conocimiento headerCat = """\n%--------------------\n% Categorias\n%--------------------\n""" recetario.write(headerCat) listaCategorias = Categoria.objects.values_list('nombre',flat=True) bufferCat = ["categoria('"+x.encode('utf-8')+"').\n" for x in listaCategorias] recetario.writelines(bufferCat) # Cargar Recetas en la Base de Conocimiento listaRecetas = Receta.objects.values_list('nombre','categoria') headerRec = """\n%--------------------\n% Recetas\n%--------------------\n""" recetario.write(headerRec) for receta in listaRecetas: recingr = Receta.objects.get(nombre=receta[0]).ingredientes.values_list('nombre',flat=True) reccat = Categoria.objects.values_list('nombre',flat=True).get(id=receta[1]) reccant = DetalleReceta.objects.filter(receta__nombre=receta[0]).values_list('cantidad', flat=True) recprep = Receta.objects.get(nombre=receta[0]).preparacion bufferRec = "receta(\tnombre('"+receta[0]+"'),\n\tcategoria('"+str(reccat)+"'),\n\tingredientes(['"+"', '".join(recingr)+"']),\n\tcantidades(['"+"', '".join(reccant)+"']),\n\tpreparacion('"+recprep+"')\n\t).\n" recetario.write(bufferRec.encode('utf-8')) recetario.close() def lista_ingredientes(self): lista = self.prolog.query("ingrediente(X)") return [d['X'] for d in lista] def hay(self,listaIngredientes): #listaIngr = [str(x) for x in listaIngredientes] hay = "hay("+str(listaIngredientes)+")" self.prolog.assertz(hay) return list(self.prolog.query("hay(X)")) def quePuedoHacer(self): return list(self.prolog.query("quePuedoHacer(Receta,Cat)"))
# A short Python script to demonstrate how the Prolog is meant to be used. # Requires pyswip and a running instance of MySQL. from pyswip import Prolog prolog = Prolog() prolog.consult("appraise.pl") # A couple preliminary assertions. prolog.assertz("value(banana, 1 rdiv 4, bitcoin)") prolog.assertz("value(bitcoin, 1 rdiv 30, namecoin)") prolog.assertz("value(apple, 3 rdiv 4, banana)") prolog.assertz("value(orange, 1 rdiv 5, apple)") # Now, how much is an orange worth in bitcoins? result = prolog.query("appraise_float(orange, Price, bitcoin)").next() print "An orange is worth %s bitcoins." % result["Price"] # And how much is a bitcoin worth in apples? result = prolog.query("appraise_float(bitcoin, Price, apple)").next() print "A bitcoin is worth %s apples." % result["Price"]
def solve(self): p=Prolog() if(self.count%3==1): p = Prolog() p.consult('func.pl') #X = (list(p.query('sudoku(Solution,[[_,_,_,_,3,8,_,_,_],[_,8,_,9,_,_,2,7,_],[3,_,4,_,_,_,_,_,1],[9,4,_,1,7,_,_,_,5],[_,_,7,_,6,_,_,_,_],[_,5,_,_,_,_,_,2,6],[_,9,_,_,_,_,_,5,_],[_,_,_,6,8,_,_,4,_],[_,6,_,_,1,_,9,_,7]])'))) X = ((p.query('sudoku(Solution,[[_,_,_,_,_,_,_,3,1],[_,1,_,_,6,2,4,_,_],[5,_,3,7,_,_,_,_,_],[_,9,_,8,2,_,_,_,_],[6,_,_,_,_,_,_,8,_],[_,5,4,9,_,_,7,6,_],[_,_,_,_,5,_,8,1,_],[_,8,_,6,_,4,_,7,_],[_,4,_,_,9,_,_,_,_]])'))) #X = (list(p.query('sudoku(Solution,[_,_,_,_,_,_,_,3,1,_,1,_,_,6,2,4,_,_,5,_,3,7,_,_,_,_,_,_,9,_,8,2,_,_,_,_,6,_,_,_,_,_,_,8,_,_,5,4,9,_,_,7,6,_,_,_,_,_,5,_,8,1,_,_,8,_,6,_,4,_,7,_,_,4,_,_,9,_,_,_,_])'))) A = X.next() Z = list(A['Solution']) print(Z) self.a1.setText(str(Z[0])) self.a2.setText(str(Z[1])) self.a3.setText(str(Z[2])) self.a4.setText(str(Z[3])) self.a5.setText(str(Z[4])) self.a6.setText(str(Z[5])) self.a7.setText(str(Z[6])) self.a8.setText(str(Z[7])) self.a9.setText(str(Z[8])) self.b1.setText(str(Z[9])) self.b2.setText(str(Z[10])) self.b3.setText(str(Z[11])) self.b4.setText(str(Z[12])) self.b5.setText(str(Z[13])) self.b6.setText(str(Z[14])) self.b7.setText(str(Z[15])) self.b8.setText(str(Z[16])) self.b9.setText(str(Z[17])) self.c1.setText(str(Z[18])) self.c2.setText(str(Z[19])) self.c3.setText(str(Z[20])) self.c4.setText(str(Z[21])) self.c5.setText(str(Z[22])) self.c6.setText(str(Z[23])) self.c7.setText(str(Z[24])) self.c8.setText(str(Z[25])) self.c9.setText(str(Z[26])) self.d1.setText(str(Z[27])) self.d2.setText(str(Z[28])) self.d3.setText(str(Z[29])) self.d4.setText(str(Z[30])) self.d5.setText(str(Z[31])) self.d6.setText(str(Z[32])) self.d7.setText(str(Z[33])) self.d8.setText(str(Z[34])) self.d9.setText(str(Z[35])) self.e1.setText(str(Z[36])) self.e2.setText(str(Z[37])) self.e3.setText(str(Z[38])) self.e4.setText(str(Z[39])) self.e5.setText(str(Z[40])) self.e6.setText(str(Z[41])) self.e7.setText(str(Z[42])) self.e8.setText(str(Z[43])) self.e9.setText(str(Z[44])) self.f1.setText(str(Z[45])) self.f2.setText(str(Z[46])) self.f3.setText(str(Z[47])) self.f4.setText(str(Z[48])) self.f5.setText(str(Z[49])) self.f6.setText(str(Z[50])) self.f7.setText(str(Z[51])) self.f8.setText(str(Z[52])) self.f9.setText(str(Z[53])) self.g1.setText(str(Z[54])) self.g2.setText(str(Z[55])) self.g3.setText(str(Z[56])) self.g4.setText(str(Z[57])) self.g5.setText(str(Z[58])) self.g6.setText(str(Z[59])) self.g7.setText(str(Z[60])) self.g8.setText(str(Z[61])) self.g9.setText(str(Z[62])) self.h1.setText(str(Z[63])) self.h2.setText(str(Z[64])) self.h3.setText(str(Z[65])) self.h4.setText(str(Z[66])) self.h5.setText(str(Z[67])) self.h6.setText(str(Z[68])) self.h7.setText(str(Z[69])) self.h8.setText(str(Z[70])) self.h9.setText(str(Z[71])) self.i1.setText(str(Z[72])) self.i2.setText(str(Z[73])) self.i3.setText(str(Z[74])) self.i4.setText(str(Z[75])) self.i5.setText(str(Z[76])) self.i6.setText(str(Z[77])) self.i7.setText(str(Z[78])) self.i8.setText(str(Z[79])) self.i9.setText(str(Z[80])) elif(self.count%3==2): X = (list(p.query('sudoku(Solution,[7,_,8,6,_,_,_,_,_,6,_,_,5,_,3,4,1,_,_,_,_,_,1,_,_,7,_,_,_,_,_,_,_,_,9,2,_,8,1,2,_,_,3,_,_,4,_,_,_,5,9,_,_,_,_,_,5,_,_,_,7,2,_,1,3,_,7,_,_,_,4,_,_,_,6,3,_,_,_,_,_])'))) #Y = dict(X[0]) #Z = list(Y['Solution']) X = ((p.query('sudoku(Solution,[[7,_,8,6,_,_,_,_,_],[6,_,_,5,_,3,4,1,_],[_,_,_,_,1,_,_,7,_],[_,_,_,_,_,_,_,9,2],[_,8,1,2,_,_,3,_,_],[4,_,_,_,5,9,_,_,_],[_,_,5,_,_,_,7,2,_],[1,3,_,7,_,_,_,4,_],[_,_,6,3,_,_,_,_,_]])'))) A = X.next() Z = list(A['Solution']) print(Z) self.a1.setText(str(Z[0])) self.a2.setText(str(Z[1])) self.a3.setText(str(Z[2])) self.a4.setText(str(Z[3])) self.a5.setText(str(Z[4])) self.a6.setText(str(Z[5])) self.a7.setText(str(Z[6])) self.a8.setText(str(Z[7])) self.a9.setText(str(Z[8])) self.b1.setText(str(Z[9])) self.b2.setText(str(Z[10])) self.b3.setText(str(Z[11])) self.b4.setText(str(Z[12])) self.b5.setText(str(Z[13])) self.b6.setText(str(Z[14])) self.b7.setText(str(Z[15])) self.b8.setText(str(Z[16])) self.b9.setText(str(Z[17])) self.c1.setText(str(Z[18])) self.c2.setText(str(Z[19])) self.c3.setText(str(Z[20])) self.c4.setText(str(Z[21])) self.c5.setText(str(Z[22])) self.c6.setText(str(Z[23])) self.c7.setText(str(Z[24])) self.c8.setText(str(Z[25])) self.c9.setText(str(Z[26])) self.d1.setText(str(Z[27])) self.d2.setText(str(Z[28])) self.d3.setText(str(Z[29])) self.d4.setText(str(Z[30])) self.d5.setText(str(Z[31])) self.d6.setText(str(Z[32])) self.d7.setText(str(Z[33])) self.d8.setText(str(Z[34])) self.d9.setText(str(Z[35])) self.e1.setText(str(Z[36])) self.e2.setText(str(Z[37])) self.e3.setText(str(Z[38])) self.e4.setText(str(Z[39])) self.e5.setText(str(Z[40])) self.e6.setText(str(Z[41])) self.e7.setText(str(Z[42])) self.e8.setText(str(Z[43])) self.e9.setText(str(Z[44])) self.f1.setText(str(Z[45])) self.f2.setText(str(Z[46])) self.f3.setText(str(Z[47])) self.f4.setText(str(Z[48])) self.f5.setText(str(Z[49])) self.f6.setText(str(Z[50])) self.f7.setText(str(Z[51])) self.f8.setText(str(Z[52])) self.f9.setText(str(Z[53])) self.g1.setText(str(Z[54])) self.g2.setText(str(Z[55])) self.g3.setText(str(Z[56])) self.g4.setText(str(Z[57])) self.g5.setText(str(Z[58])) self.g6.setText(str(Z[59])) self.g7.setText(str(Z[60])) self.g8.setText(str(Z[61])) self.g9.setText(str(Z[62])) self.h1.setText(str(Z[63])) self.h2.setText(str(Z[64])) self.h3.setText(str(Z[65])) self.h4.setText(str(Z[66])) self.h5.setText(str(Z[67])) self.h6.setText(str(Z[68])) self.h7.setText(str(Z[69])) self.h8.setText(str(Z[70])) self.h9.setText(str(Z[71])) self.i1.setText(str(Z[72])) self.i2.setText(str(Z[73])) self.i3.setText(str(Z[74])) self.i4.setText(str(Z[75])) self.i5.setText(str(Z[76])) self.i6.setText(str(Z[77])) self.i7.setText(str(Z[78])) self.i8.setText(str(Z[79])) self.i9.setText(str(Z[80])) elif(self.count%3==0): X = (list(p.query('sudoku(Solution,[_,_,_,1,2,_,7,4,_,_,_,_,5,7,3,_,_,2,3,_,_,_,_,_,_,_,_,7,1,_,_,_,_,2,_,6,_,5,2,_,_,_,8,9,_,6,_,8,_,_,_,_,7,4,_,_,_,_,_,_,_,_,5,8,_,_,3,4,1,_,_,_,_,6,3,_,5,9,_,_,_])'))) #Y = dict(X[0]) #Z = list(Y['Solution']) X = ((p.query('sudoku(Solution,[[_,_,_,1,2,_,7,4,_],[_,_,_,5,7,3,_,_,2],[3,_,_,_,_,_,_,_,_],[7,1,_,_,_,_,2,_,6],[_,5,2,_,_,_,8,9,_],[6,_,8,_,_,_,_,7,4],[_,_,_,_,_,_,_,_,5],[8,_,_,3,4,1,_,_,_],[_,6,3,_,5,9,_,_,_]])'))) A = X.next() Z = list(A['Solution']) print(Z) self.a1.setText(str(Z[0])) self.a2.setText(str(Z[1])) self.a3.setText(str(Z[2])) self.a4.setText(str(Z[3])) self.a5.setText(str(Z[4])) self.a6.setText(str(Z[5])) self.a7.setText(str(Z[6])) self.a8.setText(str(Z[7])) self.a9.setText(str(Z[8])) self.b1.setText(str(Z[9])) self.b2.setText(str(Z[10])) self.b3.setText(str(Z[11])) self.b4.setText(str(Z[12])) self.b5.setText(str(Z[13])) self.b6.setText(str(Z[14])) self.b7.setText(str(Z[15])) self.b8.setText(str(Z[16])) self.b9.setText(str(Z[17])) self.c1.setText(str(Z[18])) self.c2.setText(str(Z[19])) self.c3.setText(str(Z[20])) self.c4.setText(str(Z[21])) self.c5.setText(str(Z[22])) self.c6.setText(str(Z[23])) self.c7.setText(str(Z[24])) self.c8.setText(str(Z[25])) self.c9.setText(str(Z[26])) self.d1.setText(str(Z[27])) self.d2.setText(str(Z[28])) self.d3.setText(str(Z[29])) self.d4.setText(str(Z[30])) self.d5.setText(str(Z[31])) self.d6.setText(str(Z[32])) self.d7.setText(str(Z[33])) self.d8.setText(str(Z[34])) self.d9.setText(str(Z[35])) self.e1.setText(str(Z[36])) self.e2.setText(str(Z[37])) self.e3.setText(str(Z[38])) self.e4.setText(str(Z[39])) self.e5.setText(str(Z[40])) self.e6.setText(str(Z[41])) self.e7.setText(str(Z[42])) self.e8.setText(str(Z[43])) self.e9.setText(str(Z[44])) self.f1.setText(str(Z[45])) self.f2.setText(str(Z[46])) self.f3.setText(str(Z[47])) self.f4.setText(str(Z[48])) self.f5.setText(str(Z[49])) self.f6.setText(str(Z[50])) self.f7.setText(str(Z[51])) self.f8.setText(str(Z[52])) self.f9.setText(str(Z[53])) self.g1.setText(str(Z[54])) self.g2.setText(str(Z[55])) self.g3.setText(str(Z[56])) self.g4.setText(str(Z[57])) self.g5.setText(str(Z[58])) self.g6.setText(str(Z[59])) self.g7.setText(str(Z[60])) self.g8.setText(str(Z[61])) self.g9.setText(str(Z[62])) self.h1.setText(str(Z[63])) self.h2.setText(str(Z[64])) self.h3.setText(str(Z[65])) self.h4.setText(str(Z[66])) self.h5.setText(str(Z[67])) self.h6.setText(str(Z[68])) self.h7.setText(str(Z[69])) self.h8.setText(str(Z[70])) self.h9.setText(str(Z[71])) self.i1.setText(str(Z[72])) self.i2.setText(str(Z[73])) self.i3.setText(str(Z[74])) self.i4.setText(str(Z[75])) self.i5.setText(str(Z[76])) self.i6.setText(str(Z[77])) self.i7.setText(str(Z[78])) self.i8.setText(str(Z[79])) self.i9.setText(str(Z[80]))
class ManejoProlog: #Definición de la función constructora. #E: dirección del código de prolog. #S: ninguna #R: ninguna def __init__(self, texto): try: #Validación de que archivo exista. archivo = open(texto, "r") archivo.close self.direccion = texto #Se define el atributo con la dirección del código de prolog. self.cargarConocimientos() #Se cargan los conocimientos del código. self.error = False except: archivo = open("Recetas.pl", "w") #Creación de uno nuevo. archivo.close() self.direccion = "Recetas.pl" #Se define el atributo con la dirección del código de prolog. self.cargarConocimientos() #Se cargan los conocimientos del código. self.error = True #Definición de la función que crea una nueva regla. #E: texto con el código de prolog. #S: ninguna #R: ninguna(método llamado internamente) def nuevaRegla(self, texto): archivo = open(self.direccion, "a") archivo.write('\n' + texto + '.') archivo.close() self.cargarConocimientos() #Definición de la función que lee el código de prolog y carga cada línea en una lista #E: ninguna. #S: lista con cada línea del código fuente de prolog. #R: ninguna. def leer(self): archivo = open(self.direccion, "r") lineas = archivo.readlines() archivo.close() return lineas #Función que borra una receta. #E: nombre de la receta por borrar. #S: ninguna. #R: ninguna. def borrarReceta(self, receta): lineas = self.leer() contador = 0 for i in lineas: #Se recorre el código de prolog en busca de la receta. if (i.startswith("receta("+receta+",")): #Se verifica que la receta sea igual a la ingresada. lineas.pop(contador) #Se elimina de la lista contador += 1 else: contador += 1 archivo = open(self.direccion, "w") #Se reescribe el archivo con la receta eliminada. for i in lineas: archivo.write(i) archivo.close() self.cargarConocimientos() box.showinfo("Éxito", "La receta se ha borrado con éxito.") #Función que actualiza alguna receta. #E: lista con las posiciones a modificar y todos los datos de la receta (dato vacío si no se va a modificar y nombre de la receta siempre estará). #Ejemplo: # Se tiene una receta(pizza, giovanni, italiana, queso, calentar) # Se desea cambiar solamente el dato de 'giovanni'(autor) y 'queso'(ingredientes) por 'giussepe' y 'jamón'. # Los datos de entrada serían: posiciones = [1,3], datos = ['pizza', 'giussepe', '', 'jamon', ''] #S: ninguna. #R: ninguna. def actualizarReceta(self, posiciones, datos): lineas = self.leer() contador = 0 for i in lineas: #Se recorre el código de prolog en busca de la receta a actualizar if (i.startswith("receta("+datos[0]+",")): #Se verifica que la receta sea igual a la que se desee cambiar lineas[contador] = self.actualizarReceta_aux(posiciones, datos, i[7:]) #Se sustituye la línea con el resultado de la función auxiliar. contador += 1 else: contador += 1 archivo = open(self.direccion, "w") #Se reescribe el archivo con los nuevos datos. for i in lineas: archivo.write(i) archivo.close() self.cargarConocimientos() box.showinfo("Éxito", "La receta se ha borrado con éxito.") #Función auxiliar que se encarga de actualizar los datos. #E: lista de las posiciones por modificar, datos por cambiar, datos originales. #Continuando el ejemplo: #datos = ['pizza', 'giussepe', '', 'jamon', ''] #posiciones = [1,3] #original = 'pizza, giovanni, italiana, queso, calentar' #S: línea de código prolog con los nuevos valores. #R: ninguna. def actualizarReceta_aux(self, posiciones, datos, original): separacion = original.split(",") #Se hace una lista con los datos viejos. Continuando el ejemplo anterior: #Se obtiene separacion = ['pizza', 'giovanni', 'italiana', 'queso', 'calentar'] (DATOS ORIGINALES) for i in posiciones: #Se recorre la lista con las posiciones de la lista separacion por cambiar. separacion[i] = datos[i] #Se cambia la posición obtenida en la lista posiciones, con la misma posición de la lista datos. #Se cambiaría la posición separacion[1] = datos[1] ('giussepe') y luego separacion[3] = datos[3] ('jamon') return "receta({},{},{},{},{}).\n".format(separacion[0], separacion[1], separacion[2], separacion[3], separacion[4]) #Se retorna la nueva línea de código prolog. #Función que se encarga de cargar los conocimientos. #E: ninguna. #S: código prolog cargado. #R: ninguna. def cargarConocimientos(self): self.prolog = None #Se elimina la base de conocimientos anterior self.prolog = Prolog() #Se abre nuevamente prolog self.prolog.consult(self.direccion) #Se carga el código con la dirección obtenida anteriormente
from flask import render_template, flash, redirect from app import app from forms import txtFieldsCons, txtFieldsAgr, txtFieldsAgrPla from pyswip import Prolog, Variable, Query f = open('bc.pl','a') prolog = Prolog() prolog.consult('bc.pl') def prolCons(n): i = 0 print "hola" for result in prolog.query("por_nom(X)"): r = result["X"] print str(r) @app.route('/') @app.route('/index') def index(): return render_template("index.html") @app.route('/consultar', methods = ('GET', 'POST')) def consultar(): respuesta = '' form = txtFieldsCons() if form.validate_on_submit(): if form.nombre.data != " " and form.pais.data == None and form.platillo.data == None and form.tipo.data == None and form.ingrPlat.data == None: var = "por_nom("+form.nombre.data+")"
def create_information_frame(query_txt, choices, var): label = Label(top, text=query_txt) label.pack() frame = Frame(top) for text, i in choices: b = Radiobutton(frame, text=text, variable=var, value=i) b.pack(side=LEFT) frame.pack() if __name__ == "__main__": top = Tk() p = Prolog() p.consult("advisor.pl") print "Witaj w AutomobileAdvisor!!" print "Program pomoze w wyborze odpowiedniego dla ciebie auta przy pomocy paru pytan" print "W jakim jestes wieku(wpisz numer)? 0 - mlody 1 - sredni 2 - podeszly" age_query_text = "How old are you?" age_choices = [ ("young", "young"), ("mid", "mid"), ("old", "old") ] age_var = StringVar() age_var.set(0) create_information_frame(age_query_text, age_choices, age_var) money_query_txt = "How rich are you?"
from pyswip import Prolog prolog = Prolog() prolog.consult('family') for item in prolog.query("parent_of(Parent, Child)"): print item["Parent"]