Data always go to the same parameters in dialogflow - dialogflow-es

For my chatbot if user say "most" it will go to parameter "ansQ1_3", "little" will go to parameter "ansQ1_1" and "none" will go to parameter "ansQ1_0" but when i answer any words it will go to parameter "ansQ1_0" and data doesn't change because every words will go to parameter "ansQ1_0" So, how can i fix this problem? Here is my code.
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
// initialise DB connection
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'ws://reliever-gkkdtw.firebaseio.com/',
});
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
var test = "";
var stressQ1 = 0;var stressQ2 = 0;var stressQ3 = 0;var stressQ4 = 0;var stressQ5 = 0;
var answerDB = admin.database().ref();
function answer1(agent) {
if(agent.parameters.ansQ1_0 != ""){
stressQ1 = 0;
}else if(agent.parameters.ansQ1_1 != ""){
stressQ1 = 1;
}else if(agent.parameters.ansQ1_2 != ""){
stressQ1 = 2;
}else if(agent.parameters.ansQ1_3 != ""){
stressQ1 = 3;
//}else{
// stressQ1 = 0;
}
//stressQ1 = stressQ1 + agent.parameters.numStressQ1;
return answerDB.update({answer_1: stressQ1});
}
function answer2(agent) {
if(agent.parameters.ansQ2_0 != ""){
stressQ2 = 0;
}else if(agent.parameters.ansQ2_1 != ""){
stressQ2 = 1;
}else if(agent.parameters.ansQ2_2 != ""){
stressQ2 = 2;
}else if(agent.parameters.ansQ2_3 != ""){
stressQ2 = 3;
//}else{
// stressQ2 = 0;
}
return answerDB.update({answer_2: stressQ2});
}
function answer3(agent) {
if(agent.parameters.ansQ3_0 != ""){
stressQ3 = 0;
}else if(agent.parameters.ansQ3_1 != ""){
stressQ3 = 1;
}else if(agent.parameters.ansQ3_2 != ""){
stressQ3 = 2;
}else if(agent.parameters.ansQ3_3 != ""){
stressQ3 = 3;
//}else{
// stressQ3 = 0;
}
return answerDB.update({answer_3: stressQ3});
}
function answer4(agent) {
if(agent.parameters.ansQ4_0 != ""){
stressQ4 = 0;
}else if(agent.parameters.ansQ4_1 != ""){
stressQ4 = 1;
}else if(agent.parameters.ansQ4_2 != ""){
stressQ4 = 2;
}else if(agent.parameters.ansQ4_3 != ""){
stressQ4 = 3;
//}else{
// stressQ4 = 0;
}
return answerDB.update({answer_4: stressQ4});
}
function answer5(agent) {
if(agent.parameters.ansQ5_0 != ""){
stressQ5 = 0;
}else if(agent.parameters.ansQ5_1 != ""){
stressQ5 = 1;
}else if(agent.parameters.ansQ5_2 != ""){
stressQ5 = 2;
}else if(agent.parameters.ansQ5_3 != ""){
stressQ5 = 3;
//}else{
// stressQ5 = 0;
}
agent.add('Thank you for answer the question, and you can go to reliever' +
' application to reduce the stress level');
return answerDB.update({answer_5: stressQ5});
}
let intentMap = new Map();
intentMap.set('askStressQ1',answer1);
intentMap.set('askStressQ2',answer2);
intentMap.set('askStressQ3',answer3);
intentMap.set('askStressQ4',answer4);
intentMap.set('askStressQ5',answer5);
agent.handleRequest(intentMap);
});
here is the problem on request.
[all answer always go to parameter ansQ1_0]
[all answer always go to parameter ansQ1_0]
and this is example of how i manage the answer about which answer will go to what parameter.
[Training phrases]
[action and parameters]
I already seperate every answer for each parameter but all answer always go to the ansQ1_0 parameter.

