Exemplo n.º 1
1
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
Exemplo n.º 2
0
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]
Exemplo n.º 4
0
    def test_issue_4(self):
        """
       	Patch for a dynamic method

        Ensures that the patch is working.

        https://code.google.com/p/pyswip/issues/detail?id=4
        """

        from pyswip import Prolog
        
        Prolog.dynamic('test_issue_4_d/1')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test2)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 4)
        
        Prolog.retract('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 3)
        
        Prolog.retractall('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 1)
Exemplo n.º 5
0
    def test_issue_Unicode(self):
        """
        Unicode support
        """

        from pyswip import Prolog, registerForeign

        Prolog.assertz('отец(дима,миша)')
        Prolog.assertz('отец(дима,настя)')
        Prolog.assertz('отец(дима,света)')
        Prolog.assertz('отец(сергей,оля)')
        Prolog.assertz('отец(сергей,саша)')
        results = list(Prolog.query('отец(дима,Ребенок)'))
        self.assertEqual(len(results), 3)

        results = list(Prolog.query('отец(Отец,Ребенок)'))
        self.assertEqual(len(results), 5)

        callsToHello = []
        def hello(t):
            callsToHello.append(t.value)
        hello.arity = 1

        registerForeign(hello)

        p = Prolog.query("отец(дима,X), hello(X)")
        result = list(p)

        self.assertEqual(callsToHello, ['миша', 'настя', 'света'])
Exemplo n.º 6
0
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 start():
    kitchen_env = "resources/kitchen.env.xml"
    env = Environment()  # create the environment
    env.SetViewer('qtcoin')  # start the viewer
    env.Load(kitchen_env)  # load a model

    ssRave = interpeter_extended()
    ssRave.addVariable('kitchen', env)

    ## Example 1: Generate a map from the enitre environment
    expr = """SELECT  above(a.this, b.this), 
                      below(a.this, b.this), 
                      isEnabled(a.this),     
                      volume(a.this),        
                      position(a.this),      
                      isRobot(a.this),       
                      isKinbody(a.this)      
            FROM a=kitchen, b=kitchen      
            WHERE not (isSensor(a.this) or isSensor(b.this)) 
            AS prolog;"""

    print "query:", expr
    prog = SelectScript.compile(expr)
    prolog = Prolog()
    for result in ssRave.eval(prog):
        print result
        prolog.assertz(result)

    print list(prolog.query("above(table, X)"))
    print list(prolog.query("volume(Obj, V), V > 1.0"))
    print list(prolog.query("position(_, P)"))
Exemplo n.º 8
0
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'])
Exemplo n.º 9
0
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()
Exemplo n.º 10
0
    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))
