How can I map this asynchronous NPM twit function onto an array? - javascript

I'm trying to figure out how to map this async function onto an array that I am using. The code that I tried is returned undefined since the promise isn't completing.
I am using NPM twit and this is the function that is supposed to return a number when an ID is passed into it
ids = ['1084212656771350532','2450457644','1244639845743570948','1081269935031140353','1227966230511980550','752215003143430145']
T.get('statuses/user_timeline', { user_id: id, count: 100, exclude_replies: true, include_rts: false }, function (err, data, response) {
if (err) {
console.log('err');
} else {
var rtTotal = 0;
var likeTotal = 0;
for (var i = 0; i < data.length; i++) {
rtTotal += data[i].retweet_count;
var rtAverage = rtTotal / data.length;
}
for (var i = 0; i < data.length; i++) {
likeTotal += data[i].favorite_count;
var likeAverage = likeTotal / data.length;
}
}
var influenceScore = (.33 * rtAverage) + (.2 * likeAverage) + (.33 * (data[0].user.followers_count)) + (.14 * (data[0].user.statuses_count));
console.log(influenceScore);
return influenceScore;
})
For example the result should be an array with numerical values
[1123.11, 9200, 21882, 1011, 23110.22]

Related

foreach loop not behaving as expected javascript ajax call

Need to find out "chacesofrain" for each of the time for the next 14 days
Can only print the chanceofrain for the first day.Not sure how I can get for the rest of the days?
[![$('#weather-click').click(function() {
var state = $('#state')
.val()
.trim();
var country = $('#country')
.val()
.trim();
var queryURL = `http://api.worldweatheronline.com/premium/v1/weather.ashx?key=[API_KEY]&q=${state},%20${country}&format=json&num_of_days=14`;
$.ajax({
url: queryURL,
method: 'GET'
}).then(function(response) {
console.log(response);
var weather = response.data.weather;
console.log(weather);
for (var i = 0; i < weather.length; i++) {
var hourly = weather[i].hourly;
console.log(hourly);
for (var k = 0; k <= hourly.length; k++) {
var chanceOfRain = hourly[k].chanceofrain;
console.log(chanceOfRain);
}
// setTimeout(function() {
// for (var k = 0; k <= hourly.length; k++) {
// var changeOfRain = hourly[k].chanceofrain;
// console.log(changeOfRain);
// }
// }, 4000);
}
});
});][1]][1]
I expect chanceofrain for all the days logged in the browser
But the output shows for only 1 day

Parse cloud code, access object relations

I'm trying to create a Parse cloud code function that returns the same result as a GET on parse/classes/MyClass but with the IDs of the relations.
I've done it for one object, but I can't make it work in a loop to get all the objects.
This is how I'm trying to get all the objects. It's working without the for loop and with r as a response.
Parse.Cloud.define('get_ClassName', function(request, response) {
let query = new Parse.Query('ClassName');
var ret = {};
query.find({useMasterKey: true}).then(function(results) {
for (var i = 0; i < results.length; i++) {
ret[i] = {};
const relQuery = results[i].get('status').query();
relQuery.find({useMasterKey: true}).then(function(res) {
var ids = {};
for (var j = 0; j < res.length; j++) {
ids[j] = res[j].id;
}
var status = {...status, id: ids};
status["className"] = "Status";
var r = {...r, status: status};
r["tag"] = results[i].get("tag");
ret[i] = r; //Can't access ret
//response.success(r); //Working
})
}
response.success(ret);
});
});
This is the actual result for the working version:
{
"result": {
"status": {
"id": {
"0": "xxxxxx",
"1": "xxxxxx"
},
"className": "Status"
},
"tag": "value"
}
}
response.success(ret); will run before relQuery.find finish in for loop.
Use Promise.all()
or Async await and refactor your logic.
I comment on your code about your missing.
Parse.Cloud.define('get_ClassName', function(request, response) {
let query = new Parse.Query('ClassName');
var ret = {};
query.find({useMasterKey: true}).then(function(results) { // Asyncronous
for (var i = 0; i < results.length; i++) {
ret[i] = {};
const relQuery = results[i].get('status').query();
relQuery.find({useMasterKey: true}).then(function(res) { // Asyncronous
var ids = {};
for (var j = 0; j < res.length; j++) {
ids[j] = res[j].id;
}
var status = {...status, id: ids};
status["className"] = "Status";
var r = {...r, status: status};
r["tag"] = results[i].get("tag");
ret[i] = r; //Can't access ret
//response.success(r); //Working
console.log(`index {i}`, r);
})
}
console.log(`response will be called`);
response.success(ret); // Called before `relQuery.find` finish
});
});

