i'm trying to use Tau-Prolog integration with javascript via this script:
<!-- index.html -->
<script type="text/javascript" src="tau-prolog.js"></script>
<script>
var TEN_THOUSAND = 10000;
function buttonClick() {
var question = document.getElementById("question-area").value;
if (question == "")
return;
ask(question);
}
function ask(question) {
var session = pl.create(TEN_THOUSAND);
var program = document.getElementById("program").value;
session.consult(program, {
success: function () {
session.query(question, {
success: function (question) {
session.answer({
success: function (answer) {
console.log(answer);
},
error: function (err) {
console.log("ERROR SHOWING THE ANSWER");
console.log(err);
},
fail: function () {
console.log("Query failed.");
},
limit: function () {
console.log("Limit excedeed");
},
});
},
error: function (err) {
console.log("ERROR QUERYING THE PROGRAM");
console.log(err);
},
});
},
error: function (err) {
console.log("ERROR PARSING THE PROGRAM");
console.log(err);
},
});
}
</script>
The prolog program linked to this script is this:
bot(KB, Question, Answer) :-
ask(KB, Question, Answer).
ask(KB, Question, Answer) :-
question(SQ, Question, []),
SQ = action(Action, Modifiers1),
member(action(Action, Modifiers2), KB),
subset(Modifiers1, Modifiers2),
sentence(SQ, Answer, []).
//other predicates
The problem i'm having is that everytime i try to query the bot/3 predicate i get the exception
uncaught exception: error(existence_error(procedure, bot/3, top_level/0)).
I tried running the program on SWI-Prolog, and it works just fine.
I tried to use more simple programs, such as:
member(H, [H | _]).
member(X, [_ | R]) :-
member(X, R).
and it worked.
I'm not using the tau-prolog node.js extension.
Can anyone help? Thanks in advance.
Related
I am trying to use my json file, busesNotArrived.json and put its contents in a <p>, however it is not working and the data in the JSON file is not displaying, here is my code:
<p>Buses Not Arrived:<br><br><span id="output"></p>
<script>
const fs = require('fs')
fs.readFile('json/busesNotArrived.json', 'utf8', (err, jsonString) => {
if (err) {
alert('Error reading Database:', err)
return
}
try {
const bus = JSON.parse(jsonString)
alert("Bus address is:", bus.busNumber)
document.getElementById('output').innerHTML = bus.BusNumber;
} catch(err) {
alert('Error parsing JSON string:', err)
}
})
</script>
Inside of my JSON file, this is what is stored:
{
"busRoute": 123123,
"busNumber": 123123
}
Javascript is not the same as node.js
require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.
You might need to directly include the modules; some of the modules might not work in the browser sandbox context.
Also, tools such as http://browserify.org/ might be useful.
And please put the error message too.
Well, I eventually figured it out, so like what #Ronnel said, you cannot use require() because that is node.js and not javascript, so you would have to use the fetch() api to get the .json file.
For anyone who would like to see the code, here it is:
<div id="myData" class='absolute1' onclick='notArrived()'><strong><u>Not Yet Arrived</u></strong><br><br></div>
<script>
fetch('json/busesNotArrived.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
var mainContainer = document.getElementById("myData");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Bus Number: ' + data[i].busNumber + "<br>" + 'Bus Route:' + ' ' + data[i].busRoute + "<br><br>";
mainContainer.appendChild(div);
}
}
</script>
|| Sorry about the Indents :P ||
And also, here is what was in the .json file so you can work off of it:
[
{
"id": "1",
"busNumber": "4024",
"busRoute": "44444"
},
{
"id": "2",
"busNumber": "4044",
"busRoute": "4444"
},
{
"id": "3",
"busNumber": "5024",
"busRoute": "55555"
}
]
Good Luck using this!
If you wanted more explanation, here is where I got the code from:
(https://howtocreateapps.com/fetch-and-display-json-html-javascript/)
I have a class in jquery that calls a service and returns a promise, which is then executed in my main area via a .done and Im trying to wrap that call in a another class I have that will make sure multiple calls are not made for the same ID. However I am finding this very very difficult to test as I can not accurcately get the promise working in phantomJS/Sinon. Heres what the area Im trying to test is
LOCKER.execute(diagRunId, function (unlock) {
SERVICE_ACCESSOR.makeCall params)
.done(function (data) {
console.log("Success!");
unlock();
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("Failed!");
unlock();
});
});
and In my test file I have my setup like so
var setup = function() {
P.mock('service-accessor', function () {
return {
makeCall: sinon.stub().returns({})
};
});
P.mock('locker', function () {
var methods = {
execute: function (lockId, wrapped) {
console.log('locked - ' + lockId)
wrapped()
},
unlock: sinon.stub()
};
return {
execute: methods.execute,
unlock: methods.unlock
};
});
P.start();
}
with finally the test just calling the method
aui.suite('Locker Test', function () {
aui.test('should lock and then unlock', testFile, {
setup: setup,
browser: function () {
P.when('utils', 'service-accessor','locker').execute(
'test', function (SERVICE_ACCESSOR, LOCKER) {
UTILS.makeCall("Identifier")
expect(LOCKER.unlock).to.have.been.called.once;
done();
}
);
},
validate: function () {},
});
});
The locker works and begins execution of the service call, but then the service call fails with
Error: PhantomJS: `TypeError: 'undefined' is not a function (evaluating 'SERVICE_ACCESSOR.callService( params).done')` near
L2492> }).fail(function (jqXHR, textStatus, errorThrown) {
From my understanding my mock should return a just a empty object when its being called, but then I dont understand a) Why its going to fail and b) Whats undefined? My assumption is that its because Im not returning three objects, but Im trying to get it to succeed first! How can I correctly stub/mock this?
In the end I didn't make a promise or use a stub. I used the following function that would call the done and fail in my call instead.
function() {
return { done: function(callback) {
if(window.makeParamountCallSuccess) {
callback({"data": "data"});
return {
fail: function(){}
}
} else {
return {
fail: function(failCallback){ failCallback("jqXHR", "textStatus", "errorThrown")}
}
}
}
}
}```
I have a few codes of js which is calling from a controller in python. I am facing an error which is createdb() takes 2 arguments, 1given. May I know what should I put here in the function of my js here? I am still learning with javascript. Thank you for understanding.
.js
$(function(){
$("#start_trial").click(function(){
createDatabase();
});
});
function createDatabase(){
session.rpc('/custom/createdb', {
db_name : db_name
}).then(function() {
console.log("Database created successfully");
});
}, function () {
console.log("calling /custom/createdb caused an exception!");
});
}
.py
#http.route('/custom/createdb', type='json', auth="public", methods=["POST"], website=True)
def createdb(self, db_name):
session = self._authenticate()
if not session:
return json.dumps(False)
# create a new database
headers = {'Content-Type': 'application/json'}
create_db_url = "http://localhost:8090/cus_cus/create_db"
data = {"jsonrpc": 2.0, "params": { "name": db_name } }
_logger.debug("Creating database...")
r = session.post(url=create_db_url, data=json.dumps(data), headers=headers)
if r.ok:
return json.dumps(True)
else:
return json.dumps(False)
i have checked the native-script-paytm integration plugin. but both git-hub repository are not running instead it gives stack exception. so i created my own project and some how its doing something. but here i have lot of questions on how to get 'mid', 'order id' etc.
can anyone give step by step details for this.
const createViewModel = require("./main-view-model").createViewModel;
const Paytm = require("#nstudio/nativescript-paytm").Paytm;
const paytm = new Paytm();
exports.pageLoaded = function (args) {
const page = args.object;
page.bindingContext = createViewModel();
}
exports.onPayWithPaytm = function (args) {
console.log("Paying");
paytm.setIOSCallbacks({
didFinishedResponse: function (response) {
console.log("got response");
console.log(response);
},
didCancelTransaction: function () {
console.log("User cancelled transaction");
},
errorMissingParameterError: function (error) {
console.log(error);
}
});
const order = {
// This will fail saying duplicate order id
// generate your own order to test this.
MID: "Tomcas09769922377481",
ORDER_ID: "ORDER8874",
CUST_ID: "CUST6483",
INDUSTRY_TYPE_ID: "Retail",
CHANNEL_ID: "WAP",
TXN_AMOUNT: "10.00",
WEBSITE: "APP_STAGING",
CALLBACK_URL: "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp",
CHECKSUMHASH:
"NDspZhvSHbq44K3A9Y4daf9En3l2Ndu9fmOdLG+bIwugQ6682Q3JiNprqmhiWAgGUnNcxta3LT2Vtk3EPwDww8o87A8tyn7/jAS2UAS9m+c="
};
paytm.createOrder(order);
paytm.initialize("STAGING");
paytm.startPaymentTransaction({
someUIErrorOccurred: function (inErrorMessage) {
console.log(inErrorMessage);
},
onTransactionResponse: function (inResponse) {
console.log(inResponse);
},
networkNotAvailable: function () {
console.log("Network not available");
},
clientAuthenticationFailed: function (inErrorMessage) {
console.log(inErrorMessage);
},
onErrorLoadingWebPage: function (
iniErrorCode,
inErrorMessage,
inFailingUrl
) {
console.log(iniErrorCode, inErrorMessage, inFailingUrl);
},
onBackPressedCancelTransaction: function () {
console.log("User cancelled transaction by pressing back button");
},
onTransactionCancel: function (inErrorMessage, inResponse) {
console.log(inErrorMessage, inResponse);
}
});
}
For reference
As mentioned in the plugin's ReadMe file,
You will need a working backend server to generate paytm orders. Do not generate the order or checksum in the app.
Hello stackoverflow members.
I´m deploying following piece of code into my parse cloud. The code works fine as long as the marked area is not in it.
Why am i getting the error: cannot call method ´get´ of undefined, only when i put constraints in my query? The error happens in line 24. And like i said, if there is no constraints, the method get works.
Parse.Cloud.define("getUserLookingForChat", function(request, response) {
var remote_id_searcher = request.params.username;
var private_name_searcher = request.params.private_name;
var intentions_searcher = request.params.intentions;
var gender_searcher = request.params.gender;
var looking_gender_searcher = request.params.lookinggender;
var query = new Parse.Query("userLookingForChat");
//WITHOUT THIS PIECE IT WORKS
/*query.equalTo("gender", looking_gender_searcher);
query.equalTo("lookinggender", gender_searcher);
if(intentions_searcher === "date"){
query.notcontainedIn("intentions", "friends");
}
if(intentions_searcher === "friends"){
query.notcontainedIn("intentions", "date");
}*/
//__
query.first({
success: function(user) {
response.success(user);
Parse.Push.send({
channels: [user.get("username")],
data: {
action: "com.example.ACCEPT_INVENTATION",
remote_id_partner: remote_id_searcher,
private_name: private_name_searcher,
age: "20"
}
});
user.destroy({
success:function() {
response.success(message);
},
error:function(error) {
response.error("Could not delete object.");
}
});
},
error: function() {
response.error("no user is currently looking for a chat");
}
});
});
Thanks for your help already.