Exemplo n.º 11
0
    def test_issue_4(self):
        """
       	Patch for a dynamic method

        Ensures that the patch is working.

        https://code.google.com/p/pyswip/issues/detail?id=4
        """

        from pyswip import Prolog

        Prolog.dynamic('test_issue_4_d/1')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test1)')
        Prolog.assertz('test_issue_4_d(test2)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 4)

        Prolog.retract('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 3)

        Prolog.retractall('test_issue_4_d(test1)')
        results = list(Prolog.query('test_issue_4_d(X)'))
        self.assertEqual(len(results), 1)
Exemplo n.º 12
0
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
Exemplo n.º 13
0
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
Exemplo n.º 14
0
class AbalonePrologAIEngine(object):

	# loads the abalone.pl prolog file
	def __init__(self):
		self.swipl = Prolog()
		self.swipl.consult("./abalone.pl")
		result = list(self.swipl.query("start_game"))
		if not result:
			raise Exception('Error in initializing the game')

	# make_move
	#   @color - the color of the current player
	#   @from_cell - the beginning cell of the move
	#   #end_cell - the end cell of the move
	#   execute in prolog:
	#       can_make_move query for validation the move is valid
	#       make_move query for executing the move in prolog.
	#   returns tuple of the MoveType and Move Direction
	def make_move(self, color, from_cell, to_cell='not_exist'):
		result = list(self.swipl.query(
			"can_make_move(MoveType, %s, Direction, %s, %s), "
			"make_move(MoveType, %s, Direction, %s, %s)" % (
				color, from_cell, to_cell, color, from_cell, to_cell)))
		if not result:
			return None, None
		return PROLOG_MOVES_TO_PUSH_TYPE[str(result[0]['MoveType'])], result[0]['Direction']

	# make_move
	#   @color - the color of the current player
	#   execute in prolog:
	#       get_best_move query for getting the computer best move
	#       make_move query for executing the move in prolog.
	#   returns tuple of the MoveType, Move Direction, FromCell, EndCell
	def get_best_move(self, color):
		result = list(self.swipl.query(
			"get_best_move(%s, MoveType, Direction, From, To)" % color))
		if not result:
			return None, None, None, None
		query = "make_move(%s, %s, %s, %s, %s)" % (
				(result[0]['MoveType']), color, result[0]['Direction'], result[0]['From'], result[0]['To'])
		result2 = list(self.swipl.query(query))
		if not result2:
			print('unexpected error')
		return PROLOG_MOVES_TO_PUSH_TYPE[str(result[0]['MoveType'])], result[0]['Direction'], \
			   result[0]['From'], result[0]['To']

	def change_level(self, level):
		self.swipl.retract("level(OldLevel)" )
		self.swipl.asserta('level(%s)' % level)

	# get_current_score
	#   execute in prolog
	#       game_score query for getting the current game score
	#   returns tuple of the number of white cells, blackcells, and weather the game ended.
	def get_current_score(self):
		result = list(self.swipl.query("game_score(Black, White, Victory)"))
		return result[0]['White'], result[0]['Black'], result[0]['Victory']
Exemplo n.º 15
0
def entry_point():
    prolog = Prolog()
    prolog.consult(os.path.join(os.path.dirname(__file__), 'wumpus.pl'))
    steps = list(map(lambda d: d.value, next(prolog.query('explore(X)'))['X']))
    win_result = bool(list(prolog.query('win(_)')))
    lose_result = bool(list(prolog.query('lost(_)')))
    if not win_result or lose_result:
        raise ValueError(win_result, lose_result)
    print('I won, positions: ')
    pprint(steps)
Exemplo n.º 16
0
def append_prolog_knowledge_base():
    global answers, hero_name
    prolog = Prolog()
    answ = hero_name.get()
    print(answ)
    print(answers)
    query_str = "add_hero({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, \"{}\", Res)".format(
        *answers, answ)
    prolog.query(query_str)
    arr = list(prolog.query(query_str))
    print(arr)
Exemplo n.º 17
0
def run_aleph(output_dir):
    prolog = Prolog()
    prolog.consult("../sources/aleph/aleph_orig.pl")
    print(
        list(
            prolog.query("working_directory(_, \"" + output_dir +
                         "/aleph_input/\")")))
    print(list(prolog.query("read_all(sp)")))
    print(list(prolog.query("induce")))
    print(list(prolog.query("working_directory(_, \"../\")")))
    print(list(prolog.query("write_rules(\"explanation.txt\")")))
    print("The explanation was saved to '" + output_dir + "explanation.txt'")
Exemplo n.º 18
0
def api():
    # instanciamos prolog
    prolog = Prolog()
    # obtenemos la peticion con los datos
    data = request.get_json()
    print(data)
    # consultamos nuestro archivo de prolog
    prolog.consult("engine.pl")
    prolog.assertz("persona(fs)")
    #vemos que conocimientos tiene el usuario y los agregamos
    # a la DB de prolog
    if data['linguistico'] > 0:
        # prolog.query("ling(A).");
        prolog.assertz("persona(linguistico)")
    if data['mate'] > 0:
        # prolog.query("mate(A).");
        prolog.assertz("persona(matematico)")
    if data['espacio'] > 0:
        # prolog.query("esp(A).");
        prolog.assertz("persona(espacio)")
    if data['interpersonal'] > 0:
        # prolog.query("inte(A).");
        prolog.assertz("persona(interpersonal)")
    if data['creativa'] > 0:
        # prolog.query("cre(A).");
        prolog.assertz("persona(creativo)")

    carrera = []
    # hacemos un query para ver si cumple con alguna carrera
    abogado = list(prolog.query("abogado(A)"))
    arquitecto = list(prolog.query("arquitecto(A)"))
    civil = list(prolog.query("civil(A)"))
    electronico = list(prolog.query("electronico(A)"))
    informatico = list(prolog.query("informatico(A)"))

    if len(abogado) > 0 and (abogado[0]["A"] == 1):
        carrera.append('abogado')
    if len(arquitecto) > 0 and (arquitecto[0]["A"] == 1):
        carrera.append('arquitecto')
    if len(civil) > 0 and (civil[0]["A"] == 1):
        carrera.append('civil')
    if len(electronico) > 0 and (electronico[0]["A"] == 1):
        carrera.append('electronico')
    if len(informatico) > 0 and (informatico[0]["A"] == 1):
        carrera.append('informatico')

    # prolog.query("retractall(persona(_))");
    # prolog.query("purgar");
    prolog.retractall("persona(_)")
    print(list(prolog.query('getConocimientos(A).')))
    del prolog
    res = make_response(jsonify({"message": carrera}), 200)
    return res
Exemplo n.º 19
0
    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 getShortestPath(start, destination, time_list):
    prolog = Prolog()
    prolog.consult("TrainDB/location.pl")

    consult_data_file = getDataInTimeInterval(time_list)
    prolog.consult("TrainDB/" + consult_data_file + ".pl")
    print(consult_data_file)
    prolog.consult("astar_nextstation.pl")
    prolog.consult("TrainDB/station.pl")

    astar_query = "astar(" + start + "," + destination + ",PATH,COST)."  ## ASTAR
    shortest_path_result = list(prolog.query(astar_query))

    path_list = []
    for i in range(len(shortest_path_result[0]['PATH'])):
        path_list.append(str(shortest_path_result[0]['PATH'][i]))

    train_path_query = "trainPath(" + str(
        path_list) + ", ROW, COL, TRAIN)."  ## TRAIN PATH
    train_path_result = list(prolog.query(train_path_query))

    train_path_list = []
    for i in range(len(train_path_result[0]['TRAIN'])):
        train_path_list.append(str(train_path_result[0]['TRAIN'][i]))

    station_info_query = "station(" + str(
        path_list[len(path_list) -
                  1]) + ", EXIT, PLACE)."  ## station information
    station_info_result = list(prolog.query(station_info_query))

    station_exit_list = []
    for i in range(len(station_info_result[0]['EXIT'])):
        station_exit_list.append(str(station_info_result[0]['EXIT'][i]))

    station_place_list = []
    for i in range(len(station_info_result[0]['PLACE'])):
        station_place_list.append(str(station_info_result[0]['PLACE'][i]))

    ans_list = []
    ans_list.append(path_list)
    ans_list.append(str(shortest_path_result[0]['COST']))
    ans_list.append(train_path_list)
    ans_list.append(str(train_path_result[0]['ROW']))
    ans_list.append(str(train_path_result[0]['COL']))
    ans_list.append(station_exit_list)
    ans_list.append(station_place_list)

    return ans_list
Exemplo n.º 21
0
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')
Exemplo n.º 22
0
def prolog_query(query_string):
    prolog = Prolog()
    prolog.consult("knowledge.pl")
    results = []
    for res in prolog.query(query_string):
        results.append(res)
    return results
Exemplo n.º 23
0
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')
Exemplo n.º 24
0
async def main(query, text):
    query = query
    prolog = Prolog()
    doc = nlp(text)
    buf = []
    for word in doc.sentences[0].words:
        word_props = Word(word)
        buf.append(word_props.get_prolog_str())

    prolog_str = "\n".join(buf)
    prolog_str += "\n"
    # prolog_str += 'is_subj_of_pred(SUBJ,PRED):-head(SUBJ_NUM,PRED_NUM),deprel(SUBJ_NUM,"nsubj"),upos(PRED_NUM,"VERB"),text(SUBJ_NUM,SUBJ),text(PRED_NUM,PRED).'
    prolog_str += query

    queryy = query.split(":")[0]
    new_file_name = randomname(10) + ".pl"
    with open(new_file_name, mode="w") as f:
        f.write(prolog_str)
    with io.StringIO() as f:
        sys.stdout = f
        consult = prolog.consult(new_file_name)
        answer = list(prolog.query(queryy))
        sys.stdout = sys.__stdout__
    os.remove("./" + new_file_name)
    return answer
Exemplo n.º 25
0
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
Exemplo n.º 26
0
def create_contract_prolog(e,q_in,q_out):
	print('Process create contract: starting...')

	while(1):
		e.wait()
		
		#we take the contract body from queue
		#each contract is identified by guid, and has a specific query
		guid, query, contract_body = q_in.get().split("\n",2)
		contract_clauses = contract_body.split("\n")

		#create the Prolog instance
		prolog = Prolog()
		#assert each clause to Prolog knowledge base
		for clause in contract_clauses:
			#empty clauses are ignored
			if clause == "":
				continue
			clause_for_assert = "("+clause.split(".")[0]+")"
			#the assert statement equivalent to assertz Prolog command
			prolog.assertz(clause_for_assert)
		
		#consult Prolog with the given query 
		#check if the answer list is null then the answer is False
		answer = bool(list(prolog.query(query)))
		print(query)

		q_out.put(guid+"\n"+str(answer))
Exemplo n.º 27
0
    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)]
