Enumerate tables and list names - excel

I'm working on some code, mostly just playing around, with the Office-js API (v1.1), trying to do some things. I can take code examples and run them just fine, but I don't know Javascript well enough to know what I'm doing.
I took an example of enumerating tables and am trying to add some things to it, but it's not working and I don't know why. Can anyone help me out here?
The code:
Excel.run(function (ctx) {
var tables = ctx.workbook.tables;
var tableNames = ctx.workbook.tables.load("name");
return ctx.sync().then(function() {
console.log("Tables in workbook:");
if (tables.count = 0) {
console.log("No tables found");
} else {
for (var i = 0; i < tableNames.items.length; i++)
{
console.log(i + ": " + tableNames.items[i].name);
}
}
console.log("------------------------");
});
}).catch(function (error) {
console.log(error);
});
In the console log I get this message:
Tables in workbook:
TypeError: Assignment to read-only properties is not allowed in strict mode
I'm basing this off code found here: http://officesnippetexplorer.azurewebsites.net/#/snippets/excel (select 'Table', and snippet 'Get tables in workbook'). Any help would be greatly appreciated!
Thanks,
Zack Barresse

I don't think you mean to change tables.count, do you?
That's what the error is telling you - you have:
if (tables.count = 0) {
but you really wanted:
if (tables.count == 0) {
The first tries to set tables.count to 0, the second tests if tables.count is equal to 0.

Related

Make //repeat command correct length node & discord.js

Currently for my discord bot I am trying to make a repeat command for me and my friends but the issue is since I'm new to discord.js and node I don't know any good alternatives to "startswith", what this means is while the "//repeat #user" command works, "//repeattesttext #user" also does the same thing. Is there any way to prevent this? Here is my code:
if (!msg.guild) return;
if (msg.content.startsWith('//repeat')) {
if (msg.member.roles.cache.has("744347114255155201")) {
if (!active4) {
const user = msg.mentions.users.first();
if (user) {
const memb = msg.guild.member(user);
if (memb) {
if (active4) {
active4 = false;
msg.channel.send("Repeat Deactivated.")
} else {
id2 = memb.id
active4 = true
msg.channel.send("Repeat Activated")
}
}
}
} else {
active4 = false
msg.channel.send("Repeat Deacivated.")
}
return
} else {
msg.channel.send("You don't have RBLX permissions.")
return
}
}
Any help would be appreciated and since I'm new if you can please explain how your code works. Even if you can't I'll still be grateful for an answer of any kind!
Instead of checking if the string starts with //repeat, you should check if the first word is equal to that.
This can be achieving by separating the msg.content in an array containing its words.
msg.content.split(' ') gives that array.
msg.content.split(' ')[0] === '//repeat' is the if statement you are looking for.

If statements not working with JSON array

I have a JSON file of 2 discord client IDs `{
{
"premium": [
"a random string of numbers that is a client id",
"a random string of numbers that is a client id"
]
}
I have tried to access these client IDs to do things in the program using a for loop + if statement:
for(i in premium.premium){
if(premium.premium[i] === msg.author.id){
//do some stuff
}else{
//do some stuff
When the program is ran, it runs the for loop and goes to the else first and runs the code in there (not supposed to happen), then runs the code in the if twice. But there are only 2 client IDs and the for loop has ran 3 times, and the first time it runs it goes instantly to the else even though the person who sent the message has their client ID in the JSON file.
How can I fix this? Any help is greatly appreciated.
You may want to add a return statement within your for loop. Otherwise, the loop will continue running until a condition has been met, or it has nothing else to loop over. See the documentation on for loops here.
For example, here it is without return statements:
const json = {
"premium": [
"aaa-1",
"bbb-1"
]
}
for (i in json.premium) {
if (json.premium[i] === "aaa-1") {
console.log("this is aaa-1!!!!")
} else {
console.log("this is not what you're looking for-1...")
}
}
And here it is with return statements:
const json = {
"premium": [
"aaa-2",
"bbb-2"
]
}
function loopOverJson() {
for (i in json.premium) {
if (json.premium[i] === "aaa-2") {
console.log("this is aaa-2!!!!")
return
} else {
console.log("this is not what you're looking for-2...")
return
}
}
}
loopOverJson()
Note: without wrapping the above in a function, the console will show: "Syntax Error: Illegal return statement."
for(i in premium.premium){
if(premium.premium[i] === msg.author.id){
//do some stuff
} else{
//do some stuff
}
}
1) It will loop through all your premium.premium entries. If there are 3 entries it will execute three times. You could use a break statement if you want to exit the loop once a match is found.
2) You should check the type of your msg.author.id. Since you are using the strict comparison operator === it will evaluate to false if your msg.author.id is an integer since you are comparing to a string (based on your provided json).
Use implicit casting: if (premium.premium[i] == msg.author.id)
Use explicit casting: if (premium.premium[i] === String(msg.author.id))
The really fun and easy way to solve problems like this is to use the built-in Array methods like map, reduce or filter. Then you don't have to worry about your iterator values.
eg.
const doSomethingAuthorRelated = (el) => console.log(el, 'whoohoo!');
const authors = premiums
.filter((el) => el === msg.author.id)
.map(doSomethingAuthorRelated);
As John Lonowski points out in the comment link, using for ... in for JavaScript arrays is not reliable, because its designed to iterate over Object properties, so you can't be really sure what its iterating on, unless you've clearly defined the data and are working in an environment where you know no other library has mucked with the Array object.

Netsuite Email Merge Error (SSS_MERGER_ERROR_OCCURRED)

I'm creating a Scheduled SuiteScript in Netsuite that uses the 1.0 version of the API. The goal is to have the script run once per day to send our first time customers an email with their name (or company name) and other pre-formatted content using a Scriptable Email Template.
Once it is up and running, we are planning to extend it with additional functionality, but this is the base that we would like to have running before adding additional code.
The error message is:
SSS_MERGER_ERROR_OCCURRED - Merger error occurred: Unexpected error encountered during merging.
Everything goes smooth up until actually using .merge(). I've added the code below:
function thankyouletter() {
var searchresults = nlapiSearchRecord(null, 'customsearch127'); // minus: , filters
if (searchresults == null) {
response.write('Var searchresults is null.');
return;
} else {
nlapiLogExecution('DEBUG', 'START - Found search results', 'Starting iteration');
for (var i = 0; searchresults != null && i < searchresults.length; i++) {
var searchresult = searchresults[i];
var searchCols = searchresult.getAllColumns();
var internalid = searchresult.getId(); // Will be used after testing is finished
var emailMerger = nlapiCreateEmailMerger(38);
emailMerger.setEntity('customer', 24886); // Set for Testing
var mergeResult = emailMerger.merge(); // Fails and errors here
var emailSubject = mergeResult.getSubject();
var emailBody = mergeResult.getBody();
nlapiSendEmail(nlapiGetUser(), customerid, emailSubject, emailBody, null, null, null, null);
nlapiLogExecution('DEBUG', 'Merge Troubleshooting', 'Just after SendEmail');
}
}
var usageRemaining = context.getRemainingUsage();
nlapiLogExecution('DEBUG', 'usage left => ' + usageRemaining);
nlapiLogExecution('DEBUG', 'Script Finished.', 'Mission Complete');
}
I've removed some of the nlapiLogExecution lines for readability. If anything is confusing or additional info is needed, please let me know and I'll add/fix it.
I've dug through piles of Netsuite's documentation, SuiteAnswers, and web searches trying to find the solution, but the error message is pretty vague.
Any help is greatly appreciated! Thank you.
After further research, I found that the Freemarker Template had a syntax error, and that was causing the error.

protractor: filter until finding first valid element

I am doing e2e testing on a site that contains a table which I need to iterate "until" finding one that doesn't fail when I click on it.
I tried it using filter and it is working:
this.selectValidRow = function () {
return Rows.filter(function (row, idx) {
row.click();
showRowPage.click();
return errorMessage.isDisplayed().then(function (displayed) {
if (!displayed) {
rowsPage.click(); // go back to rows Page, all the rows
return true;
}
});
}).first().click();
};
The problem here is that it is iterating all available rows, and I only need the first one that is valid (that doesn't show an errorMessage).
The problem with my current approach is that it is taking too long, as my current table could contain hundreds of rows.
Is it possible to filter (or a different method) and stop iterating when first valid occurrence appears?, or could someone come up with a better approach?
If you prefer a non-protractor approach of handling this situation, I would suggest async.whilst. async is a very popular module and its highly likely that your application is using it. I wrote below code here in the editor, but it should work, you can customize it based on your needs. Hopefully you get an idea of what I'm doing here.
var found = false, count = 0;
async.whilst(function iterator() {
return !found && count < Rows.length;
}, function search(callback) {
Rows[count].click();
showRowPage.click();
errorMessage.isDisplayed().then(function (displayed) {
if (!displayed) {
rowsPage.click(); // go back to rows Page, all the rows
found = true; //break the loop
callback(null, Rows[count]); //all good, lets get out of here
} else {
count = count + 1;
callback(null); //continue looking
}
});
}, function aboutToExit(err, rowIwant) {
if(err) {
//if search sent an error here;
}
if(!found) {
//row was not found;
}
//otherwise as you were doing
rowIwant.click();
});
You are right, filter() and other built-in Protractor "functional programming" methods would not solve the "stop iterating when first valid occurrence appears" case. You need the "take some elements while some condition evaluates to true" (like the itertools.takewhile() in Python world).
Fortunately, you can extend ElementArrayFinder (preferably in onPrepare()) and add the takewhile() method:
Take elements while a condition evaluates to true (extending ElementArrayFinder)
Note that I've proposed it to be built-in, but the feature request is still open:
Add takewhile() method to ElementArrayFinder

how to find specific string in key value pair in mongodb

i am having data in mongodb like that
[
{
"name":"silvester",
"product":"laptop,iphone,mobile,phone"
},
{
"name":"john",
"product":"cycle,bus,phone,laptop"
},
{
"name":"franklin",
"product":"cycle,phone"
}
]
How to find that laptop is in product key.
if product key look like this
{
"name":"XXX",
"product":"laptop"
}
I can easily find that name by using this db.collection.find("product":"laptop");
So how to find this?
Also let me know this three website name running under using backbone.js and node.js and mongodb technology such as www.trello.com .
sorry for my worst english..
Using regex with mongodb
This worked for me
db.collection.find({"product": /laptop/})
Updated Answer
If you wish to use variables, try something like this:
var abc = "laptop";
// other stuff
userdetails.find({"product":new RegExp(abc)}).toArray(function(err,result){
if (err) console.log ("error: "+err);
else
{
// if you want the length
console.log(result.length);
// if you actually want to see the results
for (var i = 0; i < result.length; i++)
{
console.log(result[i]);
}
}
});
Updated One More Time
var abc = "laptop";
// other stuff
// note this is case sensitive. if abc = "Laptop", it will not find it
// to make it case insensitive, you'll need to edit the RegExp constructor
// to this: new RegExp("^"+abc+",|, "+abc+"(?!\w)", "i")
userdetails.find({"product":new RegExp("^"+abc+",|, "+abc+"(?!\w)")}).toArray(function(err,result){
if (err) console.log ("error: "+err);
else
{
// if you want the length
console.log(result.length);
// if you actually want to see the results
for (var i = 0; i < result.length; i++)
{
console.log(result[i]);
}
}
});
regex will work perfectly fine. there is also good news for you as monogdb will be releasing full text search index in the upcoming version
http://docs.mongodb.org/manual/release-notes/2.4/#text-indexes

Resources