I am developing a chatbot using HTML and javascript. I used an open source ELIZA-style code available online as my starting point. However I noticed an issue with the code:
For example the code says:
var convpatterns = new Array (
new Array (".*my name is (.*)\.", "Nice to meet you $1!"),
new Array ("^I (?:wish |would like )(?:I could |I was able to |to be able to )(.*)\.","What would it be like to be able to $1?"));
uinput = ""
soutput = ""
dialog = ""
function mainroutine() {
uinput = document.mainscreen.BasicTextArea4.value;
dialog = dialog + "User: " + uinput + '\r' + "\n";
conversationpatterns()
dialog = dialog + '\r' + "\n";
updatescreen()
}
function conversationpatterns() {
for (i=0; i < convpatterns.length; i++) {
re = new RegExp (convpatterns[i][0], "i");
if (re.test(uinput)) {
len = convpatterns[i].length - 1;
index = Math.ceil( len * Math.random());
reply = convpatterns[i][index];
soutput = uinput.replace(re, reply);
soutput = initialCap(soutput);
dialog = dialog + "System: " + soutput + '\r' + "\n";
break;
}
}
}
However if I ask the bot "I wish I could fly", the bot will reply "What would it be like to be able to fl"
Noticed the "fly" is missing a "y" letter at the end. It happens everytime no matter what I typed, for example "my name is Michelle", and the bot reply "Nice to meet you Michell", again missing the last letter of the variable.
Remove last dot in your regexp
new Array ("^I (?:wish |would like )(?:I could |I was able to |to be able to )(.*)\.","What would it be like to be able to $1?"))
----------------------------------------------------------------------------------^^
Change to this
new Array ("^I (?:wish |would like )(?:I could |I was able to |to be able to )(.*)","What would it be like to be able to $1?"))
You can test it here:
https://regex101.com/r/hN2gA2/1
Related
I have a form that I created to make my work easier and recently figured out how to make certain fields automatically generate a comma and separates after 5 letters or numbers have been typed into it (CPT codes for medical claims that I have to look up) using the same coding you would for putting spaces between numbers. I also have coding here that would force letters to be capitalized since I'm a bit OCD about that stuff for work:
<input name="checkbox24" type="checkbox" id="checkbox24" onClick="FillDetails24(this.form);" /><span style="background-color:yellow">CPT</span>
<input type = "text" size="8" class = "uc-text-smooth" name="textfield24" id="textfield24" />
<script language = "JavaScript">
const forceKeyPressUppercase = (e) => {
let el = e.target;
let charInput = e.keyCode;
if((charInput >=97) && (charInput <= 122)) { // lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey) { // no modifier key
let newChar = charInput - 32;
let start = el.selectionStart;
let end = el.selectionEnd;
el.value = el.value.substring(0, start) + String.fromCharCode(newChar) + el.value.substring(end);
el.setSelectionRange(start+1, start+1);
e.preventDefault();
}
}
};
document.querySelectorAll(".uc-text-smooth").forEach(function(current) {
current.addEventListener("keypress", forceKeyPressUppercase);
});
document.getElementById('textfield24').addEventListener('input', function (g) {
g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim();
});
</script>
When I use the checkbox, it automatically generates pre-written text using the following JavaScript:
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value + ". " + '\n' + '\n' );
}
However, because of the way that I put it together, the end result would be, "Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT V2020, 99213,. " The extra comma at the end is driving me nuts.
Since it was my first time using this
document.getElementById('textfield24').addEventListener('input', function (g) {
g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim();
});
with this
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value + ". " + '\n' + '\n' );
}
I'm not certain how I can code it to eliminate the last comma generated at the end when it pulls the value of textfield24.
This is a very long, complex html form I've coded by hand for fun and for personal use at work for 4 years with only a couple years of HTML training and a little bit of JavaScript I learned in high school forever ago and I've been busting my butt to make this work perfectly so that I only have to tweak the pre-written stuff when things change at work.
I'm at a loss on how to continue. Any suggestions?
You can replace with regex /,$/.
f = { textfield24: { value: 'V2020, 99213,'} }
console.log(f.textfield24.value);
console.log(f.textfield24.value.replace(/,$/, ''));
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value.replace(/,$/, '') + ". " + '\n' + '\n' );
}
you can use substring to remove the last comma, but you have to make sure that the last comma always be there. otherwise, you're gonna remove something else.
const example = "Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT V2020, 99213,. ";
const result = example.substring(0, example.lastIndexOf(",")) + ".";
console.log(result);
I'm trying to build a simple app to post a message to Slack for every new row in a Google Spreadsheet. I can get the info from the sheet and post it to the logger, and I can post to Slack, but I can only seem to get this to work with the first row in the loop (whereas the logger will receive all values for all rows). I'm probably just messing up the way the loops work (new to this) but having stared at it for a few hours now I can't see it. My intention is to set this to trigger on edit (it's populated from a Google Form), so I've added a column to mark when a Slack message has been sent, just to avoid a mad loop of endless messages for whatever reason.
I've tried logging the output and can get all values there. Putting the post to Slack part of the code in the same place only results in one post, though.
//Set up a variable to show when we've sent a message to Slack
var slackSentText = "Yes";
//This is hte Slack hook
var url = "https://hooks.slack.com/services/tokens!";
function getNewInfo() {
var sheetname = "Info"
var myspreadsheet = SpreadsheetApp.openById('secretID!');
var sheet = myspreadsheet.getSheetByName(sheetname);
// set rows until work out how to do more elegantly...
var startRow = 8; // First row of data to process
var numRows = 5; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 11);
var data = dataRange.getValues();
// iterate and make variables for Slack
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var idNumber = row[0];
var projectType=row[6];
var supplierName=row[2];
var projectName=row[3];
var projectDescription=row[4];
var projectStatus=row[1];
var projectDate=row[5];
var slackSent = row[10];
// check if column is marked with Slack sent note and if so ignore. If not send Slack
if (slackSent !== slackSentText) {
// Slack bit
var slackMessage = {
"channel": "ID-number-bot",
"username": "ID-bot",
"text": "\n :white_check_mark:" +
"\n *New Project:* " + idNumber +
"\n *Project Name:* " + projectName +
"\n *Supplier:* " + supplierName +
"\n *Project Status:* " + "["+projectStatus+"]" +
"\n *Project Description:* " + "_"+projectDescription+"_" +
"\n *Project Type:* " + projectType +
"\n *Estimated Delivery Date:* " + projectDate +
"\n"+ slackSent +
"\n Job folder string: \n" + "RCM "+jobNumber+" "+projectName +
"\n \n"
};
var options = {
"method": "post",
"contentType": "application/json",
"payload": JSON.stringify(slackMessage)
};
return UrlFetchApp.fetch(url,options);
sheet.getRange(startRow + i, 11).setValue(slackSentText);
Logger.log("jobNumber:"+jobNumber)
Logger.log("projectType:"+projectType)
Logger.log("supplierName:"+supplierName)
Logger.log("projectName:"+projectName)
Logger.log("projectDescription:"+projectDescription)
Logger.log("projectStatus:"+projectStatus)
Logger.log("projectDate:"+projectDate)
}
}
// SpreadsheetApp.flush();
}
Thanks very much everyone. Hopefully I've given enough info.
As #Tanaike proposed, your problem should be fixed by changing:
return UrlFetchApp.fetch(url,options);
To this:
UrlFetchApp.fetch(url,options)
The return keyword gets you out of the loop. The code finds return in the first iteration, so it doesn't go on with the following rows, and that's why you are only getting the first row sent.
I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!
I have a very basic code. However I am not able to clear the of the Year with the id (userYOB) on clicking the alert ok. The code works only for the which asks for year. Its not just the clearing of but I also want to bring the place holder back once alert is clicked ok.
Thanks for help.
[fiddle] http://jsfiddle.net/vineetgnair/j8zjjj9r/26/
var d = new Date();
var currentYear = d.getFullYear();
function test() {
var userYearOfBirth = document.getElementById("userYOB").value;
var authorisedAge = 19;
var currentAge = parseInt(currentYear - userYearOfBirth);
//console.log(currentAge);
if (currentAge < authorisedAge) {
alert("You are not authorised to visit the site");
document.getElementById("userYOB").value = " ";
} else {
alert("Welcome to the site!");
userYearOfBirth = " ";
}
}
In else part say
document.getElementById("userYOB").value= " ";
instead of
userYearOfBirth = " ";
Because userYearOfBirth is a simple string so updating it doesn't update the value of textbox.
Please add the following lines after the else part,
document.getElementById("userYOB").value= " ";
document.getElementById("userMOB").value= " ";
document.getElementById("userDOB").value= " ";
This will clear the fields and bring back the placeholder. The reason why
userYearOfBirth = " "
doesn't work is because in the following line the variable actually holds the value not the element itself,
var userYearOfBirth = document.getElementById("userYOB").value;
It would be more advisable if you, replaced the above line with,
var userYearOfBirth = document.getElementById("userYOB");
now you have the reference to the element in the variable. You can easily change the elements value by,
userYearOfBirth.value = " ";
Personally, I prefer the latter method cause its less code. I hope this helps!! :)
So i'm using multiple if statements to draw data from a database based on the users search criteria.
What i'm struggling with is
if(request.getParameter("searchProperty")!= ""){
SearchStatement = "town_city = '" + request.getParameter("searchProperty") + "'";
if(request.getParameter("bedrooms") != "0"){
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'";
}
}
with the idea that this concatenates a string to use as a query in the database, and bring back the results the user is searching for (this is a property searching website). I thought i'd done the if statement correctly. From what i understand, from what i've put, if the user were to select 0 in bedrooms it should return ALL results, but instead it returns NONE (who wants a house without a bedroom..) Can somebody explain what's going wrong please?
here's where the SQL statement is built and input
MyProperties = bookSQL.executeQuery("SELECT * FROM PROPERTIES WHERE " + SearchStatement);
with the expected outcome being, for example
SELECT * FROM PROPERTIES WHERE Location = 'input' AND Bedrooms = 'value'
unless value = 0 where it should just be
SELECT * FROM PROPERTIES WHERE Location = 'input'
i think the problem is with this statement,
request.getParameter("bedrooms") != "0"
should be something like this ,
(!request.getParameter("bedrooms").isEmpty())
Remember you are comparing the strings
so if is "0"
if(request.getParameter("bedrooms").equals("0")){
return SearchStatement ;
}
else {
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'"
}
Hope this helps!!