node.js,loops,promise,qRelated issues-Collection of common programming errors


  • Mezzarine
    node.js oracle
    I followed the instalation guide and still doesn’t work.I haven’t been able to figure out what I’m doing wrong.node-gyt rebuild works fine when I do it.Any enlightenment is welcomeOS: Win 7Console:C:\TRIVIA>npm install oracle npm WARN package.json [email protected] No repository field. npm WARN package.json [email protected] No README data> [email protected] install C:\TRIVIA\node_modules\oracle > node-gyp rebuildC:\TRIVIA\node_modules\oracle>node “C:\Program Files (x86)\nodejs\node_modules\npm\bin

  • Attila Györffy
    node.js npm
    I’m trying to install NPM packages on Ubuntu (12.04). I’ve installed Node.js and NPM via Chris Lea’s PPA repository.I’m trying to deploy the Uptime project to my server. I’ve cloned the application from GitHub, then trying to install the application dependencies as a root user:root@dev:/web/my-application# npm install -g npm http GET https://registry.npmjs.org/mongoose/2.5.11 npm http GET https://registry.npmjs.org/express/2.5.0 npm http GET https://registry.npmjs.org/ejs/0.6.1 npm http GET http

  • Stefan Manastirliu
    node.js ubuntu-12.04 npm
    I’m trying to install some node packages through npm, but it won’t go. I’ve already tried to install/unistall/update node, but nothing seems to work.Any help is really apprecieted!I’m using ubuntu 12.04 – Here is how i’m trying to install packages:npm install underscorenpm http GET http://registry.npmjs.org/underscore npm http 404 http://registry.npmjs.org/underscore npm ERR! registry error parsing json npm ERR! SyntaxError: Unexpected token < npm ERR! <html> npm ERR! <head> npm

  • Muhammad Reda
    mysql node.js
    I am very new to this node.js and ubuntu.Now i am trying to use mysql database in my application.For i have the following code:var mysql = require( “db-mysql” );new mysql.Database({hostname: “localhost”,user: “dave”,password: “asdfa”,.database: “dbNameHere”}).on( “error”, function( error ) {console.log( “ERROR: ” + error );}).on( “ready”, function( server ) {console.log( “Connected to ” + server.hostname + ” (” + server.version + “)” );}).connect( function( error ) {if ( error ) {console.log( “E

  • fdior
    node.js mongodb socket.io mongoose
    I’m having weird issue with IE9 when reloading an existing tab pointing to my nodeJS server http://localhost:8080/ :mydb.usermodels.$userId_1 dup key: { : “d268745fbe9” }Opening a new tab in IE9 and loading the same URL does not generates such error, and Firefox lets me reload the same tab with no error at all.Basically, when the tab is load (or reload) the client generate a random user ID and send it to the server over a socket.io socket. The server then checks if userId is present in database

  • Ben
    android node.js phonegap socket.io
    Problem SummaryI am trying to bundle a simple socket.io chat app into a native app to run on Android 2.2 and above using phonegap.socket.io web client –> socket.io server worksI have a simple server running socket.io which successfully communicates with a socket.io client when its run in a web browser.socket.io mobile client in mobile browser –> socket.io server worksNote that because websockets arent supported on Android 2.2 it defaults back to xhr polling, sample messages from server when co

  • Juan Carlos Coto
    python node.js http rest urllib2
    Trying to make a POST request between a Python (WSGI) and a NodeJS + Express application. They are on different servers. The problem is that when using different IP addresses (i.e. private network vs. public network), a urllib2 request on the public network succeeds, but the same request for the private network fails with a 502 Bad Gateway or URLError [32] Broken pipe.The urllib2 code I’m using is this:req = urllib2.Request(url, “{‘some’:’data’}”, {‘Content-Type’ : ‘application/json; charset=

  • Julius F
    node.js postgresql asynchronous express
    One of the advantages of NodeJS is its async and non-blocking I/O, which in my case is great on the one hand, but breaks my neck every day on the other hand.I consider myself a NodeJS / Async novice and I often end up having such code:function(req, res) {req.assert(“name”, “Lobbyname is required”).notEmpty();req.assert(“name”, “Lobbyname length should be between 4 and 64 characters”).len(4, 64);req.assert(“game”, “Game not found”).isInt();req.sanitize(“game”).toInt();var userId = req.user.id;var

  • user787738
    java android node.js sockets socket.io
    I followed the fix in this post: Error connecting an Android Client to a socket server in NodeJSHad problem connect to socket server nodeJS but the problem is a fix, now the client connecting my log console of nodeJS throw me this:debug – client authorizedinfo – handshake authorized Qs-he8QJbJYA4zlAw2YnBut now I get the following errors, please help!02-04 18:34:03.288: W/dalvikvm(2769): Unable to resolve superclass of Lio/socket/WebsocketTransport; (850) 02-04 18:34:03.288: W/dalvikvm(2769): L

  • Gates VP
    node.js windows-7 socket.io npm windows-7-x64
    I am new to Node and NPM. I am using Node v0.10.0 and when I run the npm install socket.io command I get the following error:C:\Users\USER\AppData\Roaming\npm\node_modules\socket.io\node_modules\socket.io- client\node_modules\ws>node “C:\Users\USER\AppData\Roaming\npm\node_modules\npm\ bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js” rebuild C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppBuild.targets(29 7,5): warning MSB8003: Could not find WindowsSDKDir variabl

  • Hosang Jeon
    loops mapreduce hive reduce infinite
    I am using Hive (version 0.11.0) and trying to join two tables. One has 26,286,629 records and the other one has 931 records.This is the query I am trying to run.SELECT * FROM table_1 hapmap a tabl_2 b WHERE a.chrom = b.chrom AND a.start_pos >= b.start_pos AND a.end_pos <= b.end_pos LIMIT 10 ;It looks fine at the first few minutes but if the map and reduce task reached to 100% both, then it starts to reduce again from 0%.2014-02-20 20:38:35,531 Stage-1 map = 100%, reduce = 100%, Cumulat

  • Basit
    jquery ajax jquery-ajax loops response
    i have list of rows that user select and i want to delete them, one by one and show the result in the end.obviously if i just do simple loop and call each time ajax function, but how can i loop and check which one successed and which one failed and when they are all done?how would you do it? what is proper way of doing the bulk editing/deleting?

  • Zach Nicodemous
    php mysql wordpress loops wordpress-loop
    I am trying to find a way to hook several satellite WordPress installations into a centralized installation of WordPress in order to pull post data and custom field meta from two custom post types from the central installation and display this data on the satellite sites.Is there any way to create a database connection to another WordPress database either on the same server, or on a DIFFERENT server, and then use STANDARD WORDPRESS LOOP METHODOLOGY to retrieve and display data from that second W

  • Rohit Jain
    java loops for-loop error-handling iteration
    I have a for loop like so:for (Environment environment : environmentList) { //do stuff }I catch exceptions within the loop, but would like to retry executing the code with objects that receive exceptions. Obviously I can do this with a for loop using a counter and list index, but I was curious if there was any way to do this.Elaboration,for (Environment environment : environmentList) { try{ //do stuff }catch(exception) {} //retry code using current environment }

  • Gennady Vanin Novosibirsk
    c# multithreading loops closures task-parallel-library
    I’m trying to spawn different threads for some processing. I use the for loop index for some logic inside each thread. How can I get the different threads to print 1,2,3,4, 5 in the code below? Each time I run this, I get different numbers as output – 3,3,3,4,6,6 & 2,2,3,5,5,6 etc. I tried using the lock object, but it stil wasn’t doing it correctly. Can anyone help me achive this. I just want to make sure each thread/task gets the right index. Note that each task has been forced to run on a

  • stivlo
    networking loops batch-file windows-xp
    I am trying to write a batch script with a section that ouputs your drive mappings to a text file, so i can restore it later once i wipe out the machine. I came up with this for loop to do it, but its acting differently when its a batch script versus running the command itself.This is the actual line of code:FOR /F “tokens=1,2” %i in (H:\mappings2.dat) do @echo %i %jWhen i copy and paste the command from the script to the command window it works fine. When I run the batch script from a command w

  • pythonian29033
    c arrays loops floating-point numbers
    I’m learning C and found this code on a tutorial and it works fine – but if I try to make a decimal number (like 5.5), it prints a negative one in the following arrays and loops itself. The code is German, sorry for that.#include <stdio.h> #include <locale.h> #include <stdlib.h> #include <math.h> #include “stdafx.h”#define ARBEITER 3 #define TAGE 5 #define ARBEITSKALENDER kalender();int zeitkonto[ARBEITER][TAGE];/* Fehlerausgabe */void error(int n) {printf(“%d (?) Fal

  • Cal
    asp.net vb.net loops foreach datatable
    I have a datatable and I want to convert one row to a single string with all the column names, so the format will be like: column1_name: column1_content. column2_name: column2_content…I almost got it done the way I wanted, except that the result will be the same string repeated twice. For example, a string “abc” is what I want, but it will return “abcabc”.It’s ok when I had only 1 row, I could use exit keyword to terminate the loop after 1 run, but now I have datatables with more than 1 row,

  • jeffimperial
    sql loops while-loop
    So I basically lifted the solution from selected answer here: Creating a dynamic html formI’m now trying (and failing) to store submitted data into mysql.What I do is first is check how many fields have been submitted. If there were only 6 fields submitted, then they didn’t add any more fields than was already there. If there were 10, then they added one set of fields. If there were 14, they added 2 sets of fields. And so on…$varCount is for returning the current nth field the while loop is ru

  • chepner
    linux bash shell loops scripting
    I am trying to create a script that automates one line of command which is used for archiving selected files to tape and creating a text file with the archived files. a and b are inputs and in the example below and I define them as 03 and 15. a=03b=15tar -cvf /dev/tapedrive file_03 file_04 file_05 ………file_15 > /text_files/backup_file_03-15.txtthe script I came up with is below,#! /bin/basha=03 b=15for (( c=$a; c<=$b; c++ )) $tt=” “; doif[ ! $c $a ]then$c=”0$c”fi$tt .= ” file_”.$c.”” end

  • Benjamin Gruenbaum
    javascript callback promise q bluebird
    I want to work with promises but I have a callback API in a format like:1. DOM load or other one time event:window.onload; // set to callback … window.onload = function(){};2. Plain callback:function request(onChangeHandler){ … request(function(){// change happened });3. Node style callback (“nodeback”):function getStuff(dat,callback){ … getStuff(“dataParam”,function(err,data){}4. A whole library with node style callbacks:API; API.one(function(err,data){API.two(function(err,data2){API.thre

  • Darshan
    javascript jquery asynchronous jquery-events promise
    I am building a native desktop application in javascript using CEF, And I have API to access filesystem from CEF. I have a senario, in which I need to get names of all files(there could be trees of directories) within a particular directory. I need to get result array, I am using jquery promises. I am not getting, when to resolve the promise to get final result array./*read all directories under this and get path*/var result = [];function _processEntries(dirPath) {var dirEntry = new NativeFileSy

  • Harry
    javascript node.js callback promise
    Here’s an example of my access function that I use to check whether or not the user is authenticated.access = function(id, user_id, callback) {docs.findOne({_id: id}, function(err, doc) {if (doc.user.indexOf(user_id) != -1) {callback(“authenticated”)} else {callback();}}); }I use it as with the callback pattern like this.access(id, user, function (status) {if (status == ‘authenticated’) doSomething() })I’m finding that somewhat boring to write as you really need to check the callback status ever

  • oberstet
    javascript unit-testing jquery-deferred promise deferred
    I am looking for a JavaScript test framework that natively works with Deferreds/Promises.That is: my test case functions will return a Deferred (e.g. jQuery Deferred or whenjs) that when fires will yield true or false (success/failure).A framework that only provides mechanisms to test specific async stuff like AJAX is not sufficient.

  • hadley
    r promise
    Consider the following simple function:f <- function(x, value){print(x);print(substitute(value))}Argument x will eventually be evaluated by print, but value never will. So we can get results like this:> f(a, a) Error in print(x) : object ‘a’ not found > f(3, a) [1] 3 a > f(1+1, 1+1) [1] 2 1 + 1 > f(1+1, 1+”one”) [1] 2 1 + “one”Everything as expected.Now consider the same function body in a replacement function:’g<-‘ <- function(x, value){print(x);print(su

  • Bergi
    javascript asynchronous promise api-design
    I’m writing a JavaScript function that makes an HTTP request and returns a promise for the result (but this question applies equally for a callback-based implementation).If I know immediately that the arguments supplied for the function are invalid, should the function throw synchronously, or should it return a rejected promise (or, if you prefer, invoke callback with an Error instance)?How important is it that an async function should always behave in an async manner, particularly for error con

  • Chen-Tsu Lin
    javascript angularjs expression promise jquery-chosen
    I’m trying to create a new AngularJS project, but I get some errors :(This is my app and controller;var app = angular.module(‘myApp’, [‘localytics.directives’]).config([‘$parseProvider’, function ($parseProvider) {return $parseProvider.unwrapPromises(true);}]).controller(‘myController’, function ($scope, $http, $q, $timeout) {var simulateAjax;simulateAjax = function (result) {var deferred, fn;deferred = $q.defer();fn = function () {return deferred.resolve(result);};$timeout(fn, 1000);return defe

  • Tarrence
    javascript node.js request promise
    I’m new to promises and writing some network code using request and promise in NodeJS.I would like to remove these nested promises and chain them instead, but I’m not sure how I’d go about it/whether it is the right way to go.exports.viewFile = function(req, res) { var fileId = req.params.id; boxContentRequest(‘files/’ + fileId + ‘/content’, req.user.box.accessToken).then(function(response) {boxViewerRequest(‘documents’, {url: response.request.href}, ‘POST’).then(function(response) {boxViewerReq

  • Grummle
    node.js loops promise q
    What would be the idiomatic way to do something like a while loop with promises. So:do something if the condition still stands do it again repeat then do something else.dosomething.then(possilblydomoresomethings).then(finish)I’ve done it this way I was wondering if there were any better/more idomatic ways?var q = require(‘q’);var index = 1;var useless = function(){var currentIndex = index;console.log(currentIndex)var deferred = q.defer();setTimeout(function(){if(currentIndex > 10)deferred.re

  • David.LPower
    javascript jquery promise
    I am having trouble the following javascript. I am using the jQuery framework.This code works the first time, displaying the date, temperature and humidity corectly but the second time it runs i get this error message;Uncaught SyntaxError: Unexpected identifier Here is the code;var gettingTemperature = $.post(“/get_temperature.php”);setInterval(gettingTemperature, 5000);gettingTemperature.then(function (data) {$(‘#date’).text(data.date);$(‘#temperature’).html(data.temperature + “&#8451;”);$(

  • Oliver Kane
    knockout.js breeze durandal q
    Durandal.JS and Breeze.JS have some troubles playing together. Durandal is based on a few libraries, the two of note are Require and Knockout. My original project, prior to using the modular pattern introduced by Require, used the Knockout style bindings on the Breeze models.On my journey, I found out that Breeze can work with multiple libraries for Breeze’s models, such as Backbone, Knockout, Angular, and other frameworks. When Breeze is loaded as a Require module, Breeze checks to see if th

  • Benjamin Gruenbaum
    javascript callback promise q bluebird
    I want to work with promises but I have a callback API in a format like:1. DOM load or other one time event:window.onload; // set to callback … window.onload = function(){};2. Plain callback:function request(onChangeHandler){ … request(function(){// change happened });3. Node style callback (“nodeback”):function getStuff(dat,callback){ … getStuff(“dataParam”,function(err,data){}4. A whole library with node style callbacks:API; API.one(function(err,data){API.two(function(err,data2){API.thre

  • tengen
    angularjs internet-explorer-9 q
    In Angular 1.2.0, there is this funny comment:// IE stupidity! (IE doesn’t have apply for some native functions)It sits on line 9835 in the functionCall function:functionCall: function(fn, contextGetter) {var argsFn = [];if (this.peekToken().text !== ‘)’) {do {argsFn.push(this.expression());} while (this.expect(‘,’));}this.consume(‘)’);var parser = this;return function(scope, locals) {var args = [];var context = contextGetter ? contextGetter(scope, locals) : scope;for (var i = 0; i < argsFn.l

  • Grummle
    node.js loops promise q
    What would be the idiomatic way to do something like a while loop with promises. So:do something if the condition still stands do it again repeat then do something else.dosomething.then(possilblydomoresomethings).then(finish)I’ve done it this way I was wondering if there were any better/more idomatic ways?var q = require(‘q’);var index = 1;var useless = function(){var currentIndex = index;console.log(currentIndex)var deferred = q.defer();setTimeout(function(){if(currentIndex > 10)deferred.re

  • dc7a9163d9
    asp.net asp.net-mvc breeze hottowel q
    I created an Asp.Net MVC and used nuget to add HotTowel (VS2013 which is not available anymore) and updated breeze to V1.4.5. I ran the app and got the following error in the output window. Are these bugs of Q.js and breeze?Exception was thrown at line 68, column 5 in http://localhost:49890/scripts/Q.js 0x80004005 – JavaScript runtime error: unknown exception Exception was thrown at line 433, column 9 in http://localhost:49890/scripts/Q.js 0x80004005 – JavaScript runtime error: unknown exception

  • Jeremie Parker
    promise sails.js q
    I’m starting to convert my callback code to promises in Sails.js, but I don’t understand how I can raise custom errors and handle them in the promise chain. Sails.js uses Q as its promise library.User.findOne({email: req.param(‘professorEmail’), role: ‘professor’}).then(function (user) {if (user) {return Course.create({user_id: user.id,section: req.param(‘section’),session: req.param(‘session’),course_code: req.param(‘course_code’)});} else {// At this point `user` is undefined which means that

  • The_Smallest
    breeze q
    When query execution fails (for example database constraint violation on saving) i can see in console.Should be empty: []Here is the example (you can see Should be empty: [] in console)): breeze.EntityQuery.from(“EntityThatDoesnotExist”).using(new breeze.EntityManager(“http://todo.breezejs.com/api/todos”)).execute().then(function () { }).fail(function () { });http://jsfiddle.net/vMhkg/3/I’m new to Breeze and Q, so my question is: should I just just ignore this? Or am I doing something wrong? Or

  • Eric Hotinger
    javascript angularjs requirejs breeze q
    I am creating a single page app built on AngularJS, Breeze, and RequireJS. In setting up AMD with requirejs to work with Angular and Breeze, I encountered an issue with Breeze’s dependency on “q”. If the configuration rule for “q” is lowercase, even if there is no explicit export in the “shim”, Breeze gives this error:Uncaught Error: Unable to initialize Q. See https://github.com/kriskowal/q “http://localhost:1498/Scripts/shared/breeze.js”breeze.js:1`When require config changes all references fr

  • Conradub
    javascript asynchronous web-api deferred q
    Already had a layer in JS which helps Gets and Posts to the server with the following implementations :var getJson = function(url, callback, onError) {$.get(url).done(function(data) {if(callback != null)callback(data);}).fail (function(error) {if(onError != null)onError (error);elsemy.notification.notifyError(onErrorMessage);}); };var postJSON = function(url, data, callback, onError) {$.ajax({url : url ,type: “POST” ,contentType : “application/json”dataType : “json” ,date : ko.toJSON(data)}).don

  • bob_cobb
    javascript node.js callback promise q
    I’m doing a bunch of deferred/promises with the Q library which works fine, but once I get back some of my data in one of the chained callbacks, I want to manipulate it in some way.E.g.var getFavorites = function(submissionId) {deferred = Q.defer();Submission.getFavorites({submissionId : submissionId}, function(err, favorites) {if (err) {deferred.reject(err);} else {deferred.resolve(favorites);}});return deferred.promise; };var didUserFavorite = function(favorites) {var didUserLike;deferred = Q.

Web site is in building