The problem is a combination of two things (possibly compounded by a third):
All your parameters are of the same type.
All your training phrases are one word, of that type.
So there is no way for the training system to distinguish between when the user says a value intended for "ansQ1_0" or "ansQ1_1" for example.
When you specify a parameter for a training phrase, that parameter is expected to be able to take on any of the possible values for that type. The training phrase doesn't indicate what type you want.
Related to this, however is the third issue:
All the types are of #sys.given-name, which doesn't seem like it matches the training phrases you're trying to use. "Given name" talks about the name given to a person, and is a limited list of names.
I suspect you want to create your own entity type and set each parameter to a different type depending on what value you're expecting for each.
From here, you don't necessarily need to set it into five different parameters, however. From a quick glance at your code, you might just want to store it in one parameter and check which value was given by the user.

Related

How to verify a document from QLDB in Node.js?

I'm trying to verify a document from QLDB using nodejs. I have been following the Java verification example as much as I can, but I'm unable to calculate the same digest as stored on the ledger.
This is the code I have come up with. I query the proof and block hash from QLDB and then try to calculate digest in the same way as in Java example. But after concatinating the two hashes and calculating the new hash from the result I get the wrong output from crypto.createHash('sha256').update(c).digest("base64"). I have also tried using "base64" instead of "hex" with different, but also wrong result.
const rBlock = makeReader(res.Revision.IonText);
var block = [];
rBlock.next();
rBlock.stepIn();
rBlock.next();
while (rBlock.next() != null) {
if (rBlock.fieldName() == 'hash') {
block.push(Buffer.from(rBlock.byteValue()).toString('hex'));
}
}
console.log(block);
var proof = [];
const rProof = makeReader(res.Proof.IonText);
rProof.next();
rProof.stepIn();
while (rProof.next() != null) {
proof.push(Buffer.from(rProof.byteValue()).toString('hex'));
}
var ph = block[0];
var c;
for (var i = 0; i < proof.length; i++) {
console.log(proof[i])
for (var j = 0; j < ph.length; j++) {
if (parseInt(ph[j]) > parseInt(proof[i][j])){
c = ph + proof[i];
break;
}
if (parseInt(ph[j]) < parseInt(proof[i][j])){
c = proof[i] + ph;
break;
}
}
ph = crypto.createHash('sha256').update(c).digest("hex");
console.log(ph);
console.log();
}
I have figure it out. The problem was that I was converting the blobs to hex strings and hash them instead of the raw values. For anyone wanting to verify data in node, here is the bare solution:
ledgerInfo.getRevision(params).then(res => {
console.log(res);
const rBlock = makeReader(res.Revision.IonText);
var ph;
rBlock.next();
rBlock.stepIn();
rBlock.next();
while (rBlock.next() != null) {
if (rBlock.fieldName() == 'hash') {
ph = rBlock.byteValue()
}
}
var proof = [];
const rProof = makeReader(res.Proof.IonText);
rProof.next();
rProof.stepIn();
while (rProof.next() != null) {
proof.push(rProof.byteValue());
}
for (var i = 0; i < proof.length; i++) {
var c;
if (hashComparator(ph, proof[i]) < 0) {
c = concatTypedArrays(ph, proof[i]);
}
else {
c = concatTypedArrays(proof[i], ph);
}
var buff = crypto.createHash('sha256').update(c).digest("hex");
ph = Uint8Array.from(Buffer.from(buff, 'hex'));
}
console.log(Buffer.from(ph).toString('base64'));
}).catch(err => {
console.log(err, err.stack)
});
function concatTypedArrays(a, b) {
var c = new (a.constructor)(a.length + b.length);
c.set(a, 0);
c.set(b, a.length);
return c;
}
function hashComparator(h1, h2) {
for (var i = h1.length - 1; i >= 0; i--) {
var diff = (h1[i]<<24>>24) - (h2[i]<<24>>24);
if (diff != 0)
return diff;
}
return 0;
}