Multidimentioanal arrays in JavaScript values not appending

I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);

JS missing ) in parenthetical (line #88)

I'm writing a program in JS for checking equal angles in GeoGebra.
This is my first JS code, I used c# formerly for game programming.
The code is:
var names = ggbApplet.getAllObjectNames();
var lines = new Set();
var angles = new Set();
var groups = new Set();
for(var i=0; i<names.length; i++)
{
if(getObjectType(names[i].e)==="line")
{
lines.add(names[i]);
}
}
for(var i=0;i<lines.size;i++)
{
for(var j=0;j<i;j++)
{
var angle = new Angle(i,j);
angles.add(angle);
}
}
for(var i=0;i<angles.size;i++)
{
var thisVal = angles.get(i).value;
var placed = false;
for(var j=0;j<groups.size;j++)
{
if(groups.get(j).get(0).value===thisVal)
{
groups.get(j).add(angles.get(i));
placed = true;
}
}
if(!placed)
{
var newGroup = new Set();
newGroup.add(angles.get(i));
groups.add(newGroup);
}
}
for(var i=0;i<groups.size;i++)
{
var list="";
for(var j=0;j<groups.get(i).size;j++)
{
list = list+groups.get(i).get(j).name;
if(j != groups.get(i).size-1)
{
list = list+",";
}
}
var comm1 = "Checkbox[angle_{"+groups.get(i).get(0).value+"},{"+list+"}]";
ggbApplet.evalCommand(comm1);
var comm2 = "SetValue[angle_{"+groups.get(i).get(0).value+"}+,0]";
ggbApplet.evalCommand(comm2);
}
(function Angle (i, j)
{
this.lineA = lines.get(i);
this.lineB = lines.get(j);
this.name = "angleA_"+i+"B_"+j;
var comm3 = "angleA_"+i+"B_"+j+" = Angle["+this.lineA+","+this.lineB+"]";
ggbApplet.evalCommand(comm3);
var val = ggbApplet.getValue(this.name);
if(val>180)
{val = val-180}
this.value = val;
ggbApplet.setVisible(name,false)
});
function Set {
var elm;
this.elements=elm;
this.size=0;
}
Set.prototype.get = new function(index)
{
return this.elements[index];
}
Set.prototype.add = new function(object)
{
this.elements[this.size]=object;
this.size = this.size+1;
}
It turned out that GeoGebra does not recognize Sets so I tried to make a Set function.
Basically it collects all lines into a set, calculates the angles between them, groups them and makes checkboxes to trigger visuals.
the GeoGebra functions can be called via ggbApplet and the original Workspace commands via ggbApplet.evalCommand(String) and the Workspace commands I used are the basic Checkbox, SetValue and Angle commands.
The syntax for GeoGebra commands are:
Checkbox[ <Caption>, <List> ]
SetValue[ <Boolean|Checkbox>, <0|1> ]
Angle[ <Line>, <Line> ]
Thank you for your help!
In short, the syntax error you're running to is because of these lines of code:
function Set {
and after fixing this, new function(index) / new function(object) will also cause problems.
This isn't valid JS, you're likely looking for this:
function Set() {
this.elements = [];
this.size = 0;
}
Set.prototype.get = function(index) {
return this.elements[index];
};
Set.prototype.add = function(object) {
this.elements[this.size] = object;
this.size = this.size + 1;
};
Notice no new before each function as well.
I'm not sure what you're trying to accomplish by creating this Set object though - it looks like a wrapper for holding an array and its size, similar to how something might be implemented in C. In JavaScript, arrays can be mutated freely without worrying about memory.
Here's an untested refactor that removes the use of Set in favour of native JavaScript capabilities (mostly mutable arrays):
var names = ggbApplet.getAllObjectNames();
var lines = [];
var angles = [];
var groups = [];
for (var i = 0; i < names.length; i++) {
if (getObjectType(names[i].e) === "line") {
lines.push(names[i]);
}
}
for (var i = 0; i < lines.length; i++) {
for (var j = 0; j < i; j++) {
angles.push(new Angle(i, j));
}
}
for (var i = 0; i < angles.length; i++) {
var thisVal = angles[i].value;
var placed = false;
for (var j = 0; j < groups.length; j++) {
if (groups[j][0].value === thisVal) {
groups[j].push(angles[i]);
placed = true;
}
}
if (!placed) {
groups.push([angles[i]]);
}
}
for (var i = 0; i < groups.length; i++) {
var list = "";
for (var j = 0; j < groups[i].length; j++) {
list += groups[i][j].name;
if (j != groups[i].length - 1) {
list += ",";
}
}
var comm1 = "Checkbox[angle_{" + groups[i][0].value + "},{" + list + "}]";
ggbApplet.evalCommand(comm1);
var comm2 = "SetValue[angle_{" + groups[i][0].value + "}+,0]";
ggbApplet.evalCommand(comm2);
}
function Angle(i, j) {
this.name = "angleA_" + i + "B_" + j;
var comm3 = "angleA_" + i + "B_" + j + " = Angle[" + lines[i] + "," + lines[j] + "]";
ggbApplet.evalCommand(comm3);
var val = ggbApplet.getValue(this.name);
if (val > 180) {
val -= 180;
}
this.value = val;
ggbApplet.setVisible(name, false);
}
Hopefully this helps!
Your function definition is missing the parameter list after the function name.
Also, you're initializing the elements property to an undefined value. You need to initialize it to an empty array, so that the add method can set elements of it.
function Set() {
this.elements=[];
this.size=0;
}

using new keyword in callback causes "TypeError: object is not a function"

I have a call:
var serve = function(teacher, callback) {
RE.createFakeMemberData(function(err, avgMember) {
//omitted
});
};
inside the createFakeMemberData, if I try to instantiate a mongoose model:
var statistic = new Statistic();
I get the error with the stack trace:
D:\Orkun\workspace\teb\tebesir-repo\scripts\engines\ResetEngine.js:61
var statistic = new Statistic();
^
TypeError: object is not a function
at Object.createFakeMemberData (D:\Orkun\workspace\teb\tebesir-repo\scripts\engines\ResetEngine.js:61:21)
at Promise.<anonymous> (D:\Orkun\workspace\teb\tebesir-repo\scripts\servlets\graph\ServeSpider-Teacher.js:29:20)
at Promise.<anonymous> (D:\Orkun\workspace\teb\tebesir-repo\node_modules\mongoose\node_modules\mpromise\lib\promise.js:177:8)
at Promise.emit (events.js:95:17)
I think the 'this' is going out of scope or sth. I have also tried using bind..
RE.createFakeMemberData(function(err, avgMember) {
//omitted
}).bind(this);
no joy..
EDIT: statistic
// external libs that are going to be used
var bunyan = require('bunyan');
var mongoose = require('mongoose');
var _ = require('underscore');
var Schema = mongoose.Schema;
// models that are going to be used
var Subject = require('../../scripts/models/Subject');
var CF = require('../../scripts/utilities/CommonFunctions');
var ResetEngine = require('../engines/ResetEngine');
var MetricEngine = require('../engines/MetricEngine');
var Constants = require('../../scripts/utilities/Constants');
var log = bunyan.createLogger({src: true, name: 'logStatistics'});
var Statistic = new Schema(
{
solved_tot: {type: Number, default : 0}, // number
score_tot: {type: Number, default : 0}, // score
time_tot: {type: Number, default : 0}, // time
// statistics for all the subjects available to the client
stats: [{
stat_id: { type: String, required: true},
stat_name: { type: String, required: true},
stat_solved: { type: Number, default : 0},
stat_score: { type: Number, default : 0},
stat_time: { type: Number, default : 0}
}]
}, { strict: true });
// !param new_score the book that has been bought as Book
// !param new_time of the user which makes the buy as String
// !param test_solved the book that has been bought as Book
// !desc should be async for extra performance opt
Statistic.methods.updateStatisticsFromTest = function(test_solved, new_time, new_score, callback) {
for (var i = 0; i < test_solved.subjects.length; i++) {
for (var k = 0; k < this.stats.length; ++k) {
if (test_solved.subjects[i].subject_name == this.stats[k].stat_name) {
// set the current variables
var current_score = this.stats[k].stat_score;
var current_time = this.stats[k].stat_time;
var current_solved = this.stats[k].stat_solved;
// calculate and update three indexes
this.stats[k].stat_score = (((current_score * current_solved) + new_score) / (current_solved + 1)).toFixed(5);
this.stats[k].stat_time = (((current_time * current_solved) + new_time) / (current_solved + 1)).toFixed(5);
this.stats[k].stat_solved++;
break;
}
}
}
// calculate the average total time
this.time_tot = (((this.time_tot * this.solved_tot) + new_time) / (this.solved_tot + 1)).toFixed(5);
// calculate the average score
this.score_tot = (((this.score_tot * this.solved_tot) + new_score) / (this.solved_tot + 1)).toFixed(5);
// increase the number of tests solved
this.solved_tot++;
// save the new user stat
this.save(function(err) {
if (CF.errorCheck(err, Constants.DB_ERROR, 'save Statistic')) return callback(err);
return callback(null, this);
});
};
// !brief creates an empty subject statistics object for a new user
// !param subjectList (Array<Subject>) list of subjects that will be included to the statistics
// !callback function that will be called when the database query ends
Statistic.methods.createStatistics = function(subjectList) {
// initialize and add all the subjects to the statistics object
this.stats = [];
for (var i = 0; i < subjectList.length; i++) {
this.stats.push({'stat_id': subjectList[i].id.toString(), 'stat_name' : subjectList[i].name});
}
};
// !brief aggregates the subject statistics on a single topic statistics
// !param subjectStatisticsObjectList ( Array <Statistic> ) subject statistics to be aggregated
Statistic.methods.aggregateStatistic = function(statisticsObjectList) {
ResetEngine.resetStatistic(this);
for (var i = 0; i < statisticsObjectList.length; i++) {
this.solved_tot += statisticsObjectList[i].solved_tot;
this.time_tot += statisticsObjectList[i].time_tot;
this.score_tot += statisticsObjectList[i].score_tot * statisticsObjectList[i].solved_tot;
for (var k = 0; k < statisticsObjectList[i].stats.length; k++) {
this.stats[k].stat_solved += statisticsObjectList[i].stats[k].stat_solved;
this.stats[k].stat_score += statisticsObjectList[i].stats[k].stat_score / statisticsObjectList.length;
this.stats[k].stat_time += statisticsObjectList[i].stats[k].stat_time;
this.stats[k].subject_watch += statisticsObjectList[i].stats[k].subject_watch;
}
}
this.score_tot = this.score_tot / statisticsObjectList.length;
ResetEngine.roundStatistic(this);
};
// !brief gets the topic statistics in the this object which belong to a subject
// !param theSubject ( Subject ) subject that we are going to search for
// !param topicList ( Array<Topic> ) topic lists that is going to be searched
// !return (Array<Topic>) test that are found by the function
Statistic.methods.getTopicStatBlobBySubject = function(subjectObject, topicList) {
var TopicStatisticsOfSubject = [];
for (var i = 0; i < topicList.length; i++) {
if (topicList[i].subject === subjectObject._id.toString()) {
for (var k = 0; k < this.stats.length; k++) {
if (this.stats[k].stat_id === topicList[i]._id.toString()) {
TopicStatisticsOfSubject.push(this.stats[k]);
break;
}
}
}
}
return TopicStatisticsOfSubject;
};
// !brief find the blob that belongs to the given subject or topic name
// !param statName ( String ) the name of the subject or topic that blob will be found
// !return subjectBlob or topicBlob (Statistic.stats)
Statistic.methods.getStatBlob = function(statName) {
for (var i = 0; i < this.stats.length; i++) {
if (this.stats[i].stat_name === statName) {
return this.stats[i];
}
}
};
module.exports = mongoose.model('Statistic' , Statistic);

Categories