Exemplo n.º 28
0
    def test_issue_8(self):
        """
        Callbacks can cause segv's

        https://code.google.com/p/pyswip/issues/detail?id=8
        """

        from pyswip import Prolog, registerForeign

        callsToHello = []

        def hello(t):
            callsToHello.append(t)

        hello.arity = 1

        registerForeign(hello)

        prolog = Prolog()
        prolog.assertz("parent(michael,john)")
        prolog.assertz("parent(michael,gina)")
        p = prolog.query("parent(michael,X), hello(X)")
        result = list(p)  # Will run over the iterator

        self.assertEqual(len(callsToHello), 2)  # ['john', 'gina']
        self.assertEqual(len(result), 2)  # [{'X': 'john'}, {'X': 'gina'}]
Exemplo n.º 29
0
    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
Exemplo n.º 30
0
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"
    )
Exemplo n.º 31
0
 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
Exemplo n.º 32
0
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 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")
Exemplo n.º 35
0
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))
Exemplo n.º 36
0
def index(request):
    if request.method == "GET":
        print "AQUI"
        prolog = Prolog()
        print "AQUI TAMBIEN"
        #prolog.consult("recetas.pl")
        print "AQUI TAMBIEN ES"
        ingredientes = list(prolog.query("ingrediente(X)"))
        #salida = str(ingredientes)
        salida = "Hola"

    return HttpResponse(salida)
