I have defined a parameter named age of the type #sys.age
When trying to access it through fulfillment, its showing no output in the first line and falls into the else clause.
function EntryPointHandler(agent) {
const number = agent.parameters.age;
agent.add(`inside fulfilment1`+ number);
if(number < 18 )
{
agent.add(`Sorry, we dont have products for under ages under 18`);
}
else {
agent.add(`Thank you, do you have an ID`);
}
}
To access age value, you should use the following,
const age = agent.parameters.age.amount;
Related
I have build an API using Nodejs and express which listens to a query string like so:
http://localhost:3000/get?pos=52.4919643,13.3772875&bboxSize=400&query=wfs&outputType=geojson
I need all of these arguments to work. what would be the correct way to test a string like that for correctness? Currently I try something like this:
type OutputType = "glb" | "cityjson" | "geojson"
type QueryType = "lod2" | "wfs"
let lat: number
let lon: number
let bboxSize: number
let output: OutputType
let query: QueryType
//try to get all necessary arguments for running the api
//TODO: codereview?
try {
lat = Number((request.query.pos as string).split(",")[0])
lon = Number((request.query.pos as string).split(",")[1])
bboxSize = isFinite(Number(request.query.bboxSize as string)) ? Number((request.query.bboxSize as string)) : 200
output = request.query.outputType as OutputType
query = request.query.query as QueryType
if (bboxSize > maxOutputSize) {
throw "bbox Size too big";
}
if (!isFinite(lat) || !isFinite(lon) || !isFinite(bboxSize)) {
throw "lat lon bboxSize need to be numbers";
}
if (query === "wfs" && output !== "geojson") {
throw "only geojson is allowed for wfs data";
}
}
catch (err) {
return response.status(400).json(`Error in Query`)
}
it works, but how can I be sure that this really works? Would I go for a regex (it would be super hard to maintain I guess..)? or is there a "standard" how to check strings for correctness?
I am concerned about the developer experience (changing the string would need to be reflected in the test too in a simple matter..) and of course about the fact that I could have forgotten a case where it does not catch an error...
Any idea would be great!
Cheers
I want to get random user ID from users with reaction under some message, but almost always when I'm trying to get all users with reaction it returns No Winner even if I reacted
Code:
setTimeout(()=> {
// msg.reactions.removeAll
if(msg.reactions.cache.get("π").users.cache.filter(user => !user.bot).size > 0) {
const winner = msg.reactions.cache.get("π").users.cache.filter(user => !user.client).random().id
message.channel.send(`Winner: #<${winner}>`)
} else {
message.channel.send("No winner.")
}
}, time-Date.now())
I had to add
Intents.FLAGS.GUILD_MESSAGE_REACTIONS to my intents.
I modified your code and it's working. You get No winner result every time because of user.client. You should use user.bot.
Here's a code I modified:
setTimeout(()=> {
const reaction = message.reactions.cache.get("π")
const reactionUsers = reaction.users.cache.filter(user => !user.bot)
if(reactionUsers.size > 0){
const winner = reactionUsers.random()
const winnerId = winner.id
message.channel.send(`Winner: <#${winnerId}>`)
} else {
message.channel.send(`No winner`)
}
}, 10000)
Change 1: I used user.bot instead of user.client
Change 2: I assigned all variables before using them (It's more readable for me).
Change 3: #<${winnerId}> is not correct. Use <#${winnerId}> instead. (# should be inside of <> tag)
I'm running cron that is checking price each 30 seconds and will return me a value of asset.
If the price will be different than previous price, i would like to log it.. I'm testing this because this will be very usable for me in the future ideas... price variable is holding the price. My goal is to do some action when the variable is different.
//Stuff above the code like cron and general discord client.on β
//this will log current price of asset
console.log(price, 'PRICE UPDATED!')
// tried to compare price however this is unsucessful, as it doesn't do anything...
var Previousprice = null;
function foo() {
var Currentprice = $(price.toFixed(2))
if (Previousprice == Currentprice) {
$(price.toFixed(2))
console.log('Price is same!')
}
Previousprice = Currentprice
console.log('Price has changed!')
//new discord action...
}
});
});
});
});
So far I also tried this, but i think this is completely useless and won't work that way...
console.log(price, 'PRICE UPDATED!')
let Previousprice = null;
let Currentprice = price
if (price) {
let Previousprice = price.toFixed(2)
console.log(price, 'Price defined')
} else if(Previousprice === Currentprice) {
console.log(price, 'Price is same')
} else if(Previousprice !== Currentprice) {
let Previousprice = price.toFixed(2)
console.log(price, 'Price changed!')
}
Logs:
1.29739982471208 PRICE UPDATED!
1.29739982471208 Price defined
1.29739982471208 PRICE UPDATED!
1.29739982471208 Price defined
1.29660532105896 PRICE UPDATED!
1.29660532105896 Price defined
You are re-declaring and assigning previousPrice = null; every 30 seconds. Can't give you specifics without seeing the surrounding code but what you generally want is a global variable like currentPrice, initialised to 0 when the app first runs. something like this should work:
// initialise a global variable with inital value of 0
let currentPrice = 0;
// Stuff above the code like cron and general discord client.on
console.log(price, 'PRICE UPDATED!');
if (price !== currentPrice) {
console.log(`Price changed from ${currentPrice} to ${price}`);
currentPrice = price;
}
else {
console.log(`Price remains at ${currentPrice}`);
}
The first run will obviously change the price from 0 to the first initial price, but that's fine.
Alright, so have you tried previous_price = current_price after having previous_price set to some price currently, run it, and then after console.log if it is different or something, then it gets set to current price, and then it will change after every internal?
This should work.
I am working on app needs an NZBN Code to register with stripe payments, when a user can enter any NZBN that cause Stripe issues,
i entered the https://api.business.govt.nz/services/v4/nzbn to check it but no obivious api call contain the real check of the NZBN code .
is there any way please ?
EDIT:
i am passing the NZBN number as tax_id to Stripe so Stripe check it with what ever api and tell me that the tax_id is not a valid nzbn , but when i put a valid nzbn it takes it correclty how to prevent entering a not valid NZBN before going to stripe
This is a really old question but it has no answer, so I thought I'd share;
NZBN (different from the NZ GST number) is a plain old GTIN 13. This is my TypeScript for checking for 1) a valid GTIN, and then 2) a GTIN13 specifically
/**
* Boolean function to test code against GTIN published checksum method(s)
*/
export function isGTIN(text: number | string): boolean {
try {
const r = /[\D]/g,
gtin = typeof text === "number" ? text.toString().replace(r, "") : text.replace(r, ""),
paddedValue = gtin.padStart(14, "0")
if (!gtin.match(/^(\d{8}|\d{12,14})$/)) return false
let result = 0
for (let i = 0; i < paddedValue.length - 1; i += 1) {
result += parseInt(paddedValue.charAt(i), 10) * (i % 2 === 0 ? 3 : 1)
}
return (10 - (result % 10)) % 10 === parseInt(paddedValue.charAt(13), 10)
} catch (err) {
console.error(err.message)
return false
}
}
/**
* Boolean function to test NZBN (GTIN13) against published checksum method
*/
export function isNZBN(text: number | string): boolean {
try {
const r = /[\D]/g,
gtin = typeof text === "number" ? text.toString().replace(r, "") : text.replace(r, "")
// NZBN is a GTIN 13
if (gtin.length !== 13) return false
else return isGTIN(gtin)
} catch (err) {
console.error(err.message)
return false
}
}
While you could rely on validation error instead of implementing this yourself, you can also optionally pre-validate the input. This is really up to you.
Validation follows the OECD TIN specifications, such as for NZ IRDs, which looks to be 8 or 9 numeric digits. If the NZBN has a different spec than this, you'd need to implement a validation check before submitting.
So i'm working with moment.js.
I see you can translate a date into a human-friendly format using moment().fromNow();
Is there a way to do the opposite?
For example, I want to turn this --> "2 weeks ago" into a normal date format or UNIX timestamp.
I sifted through the documentation but couldnt find anything. Any direction would help, thanks.
Depending on how complicated/different the input strings can be, you could do this:
//parse out the number and the duration
var inputString = "2 weeks ago";
var myRegExp = /^(\d+)\s(\w+)\sago$/;
var results = myRegExp.exec(inputString);
var num = results[1];
var duration = results[2];
moment().subtract(duration,num).toString() //or whatever format you prefer
Note this will work for input strings of the format "number duration ago".
Hope that helps!
In some cases .fromNow() returns string like "30+ days ago". The regex provided in above solution doesn't handle to parse that properly.
Here's the updated regex to handle that case:
var myRegExp = /^(\d+)\+?\s(\w+)\sago$/;
Here is the method that I used to reverse it for the current moment.js locale. I tested it on a few locales and it should work for every locale but it might not.
Change the last two .toString() functions to .valueOf() to get numerical values.
Moment actually doesn't have the week name data for all languages right now, so the function will assume that the string is a week if it could not find the value.
Some languages use translation functions instead of having built in values so the script will not work on those either! If you manually specify your language data then it should work.
//test en locale
moment.locale("en");
console.log(reversefromNow("5 days ago"));
console.log(reversefromNow("in 5 days"));
//test ja locale
moment.locale("ja");
console.log(reversefromNow("5 ζ₯ε"));
console.log(reversefromNow("5 ζ₯εΎ"));
function reversefromNow(input) {
let relativeLocale = JSON.parse(JSON.stringify(moment.localeData()._relativeTime));
let pastfutureObject = {
future: relativeLocale.future,
past: relativeLocale.past
};
delete relativeLocale.future;
delete relativeLocale.past;
//detect if past or future
let pastfuture;
for (const [key, value] of Object.entries(pastfutureObject)) {
if (input.indexOf(value.replace("%s", "")) != -1) {
pastfuture = key;
}
}
//detect the time unit
let unitkey;
for (const [key, value] of Object.entries(relativeLocale)) {
if (input.indexOf(value.replace("%d", "")) != -1) {
unitkey = key.charAt(0);
}
}
//if its not in the data, then assume that it is a week
if (unitkey == null) {
unitkey = "w";
}
const units = {
M: "month",
d: "day",
h: "hour",
m: "minute",
s: "second",
w: "week",
y: "year"
};
//Detect number value
const regex = /(\d+)/g;
let numbervalue = input.match(regex) || [1];
//Add if future, subtract if past
if (pastfuture == "past") {
return moment().subtract(numbervalue, units[unitkey]).valueOf();
} else {
return moment().add(numbervalue, units[unitkey]).valueOf();
}
}