Get all date based on given requirement

My requirement.EX: date(2019-07-01) in that month 4th week i wanna particular dates based on like["1","6","7"] . ex Result like: [2019-07-28,2019-,2019-08-02,2019-08-03]
var data = {"2020-07-01",
"2020-07-02",
"2020-07-03",
"2020-07-04",
"2020-07-05",
"2020-07-06",
"2020-07-07",
"2020-07-08",
"2020-07-09",
"2020-07-10",
"2020-07-11",
"2020-07-12",
"2020-07-13",
"2020-07-14",
"2020-07-15",
"2020-07-16",
"2020-07-17",
"2020-07-18",
"2020-07-19",
"2020-07-20",
"2020-07-21",
"2020-07-22",
"2020-07-23",
"2020-07-24",
"2020-07-25",
"2020-07-26",
"2020-07-27",
"2020-07-28",
"2020-07-29",
"2020-07-30",
"2020-07-31",}
for(var n = 0; n < data.on.order.length; n++){
for(var m = 0; m < data.on.days.length; m++){
//****
if(data.on.order[n] === '1'){
firstdayMonth = moment(endOfMonth).date(0);
}else{
firstdayMonth = moment(endOfMonth).date(1);
}
// console.log('------------1',firstdayMonth)
var firstdayWeek = moment(firstdayMonth).isoWeekday(parseInt(data.on.days[m],10));
console.log('------------2 ',firstdayWeek)
// if(data.on.order[n] === "1"){
nWeeks = parseInt(data.on.order[n],10);
// }else{
// nWeeks = parseInt(data.on.order[n],10);
// }
var nextEvent = moment(firstdayWeek).add(nWeeks,'w');
// = moment(firstdayWeek).add(nWeeks,'w');
console.log('------------3',nextEvent,'---- ',nWeeks)
//****
if(nextEvent.isAfter(eventDate)){
eventDate = nextEvent;
// console.log("### eventDate: ", eventDate)
// console.log('Total dates in month ',eventDate.format("YYYY-MM-DD"))
meetings.push(eventDate.format("YYYY-MM-DD"));
}
}
}

Instagram Auto-Like JavaScript BOT

This code brings back an error of
Uncaught TypeError: Cannot read property 'innerHTML' of null
at doLike (<anonymous>:20:21)
at <anonymous>:35:1
doLike # VM1269:20
(anonymous) # VM1269:35
It has worked in the past, I got it from this website : https://blog.joeldare.com/simple-instagram-like-bot/
function getHeartElement() {
var knownHeartElementNames = ["coreSpriteHeartOpen", "coreSpriteLikeHeartOpen"];
var i = 0;
// Loop through the known heart elements until one works
for (i = 0; i < knownHeartElementNames.length; i++) {
var heartElement = document.querySelector("." + knownHeartElementNames[i]);
if (heartElement != undefined) {
break;
}
}
return heartElement;
}
function doLike() {
var likeMax = 100;
var likeElement = getHeartElement();
var nextElement = document.querySelector(".coreSpriteRightPaginationArrow");
likeCount++;
var nextTime = Math.random() * (14000 - 4000) + 4000;
if (likeElement.innerHTML.match("Unlike") == null) {
likeElement.click();
console.log(likeCount + " - liked");
} else {
console.log(likeCount + " - skipped");
}
setTimeout(function() {nextElement.click();}, 1000);
if (likeCount < likeMax) {
setTimeout(doLike, nextTime);
} else {
console.log("Nice! Time for a break.");
}
}
var likeCount = 0;
doLike();
You may want to use a tool such a Keygram - https://www.thekeygram.com
It works really well for me to gain followers

Nodejs while loop doesnt work