Exemplo n.º 37
0
 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
Exemplo n.º 38
0
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
Exemplo n.º 39
0
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)
Exemplo n.º 41
0
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()
Exemplo n.º 42
0
    def test_issue_8(self):
        """
        Callbacks can cause segv's

        https://code.google.com/p/pyswip/issues/detail?id=8
        """

        from pyswip import Prolog, registerForeign

        callsToHello = []
        def hello(t):
            callsToHello.append(t)
        hello.arity = 1

        registerForeign(hello)

        prolog = Prolog()
        prolog.assertz("parent(michael,john)")
        prolog.assertz("parent(michael,gina)")
        p = prolog.query("parent(michael,X), hello(X)")
        result = list(p)   # Will run over the iterator
        
        self.assertEqual(len(callsToHello), 2)  # ['john', 'gina']
        self.assertEqual(len(result), 2) # [{'X': 'john'}, {'X': 'gina'}]
Exemplo n.º 43
0
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>";
Exemplo n.º 44
0
# 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"]
Exemplo n.º 45
0
X = Variable()

q = Query(father("michael",X))
while q.nextSolution():
    print "Hello,", X.value
q.closeQuery()


prolog = Prolog()

#prolog.consult("e:/ia/testeXadrezBFa.pl")
prolog.consult("f:/temp/pee1.pl")
#prolog.assertz("posicao(2,3)")

