express-handlebars unable to print Object content , - express-handlebars

express-handlebars
exports.All_category = async (req,res)=>{
var categories = await Category.find({},{"date":0, '__v':0})
.then(result=> {
console.log(result);
res.render('category', { title: 'Category', cate: 'active',result });
})
I want to Print only name and id but its printing full Objects

You are printing the whole object because the model.find({}); method returns an object to result which you print afterwards.
So if you want to only print the id and the name then you should instead write:
console.log('Id: ' + result._id + ' Name: ' + result.name);

TO add run time option in handle bar engine
app.engine('hbs', exphbs({layoutsDir: __dirname + '/views/layouts', extname: 'hbs',
defaultLayout:'layout'}));
the above mentions app engine that i created first then i added some runtime options
like this
app.engine('hbs', exphbs({layoutsDir: __dirname + '/views/layouts', extname: 'hbs',
defaultLayout:'layout',
runtimeOptions: {
allowProtoPropertiesByDefault: true,
allowProtoMethodsByDefault: true
}}));

Related

How to separate multiple columns from a range in an array?

I have a range of data in a Google Sheet and I want to store that data into an array using the app script. At the moment I can bring in the data easily enough and put it into an array with this code:
var sheetData = sheet.getSheetByName('Fruit').getRange('A1:C2').getValues()
However, this puts each row into an array. For example, [[Apple,Red,Round],[Banana,Yellow,Long]].
How can I arrange the array by columns so it would look: [[Apple,Banana],[Red,Yellow],[Round,Long]].
Thanks.
It looks like you have to transpose the array. You can create a function
function transpose(data) {
return (data[0] || []).map (function (col , colIndex) {
return data.map (function (row) {
return row[colIndex];
});
});
}
and then pass the values obtained by .getValues() to that function..
var sheetData = transpose(sheet.getSheetByName('Fruit').getRange('A1:C2').getValues())
and check the log. See if that works for you?
Use the Google Sheets API, which allows you to specify the primary dimension of the response. To do so, first you must enable the API and the advanced service
To acquire values most efficiently, use the spreadsheets.values endpoints, either get or batchGet as appropriate. You are able to supply optional arguments to both calls, and one of which controls the orientation of the response:
const wb = SpreadsheetApp.getActive();
const valService = Sheets.Spreadsheets.Values;
const asColumn2D = { majorDimension: SpreadsheetApp.Dimension.COLUMNS };
const asRow2D = { majorDimension: SpreadsheetApp.Dimension.ROWS }; // this is the default
var sheet = wb.getSheetByName("some name");
var rgPrefix = "'" + sheet.getName() + "'!";
// spreadsheetId, range string, {optional arguments}
var single = valService.get(wb.getId(), rgPrefix + "A1:C30");
var singleAsCols = valService.get(wb.getId(), rgPrefix + "A1:C30", asColumn2D);
// spreadsheetId, {other arguments}
var batchAsCols = valService.batchGet(wb.getId(), {
ranges: [
rgPrefix + "A1:C30",
rgPrefix + "J8",
...
],
majorDimension: SpreadsheetApp.Dimension.COLUMNS
});
console.log({rowResp: single, colResp: singleAsCols, batchResponse: batchAsCols});
The reply will either be a ValueRange (using get) or an object wrapping several ValueRanges (if using batchGet). You can access the data (if any was present) at the ValueRange's values property. Note that trailing blanks are omitted.
You can find more information in the Sheets API documentation, and other relevant Stack Overflow questions such as this one.

Saving scraped data to mysql database through phantomjs and casperjs

Hi I am working on a web scraper, first I was trying to scrape using php CURL, but then I faced a problem that I wasn't able to scrape the sites which loads through AJAX and then I shifted to 'phantom JS' and 'casper JS`.
Now I have successfully installed the webkit and can scrape the data from any website, but I am unable to save the data for long use in a database. Simply, for later use. What I want to do is, whatever data I have scraped I want to save that to mySql database.
Is there any way I can achieve such functionality? I have tried sending Ajax request to send the data to the database but failed.
I came up with one another solution for instance, that is when I scrape the data from the specified website, I push the data to an array called data[] and then I write that data to a .json file. Where each bunch of data is saved in array of objects form which is get from JSON.stringify(data).
Now, I don't know if how can I get that file data and save it in database? Is it possible that, whenever the scraping is finished, right after I grab data from that .json file and save it to database.
For now just take this code as an example
var casper = require('casper').create();
var file = require('fs');
var data = [];
casper.start('http://casperjs.org/', function() {
data.push(this.getTitle());
file.write("file.json", JSON.stringify(data), "a");
});
casper.run();
A Proof Of Concept, using jq :
#!/bin/bash
casperjs script.js
[[ -s file.json ]] || exit 1
jq '"UPDATE ROW SET XXX = "+ .[] + " WHERE FOO=BAR;"' file.json | mysql -D DB_name
The file.json :
[
"foo",
"bar",
"base"
]
jq output :
jq -r '"UPDATE ROW SET XXX = "+ .[] + " WHERE FOO=BAR;"' file.json
UPDATE ROW SET XXX = foo WHERE FOO=BAR;
UPDATE ROW SET XXX = bar WHERE FOO=BAR;
UPDATE ROW SET XXX = base WHERE FOO=BAR;
Check https://stedolan.github.io/jq/
Simple solution I found is to make ajax request to the server, inside the evaluate function :
casper.then(function() {
details = this.evaluate(function() {
var elDet = document.getElementsByClassName("job-description-column")[0];
var detLen = elDet.children[2].children[0].children.length;
var details = elDet.children[2].children[0].children;
var linkedData = [];
for (var i = 0; i < detLen; i++) {
if (details[i].nodeName == "H3" && details[i].id != "if-this-sounds-like-you,-apply") {
linkedData.push({
head: details[i].textContent,
description: details[i + 1].textContent,
title: elDet.children[0].children[0].children[0].textContent,
loc: elDet.children[0].children[0].children[1].textContent,
date: elDet.children[0].children[0].children[2].textContent
})
i++;
} else {
linkedData.push({
head: "No Head",
description: details[i].textContent,
title: elDet.children[0].children[0].children[0].textContent,
loc: elDet.children[0].children[0].children[1].textContent,
date: elDet.children[0].children[0].children[2].textContent
})
}
}
var s = JSON.stringify(linkedData);
console.log(linkedData);
$.ajax({
method: "POST",
url: "http://localhost/fiverr/Crawl%20The%20Jobs/modal_scripts.php",
data: "add_jobdets=true&job_details=" + s,
async: false
})
return linkedData;
})
})

get label within the addEdge event

How can I get information about the node within the addEdge event. I managed to get the start and the end node ids but is there a possibility to get more information about the node itself? edgeData only contains 2 objects "from" and "to"
var optionsFA = {
manipulation: {
enabled: true,
addEdge: function (edgeData,callback) {
console.log('from: ' + edgeData.from + ' / to: ' + edgeData.to);
callback(edgeData);}
thanks in advance!
If you use dataset then there is an object search function by id:
addEdge: function(edge, callback) {
var from = data.nodes.get(edge.from)
var to = data.nodes.get(edge.to)
console.log('from:', from)
console.log('to:', to)
callback(edge)
}
https://jsfiddle.net/ev0h9tdz/

Insert id's into script tags using grunt

I want to insert id into the script tag
gruntfile.js
var obj = ['id1', 'id2', 'id3'];
var i = 0;
grunt.initConfig({
concat:{
basic:{
options:{
banner:'<script type="text/ng-template" id=' +obj[i] + ' >',
separator:'</script><script type="text/ng-template" id=' + obj[i++] + ' >',
footer:'</script>'
},
files:[{
src:['./src/folder/*.html'],
dest:'./src/foler/index.ftl'
}]
}
}
})
but on the output when the files are concated into index.ftl all the ids have the same id='id3'
how can I get the final concatinated file with all unique ids.
The following link solves the part of this question of adding ID,
I had created my own wrap plugin and used it in the code to added id's dynamically,
Replace all the text with specified replacement using grunt replace

How to define the number of columns to show on Jquery Full Calendar?

I'm using the week view, but instead of showing 7 columns per slide I want to show three columns, is it possible to archive this?
I failed to see any related method on the official documentation: http://fullcalendar.io/docs/
Version 2.2.5+ of Full Calendar has this kind of customization built in.
You just need to do something like this:
views: {
agendaThreeDay: {
type: 'agenda',
duration: { days: 3 },
buttonText: '3 day'
},
defaultView: 'agendaThreeDay'
}
You can get more information on this from the document page here.
Pull the source, use this code (may need some additional change).
src/agenda/AgendaThreeDayView.js
fcViews.agendaThreeDay = AgendaThreeDayView;
function AgendaThreeDayView(a) {
AgendaView.call(this, a);
}
AgendaThreeDayView.prototype = createObject(AgendaView.prototype);
$.extend(AgendaThreeDayView.prototype, {
name: "agendaThreeDay",
incrementDate: function(a, b) {
return a.clone().stripTime().add(b, "days");
},
render: function(a) {
this.intervalStart = a.clone().stripTime();
this.intervalEnd = this.intervalStart.clone().add(3, "days");
this.start = this.skipHiddenDays(this.intervalStart);
this.end = this.skipHiddenDays(this.intervalEnd, -1, true);
this.title = this.calendar.formatRange(this.start, this.end.clone().subtract(1), this.opt("titleFormat"), " — ");
AgendaView.prototype.render.call(this, 3);
}
});
Edit:
Remembered that you need to add the file to lumbar.json
Look here for how to build: https://github.com/arshaw/fullcalendar/wiki/Contributing-Code

Resources