I am learning mongoDB and the below code will find the descendants of "Programming". However, I did not quite understand what would .shift do here.
var descendants = [];
var stack = [];
var item = db.categories.findOne({_id:"Programming"});
stack.push(item);
while(stack.length>0){
var current = stack.shift();
for(let i=0; i<current.children.length;i++){
var children = db.categories.findOne({_id:current.children[i]});
stack.push(children);
descendants.push(children._id);
}
}
descendants;
Could anyone help me understand this functionality?
the stack.shift() function shift the array stack one time to left. It says that the first element in the array removes from it, and returns to current.
Related
I have figured out how to run a Google App Script project/function on a form submit using the information at https://developers.google.com/apps-script/guides/triggers/events#form-submit_4.
Once I have e I can call e.response to get a FormResponse object and then call getItemResponses() to get an array of all of the responses.
Without iterating through the array and checking each one, is there a way to find the ItemResponse for a specific question?
I see getResponseForItem(item) but it looks like I have to somehow create an Item first?
Can I some how use e.source to get the Form object and then find the Item by question, without iterating through all of them, so I could get the Item object I can use with getResponseForItem(item)?
This is the code I use to pull the current set of answers into a object, so the most current response for the question Your Name becomes form.yourName which I found to be the easiest way to find responses by question:
function objectifyForm() {
//Makes the form info into an object
var myform = FormApp.getActiveForm();
var formResponses = myform.getResponses()
var currentResponse = formResponses[formResponses.length-1];
var responseArray = currentResponse.getItemResponses()
var form = {};
form.user = currentResponse.getRespondentEmail(); //requires collect email addresses to be turned on or is undefined.
form.timestamp = currentResponse.getTimestamp();
form.formName = myform.getTitle();
for (var i = 0; i < responseArray.length; i++){
var response = responseArray[i].getResponse();
var item = responseArray[i].getItem().getTitle();
var item = camelize(item);
form[item] = response;
}
return form;
}
function camelize(str) {
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()#\+\?><\[\]\+]/g, '')
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
//Use with installable trigger
function onSubmittedForm() {
var form = objectifyForm();
Logger.log(form);
//Put Code here
}
A couple of important things.
If you change the question on the form, you will need to update your
code
Non required questions may or may not have answers, so check if answer exists before you use it
I only use installable triggers, so I know it works with those. Not sure about with simple triggers
You can see the form object by opening the logs, which is useful for finding the object names
Is there any way to add colors to a sublist's row depending upon a condition. I have loaded a saved search to show output on a sublist. But now I want to highlight the rows if the difference between todays date and audit date(search output) is more than 100 days.
var search = nlapiLoadSearch('customrecord_cseg_properties', 'customsearch52');
var columns=search.getColumns();
var sublist = form.addSubList('customsublist', 'staticlist', 'List of properties');
for(var i = 0; i< columns.length; i++){
sublist.addField('customcolumn'+i, 'text', columns[i].getLabel());
}
var result= search.runSearch();
var resultIndex = 0,resultStep = 1000,resultSet,resultSets = [];
do {
resultSet = result.getResults(resultIndex, resultIndex + resultStep);
resultSets = resultSets.concat(resultSet);
resultIndex = resultIndex + resultStep;
} while (resultSet.length > 0);
nlapiLogExecution('DEBUG','The Total number of rows is',resultSets.length);
for(var w= 0; w<resultSets.length ;w++){
for(var x=0; x<columns.length; x++){
var temp;
temp=resultSets[w].getText(columns[x]);
if(temp==null || temp==''){
temp=resultSets[w].getValue(columns[x]);
}
sublist.setLineItemValue('customcolumn'+x, Number(w)+1,temp);
}
I couldn't find any functions in UI Builder API for Netsuite for doing this. Please let me know if there is any other way to do this. Above is the code which I have used to display search result in suitelet.
There is no native api for that.
You can do it by mainpulating the DOM on the client script onInit function.
Just keep in mind that DOM manipulation are risky since they can break if NetSuite will chnage the DOM structure.
I succeed to get intersection between line and polygon and display it on map. I had already post this issue here. Now I'm trying to display result for each line on console. When I tried to write console.log(result[i]) I got undefined. What is the right syntax I have to do, I tried many times. Here is my current code:
var lines = [line1, line2, line3, line4];
for (var i = 0; i < lines.length; i++) {
var intersection = [];
var result = [];
intersection = turf.intersect(lines[i], polygon1);
if (intersection) {
result.push(intersection);
L.geoJson(result, {
style: Style
}).addTo(map);
console.log(JSON.stringify(result[i]));
} else {
L.geoJson(lines[i]).addTo(map);
}
result is being defined inside your for loop which operates over lines...so why are you trying to use that loop's internal variable(meant for lines) on result, which only receives input from turf. I would think you just need console.log(result[0]), which would log your intersection.Secondly, I don't see the benefit of calling JSON.stringify for that console.log.
I wrote the code to update my table (SecurityQuestionAnswer) with new security password questions and move to old questions to another table (SecurityQuestionAnswersArchives). Total no of security questions is 3. I am able to update the current table, but when I add the same rows to history table, it shows weird data: only two records are added instead of 3 and the data is also duplicated. My code is as follows:
if (oldQuestions.Any())
{
var oldquestionstoarchivelist = new List<SecurityQuestionAnswersArchives>();
var oldquestionstoarchive =new SecurityQuestionAnswersArchives();
for (int i = 0; i < 3; i++)
{
oldquestionstoarchive.Id = oldQuestions[i].Id;
oldquestionstoarchive.SecurityQuestionId = oldQuestions[i].SecurityQuestionId;
oldquestionstoarchive.Answer = oldQuestions[i].Answer;
oldquestionstoarchive.UpdateDate = oldQuestions[i].UpdateDate;
oldquestionstoarchive.IpAddress = oldQuestions[i].IpAddress;
oldquestionstoarchive.SecurityQuestion = oldQuestions[i].SecurityQuestion;
oldquestionstoarchive.User = oldQuestions[i].User;
oldquestionstoarchivelist.Add(oldquestionstoarchive);
}
user.SecurityQuestionAnswersArchives = oldquestionstoarchivelist;
//await Store.UpdateAsync(user);
_dbContext.ArchiveSecurityQuestionAnswers.AddRange(oldquestionstoarchivelist);
_dbContext.SecurityQuestionAnswers.RemoveRange(oldQuestions);
await _dbContext.SaveChangesAsync();
oldquestionstoarchivelist.Clear();
}
UPDATE 1
The loop looks fine, It iterates three times(0,1,2), which is expected. First issue is with AddRange function to which I was passing a list , but it takes an IEnumerable input, I rectified it using following code.
IEnumerable<SecurityQuestionAnswersArchives> finalArchiveses = oldquestionstoarchivelist;
_dbContext.ArchiveSecurityQuestionAnswers.AddRange(finalArchiveses);
The other issue is duplicate data , which I am unable to figure out where the issue is. Please help me in finding this out.
Your help is much appreciated !
Got it ! Just sharing in case anybody has same issue.
The problem was with initialization at wrong place. I moved
var oldquestionstoarchive =new SecurityQuestionAnswersArchives();
in side the Forloop, now the variable will hold the unique values over each iteration.
var oldquestionstoarchivelist = new List<SecurityQuestionAnswersArchives>();
for (int i = 0; i < 3; i++)
{
var oldquestionstoarchive = new SecurityQuestionAnswersArchives();
oldquestionstoarchive.SecurityQuestionId = oldQuestions[i].SecurityQuestionId;
oldquestionstoarchive.Answer = oldQuestions[i].Answer;
oldquestionstoarchive.UpdateDate = oldQuestions[i].UpdateDate;
oldquestionstoarchive.IpAddress = oldQuestions[i].IpAddress;
oldquestionstoarchive.SecurityQuestion = oldQuestions[i].SecurityQuestion;
oldquestionstoarchive.User = oldQuestions[i].User;
oldquestionstoarchivelist.Add(oldquestionstoarchive);
}
I want to know if I get a lat-long of a user and want to check if he lies in any of the polygon that is stored in my db (MongoDB). How can this be achieved using mongoDB.
For instance my db will have 10 polygons stored as GeoJson objects. I get a lat-long and want to check if this lat-long lies in any of the 10 polygons in my DB.
Can this be achieved in MongoDB?
I dont think your particular case can be achieved in MongoDB. MongoDB does have polygon calculations with the $polygon operator. However, this operator takes a polygon and confirms if any documents are within it not the other way round.
I wrote this code in javascript it is working fine for me
var polygonData = "43.64486433588385,-79.3791389465332;43.64508171979899,-79.3930435180664;43.63682057801007,-79.38437461853027;43.63946054004705,-79.36819553375244;43.652720712083266,-79.37201499938965;43.65793702655821,-79.39111232757568;43.64927396999741,-79.37222957611084";
var lat='43.64927396999741';
var lng='-79.37222957611084';
polySearch(polygonData,lat,lng);
function polySearch(polygonData,lat,lng){
var lat_long=lat+","+lng;
var longitude_x = lng;
var latitude_y = lat;
var is_in_polygon=false;
var vertices_x=[];
var vertices_y=[];
var arr=polygonData.split(';');
for(var j=0; j<arr.length; j++){
var arr1=arr[j].split(',');
vertices_x.push(arr1[1]);
vertices_y.push(arr1[0]);
}
var points_polygon = vertices_x.length;
var isIn=isInPolygon(points_polygon, vertices_x, vertices_y, longitude_x, latitude_y);
if (isIn==1)
console.log('Which is in polygon');
else
console.log('Which is not in polygon');
function isInPolygon(points_polygon, vertices_x, vertices_y, longitude_x, latitude_y)
{
var i = 0;
var j = 0;
var c = 0;
for (i = 0, j = points_polygon-1 ; i < points_polygon; j = i++) {
var val="((("+vertices_y[i]+" > "+latitude_y+") != ("+vertices_y[j]+" > "+latitude_y+")) && ("+longitude_x+" < ("+vertices_x[j]+" - "+vertices_x[i]+") * ("+latitude_y+" - "+vertices_y[i]+") / ("+vertices_y[j]+" - "+vertices_y[i]+") + "+vertices_x[i]+"))";
if(eval(val))c=!c;
}
return c;
}
}
Sorry to only past two links, but i think these explains what should be done far better then i would:
A SO answer in the same subject
An excellent tutorial how to use mongodb geospatial indexes