repeat(1000, function() {
console.log("REPEAT");
var i = 1;
var max = 1;
var mS = ini.parse(fs.readFileSync(__dirname + '/XXX/Temp/MS.ini', 'utf-8'));
var array = new Array();
while(i<=max){
if(typeof mS[i] != 'undefined'){
if(mS[i]['10'] == true){
array.push(i);
console.log(array);
}else{
console.log("ERROR");
}
i++;
max++;
}else{ //if undefined
if(mS[i+1] == 'undefined' && mS[i+2] == 'undefined') i++;
else{ i++; max++; }
}
}//while
});
It works without repeat function. (waitjs module)
Also repeat works without while loop.
I am trying to become reconciled to node.js (single thread). But i do not know, where is the mistake?
var i = 1;
var max = 1;
while(i<=max){
This condition is valid only once.
Update (due to #user949300 comments):
How many times your loop executes depends on your ini file. I recommend you to step into your code with a debugger.

Opening tabs in Chrome news reader extension

I'm trying to create a simple chrome extension using the following google RSS reader sample,
http://code.google.com/chrome/extensions/samples.html#597015d3bcce3da693b02314afd607bec4f55291
I can add links in the pop-up window that open tabs, but not from the feeds themselves.
Looping through the items in the feed, grabbing title tags and link tags, I want the title to link the the appropriate sites
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for this feed item
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var title = document.createElement("a");
title.className = "item_title";
title.innerText = itemTitle; //display title in iframe
title.addEventListener("click", titleLink); // should open link when clicking on title, but does not.
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(itemLink);
}
Any thoughts on why this is not working.
If I replace title.addEventListener("click", titleLink); with title.addEventListener("click", moreStories); each title will link to moreStories, I cannot get each title to link to itemLink.
Thanks
Its a bit hard to answer your question without the whole code, but Ill give it a shot ;)
First up, titleLink() isnt going to work because itemLink isnt known. When you create title (the link) you should of attached it to that...say title.href=itemLink then in tiltleLinks you could access that href with showUrl(event.currentTarget.href)
Also did you fix the error in that example?...if not then change frameLoaded to....
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var clssName = links[i].className;
if (clssName != "item_title" && clssName != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
If you still have probs could you attach the whole code so I can see what your doing and Ill give you a hand.
Thank you very much for your help.
code title.href=itemLink and code showUrl(event.currentTarget.href) was exactly what I needed.
For completeness, here is the full code,
<script id="iframe_script">
function reportHeight() {
var msg = JSON.stringify({type:"size", size:document.body.offsetHeight});
parent.postMessage(msg, "*");
}
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var class = links[i].className;
if (class != "item_title" && class != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
function showStory(event) {
var href = event.currentTarget.href;
parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
event.preventDefault();
}
function messageHandler(event) {
reportHeight();
}
</script>
<script>
// Feed URL.
var feedUrl = 'http://localhost/newsfeed.xml';
// The XMLHttpRequest object that tries to load and parse the feed.
var req;
function main() {
req = new XMLHttpRequest();
req.onload = handleResponse;
req.onerror = handleError;
req.open("GET", feedUrl, true);
req.send(null);
}
// Handles feed parsing errors.
function handleFeedParsingFailed(error) {
var feed = document.getElementById("feed");
feed.className = "error";
feed.innerText = "Error: " + error;
}
// Handles errors during the XMLHttpRequest.
function handleError() {
handleFeedParsingFailed('Failed to fetch RSS feed.');
}
// Handles parsing the feed data we got back from XMLHttpRequest.
function handleResponse() {
var doc = req.responseXML;
if (!doc) {
handleFeedParsingFailed("Not a valid feed.");
return;
}
buildPreview(doc);
}
// The maximum number of feed items to show in the preview.
var maxFeedItems = 10;
// Where the more stories link should navigate to.
var moreStoriesUrl;
function buildPreview(doc) {
// Get the link to the feed source.
var link = doc.getElementsByTagName("link");
var parentTag = link[0].parentNode.tagName;
if (parentTag != "item" && parentTag != "entry") {
moreStoriesUrl = link[0].textContent;
}
// Setup the title image.
var images = doc.getElementsByTagName("image");
var titleImg;
if (images.length != 0) {
var urls = images[0].getElementsByTagName("url");
if (urls.length != 0) {
titleImg = urls[0].textContent;
}
}
var img = document.getElementById("title");
// Listen for mouse and key events
if (titleImg) {
img.src = titleImg;
if (moreStoriesUrl) {
document.getElementById("title_a").addEventListener("click",moreStories);
document.getElementById("title_a").addEventListener("keydown",
function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
}
} else {
img.style.display = "none";
}
// Construct the iframe's HTML.
var iframe_src = "<!doctype html><html><head><script>" +
document.getElementById("iframe_script").textContent + "<" +
"/script></head><body onload='frameLoaded();' " +
"style='padding:0px;margin:0px;'>";
var feed = document.getElementById("feed");
// Set ARIA role indicating the feed element has a tree structure
feed.setAttribute("role", "tree");
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for the feed item.
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var item = document.createElement("div");
var title = document.createElement("a");
title.innerText = itemTitle; //display title in iframe
title.href=itemLink;
title.addEventListener("click", titleLink);
item.appendChild(title);
feed.appendChild(item);
}
if (moreStoriesUrl) {
var more = document.createElement("a");
more.className = "more";
more.innerText = "***Site Main Page*** \u00BB";
more.tabIndex = 0;
more.addEventListener("click", moreStories);
more.addEventListener("keydown", function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
feed.appendChild(more);
}
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
// -------------------------------------------------------------------
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(event.currentTarget.href);
}
function keyHandlerShowDesc(event) {
// Display content under heading when spacebar or right-arrow pressed
// Hide content when spacebar pressed again or left-arrow pressed
// Move to next heading when down-arrow pressed
// Move to previous heading when up-arrow pressed
if (event.keyCode == 32) {
showDesc(event);
} else if ((this.parentNode.className == "item opened") &&
(event.keyCode == 37)) {
showDesc(event);
} else if ((this.parentNode.className == "item") && (event.keyCode == 39)) {
showDesc(event);
} else if (event.keyCode == 40) {
if (this.parentNode.nextSibling) {
this.parentNode.nextSibling.children[1].focus();
}
} else if (event.keyCode == 38) {
if (this.parentNode.previousSibling) {
this.parentNode.previousSibling.children[1].focus();
}
}
}
function showDesc(event) {
var item = event.currentTarget.parentNode;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var iframe = items[i].getElementsByClassName("item_desc")[0];
if (items[i] == item && items[i].className == "item") {
items[i].className = "item opened";
iframe.contentWindow.postMessage("reportHeight", "*");
// Set the ARIA state indicating the tree item is currently expanded.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "true");
iframe.tabIndex = 0;
} else {
items[i].className = "item";
iframe.style.height = "0px";
// Set the ARIA state indicating the tree item is currently collapsed.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "false");
iframe.tabIndex = -1;
}
}
}
function iframeMessageHandler(e) {
// Only listen to messages from one of our own iframes.
var iframes = document.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow == e.source) {
var msg = JSON.parse(e.data);
if (msg) {
if (msg.type == "size") {
iframes[i].style.height = msg.size + "px";
}
else if (msg.type == "show") {
var url = msg.url;
if (url.indexOf("http://localhost/index.html") == 0) {
// If the URL is a redirect URL, strip of the destination and go to
// that directly. This is necessary because the Google news
// redirector blocks use of the redirects in this case.
var index = url.indexOf("&url=");
if (index >= 0) {
url = url.substring(index + 5);
index = url.indexOf("&");
if (index >= 0)
url = url.substring(0, index);
}
}
showUrl(url);
}
}
return;
}
}
}
window.addEventListener("message", iframeMessageHandler);
</script>
Thanks again for the help.
-Mike

Resources