for result in prolog.query("mover( 3/4, X/Y, C )"):
    print result['X'], result['Y'], result['C']


for result in prolog.query("aStar( 6/6, V, C)",maxresult=1):
    for estado in result['V']:
        print estado.args

V = Variable()
C = Variable()
E = Variable()
aStar = Functor("aStar", 3)
posicao = Functor("posicao",2)
q = Query(posicao( V, C) )
pos= '3/7'
#q = Query(aStar(pos, V, C) )
Exemplo n.º 46
0
from pyswip import Prolog

prolog = Prolog()

prolog.assertz("hello(test)")
prolog.assertz("hello(world)")

print list(prolog.query("hello(world)"))
print list(prolog.query("hello(x)"))

for result in prolog.query("hello(X)"):
    print result["X"]

print "--------------"
for result in prolog.query("retractall(hello(_))"):
    continue

for result in prolog.query("hello(X)"):
    print result["X"]

print "--------------"
Exemplo n.º 47
0
	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)
	ans=next(query)
	code=ans['X']
	print(code)
	#p.assertz(code)
Exemplo n.º 48
0
class Game():
    def __init__(self,radius=80):
        self.win = Tk()
        self.radius = radius
        self.pawnList1 = []
        self.pawnList2 = []
        self.generatePawns()
        self.playerOne = True
        self.pawnSelected = False
        self.chaining = False
        self.capturing = False
        self.selectedPawn = None
        self.captured = None
        self.prolog = Prolog()
        self.prolog.consult("clauses.pl")
        self.prolog.asserta("hos(dummy)")
        self.defaultPosition()
        self.board = Board(self.pawnList1,self.pawnList2,self.radius,self.win,self)
        self.board.mainloop()

    def getPawnByName(self,name):
        for p in self.pawnList1:
            if p.getName() == name:
                return p
        for p in self.pawnList2:
            if p.getName() == name:
                return p

    def checkMove(self,pos):
        validMoveQuery = "canMove("+self.selectedPawn.getName()+",NewPos)"
        l = list(self.prolog.query(validMoveQuery))
        validMoves = []
        for i in l:
            validMoves.extend(i.values())
        if pos in validMoves:
            return True
        else:
            return False

    def queryCapturing(self,p):
        capturingQuery = "canEat("+p.getName()+",Target,NewPos)"
        l = list(self.prolog.query(capturingQuery))
        posAfterCapturing = []
        for i in l:
            posAfterCapturing.extend(i.values())
        return posAfterCapturing

    def checkCapturing(self,pos):
        posAfterCapturing = self.queryCapturing(self.selectedPawn)
        if pos in posAfterCapturing:
            self.captured = self.getPawnByName(posAfterCapturing[posAfterCapturing.index(pos)+1])
            self.capturing = True
            return True
        else:
            return False

    def defaultPosition(self):
        positions = ["position(a1,60)",
                     "position(b1,71)",
                     "position(c1,62)",
                     "position(d1,73)",
                     "position(e1,64)",
                     "position(f1,75)",
                     "position(g1,66)",
                     "position(h1,77)",
                     "position(a2,00)",
                     "position(b2,11)",
                     "position(c2,02)",
                     "position(d2,13)",
                     "position(e2,04)",
                     "position(f2,15)",
                     "position(g2,06)",
                     "position(h2,17)"]
        for position in positions:
            self.prolog.asserta(position)
        #for pos in self.prolog.query("position(X,Y)"):
            #print pos["X"], pos["Y"]

    def modifyPosition(self):
        for position in self.prolog.query("retractall(position(_,_))"):
            pass

        for pawn in self.pawnList1:
            self.prolog.asserta(
                "position(" + pawn.getName() + "," +
                str(pawn.getRow()) + str(pawn.getColumn()) + ")")
        
        for pawn in self.pawnList2:
            self.prolog.asserta(
                "position(" + pawn.getName() + "," +
                str(pawn.getRow()) + str(pawn.getColumn()) + ")")
            
    def generatePawns(self):
        for i in range(8):
            name = chr(97+i)
            self.pawnList1.append(Pawn(name+"1", 6 + (i % 2), i, 'blue', self.radius))
            self.pawnList2.append(Pawn(name+"2", 0 + (i % 2), i, 'red', self.radius))

    def selectPawn(self,p):
        self.pawnSelected = True
        self.selectedPawn = p
#        self.board.highlightPawn(p)

    def unselectPawn(self):
        self.pawnSelected = False
#        self.board.drawPawn(self.selectedPawn)
        self.selectedPawn = None

    def addHos(self, pawn):
        self.prolog.asserta("hos("+pawn.getName()+")")

    def checkHos(self,pawn):
        if pawn in self.pawnList1:
            if pawn.row == 0:
                if pawn.hos is not True:
                    pawn.hos = True
                    self.addHos(pawn)
        elif pawn in self.pawnList2:
            if pawn.row == 7:
                if pawn.hos is not True:
                    pawn.hos = True
                    self.addHos(pawn)

    def punish(self):
        if self.playerOne:
            for p in self.pawnList1:
                if len(self.queryCapturing(p)) > 0:
                    self.deletePawn(p)
                    break
        else:
            for p in self.pawnList2:
                if len(self.queryCapturing(p)) > 0:
                    self.deletePawn(p)
                    break

    def move(self, pos):
        if self.checkCapturing(pos) or self.checkMove(pos):
            self.selectedPawn.move(pos // 10, pos % 10)
            if self.capturing:
                self.deletePawn(self.captured)
            moved = True
        else:
            moved = False

        if moved:
            if not self.capturing:
                self.punish()
            self.checkHos(self.selectedPawn)
            self.chaining = True
            self.modifyPosition()
            if self.selectedPawn == None or (len(self.queryCapturing(self.selectedPawn)) == 0 and self.capturing or not self.capturing):
                self.playerOne = not self.playerOne
                self.chaining = False
                self.capturing = False
                self.captured = None
                self.botPlays()
            '''print "---------"
            for pos in self.prolog.query("position(X,Y)"):
                print pos["X"], pos["Y"]
            print "-------------------------------"
            for hos in self.prolog.query("hos(X)"):
                print hos["X"]'''
        
    def deletePawn(self, pawn):
        if pawn in self.pawnList1:
            self.pawnList1.remove(pawn)
        else:
            self.pawnList2.remove(pawn)
        self.board.deletePawn(pawn)

        if pawn == self.selectedPawn:
            self.selectedPawn = None

    def generateStates(self):
        lst = []
        for pos in self.prolog.query("position(X,Y)"):
            #print pos["X"]
            lst.append([pos["X"], pos["Y"]])
        return lst

    def generateHoses(self):
        lst = []
        for pos in self.prolog.query("hos(X)"):
            #print pos["X"]
            lst.append(pos["X"])
        return lst
    def botPlays(self):
        s = str(self.generateStates())
        s = s.replace("'",'')
        h = str(self.generateHoses())
        h = h.replace("'",'')
        states = []
        for res in self.prolog.query("minimax("+s+","+h+",NewStates)"):
	        states.append(res["NewStates"])
        #for res in self.prolog.query("minimaxVal(_,1,States)"):
        #    states.append(res["States"])
        states = states[0]
        for i in range(len(states)):
            states[i][0] = str(states[i][0])
        '''for i in range(len(self.pawnList1)):
            pawn = self.pawnList1[i]
            pos = states[i][1]
            if states[i][0] == pawn and states[i][1] != pawn.row*10+pawn.col:
                self.board.deletePawn(pawn)
                self.selectedPawn.move(pos // 10, pos % 10)
                self.board.drawPawn(pawn)'''

        for i in range(len(self.pawnList2)):
            pawn = self.pawnList2[i]
            pos = states[i][1]
            for j in range(len(states)):
                if states[j][0] == pawn.name and states[j][1] != pawn.row*10+pawn.col:
                    self.board.deletePawn(pawn)
                    pawn.move(states[j][1]//10, states[j][1]%10)
                    self.board.drawPawn(pawn)

        for i in range(len(states)):
            states[i] = states[i][0]

        for pawn in self.pawnList1:
            if pawn.name not in states:
                self.pawnList1.remove(pawn)
                self.board.deletePawn(pawn)

        for pawn in self.pawnList2:
            if pawn.name not in states:
                self.pawnList2.remove(pawn)
                self.board.deletePawn(pawn)

        self.modifyPosition()
        self.playerOne = not self.playerOne
Exemplo n.º 49
0
# -*- coding: utf8 -*-
from pyswip import Prolog

prolog = Prolog()

prolog.consult('base.pro')
# prolog.retract("software('Nazario Contruções',fincanceiro,python,'',web,_,'2014-5-1','2014-7-7',2500)")
results = prolog.query("software(Nome,Categoria,Linguagem,Licensa,Plataforma,Tamanho,DataI,DataF,Valor )")
for result in results:
    print result
Exemplo n.º 50
0
from pyswip import Prolog, registerForeign, Atom

def atom_checksum(*a):
    print a
    if isinstance(a[0], Atom):
        r = sum(ord(c)&0xFF for c in str(a[0]))
        a[1].value = r&0xFF
        return True
    else:
        return False

p = Prolog()
registerForeign(atom_checksum, arity=2)
print list(p.query("X='Python', atom_checksum(X, Y)"))
Exemplo n.º 51
0
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# 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.


from pyswip import Prolog, registerForeign, Atom


def atom_checksum(*a):
    if isinstance(a[0], Atom):
        r = sum(ord(c)&0xFF for c in str(a[0]))
        a[1].value = r&0xFF
        return True
    else:
        return False

p = Prolog()
registerForeign(atom_checksum, arity=2)
print list(p.query("X='Python', atom_checksum(X, Y)", catcherrors=False))
Exemplo n.º 52
0
from pyswip import Prolog

prolog = Prolog()
prolog.assertz("father(michael,john)")
prolog.assertz("father(michael,gina)")
result = list(prolog.query("father(michael,X)"))
print result
Exemplo n.º 53
0
from pyswip import Prolog

prolog = Prolog()

prolog.consult('family')

for item in  prolog.query("parent_of(Parent, Child)"):
	print item["Parent"]


Exemplo n.º 54
0
# 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..."
Exemplo n.º 55
0
    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]))
Exemplo n.º 56
0
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)"))
Exemplo n.º 57
0
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})
Exemplo n.º 58
0
#Stvaramo dvodimenzionalno polje koje je jednostavno lista unutar liste
grid=[]
for row in range(N):
    #Dodajemo praznu listu koja æe u sebi imate podatke o svako æeliji
    grid.append([])
    for column in range(N):
        grid[row].append(0) # Dodaj podatak u æeliju

#Preko dodatnog paketa pyswip pozivamo predikat iz prologa
#koji nam vraæa listu rješenja te svako rješenje spremamo
#u zasebno polje
solutions = []
number = 0
prolog = Prolog()
prolog.consult('queens.pl')
for result in prolog.query("solution(S)", maxresult = 20):
    print (result)
    solutions.append(number)
    solutions[number] = result["S"]
    number += 1

number = 0



# Inicijalizacija pygame-a
pygame.init()
 
# Postavljanje širine i visine ekrana
size=[50*N,50*N]
screen=pygame.display.set_mode(size)