Пример #1
0
        function(req, res, next)
        {
          var             sync = require("synchronize");

          // We're not using bodyParser due to some internal problem. Instead,
          // parse the url-encoded body ourself, here.
          var qs = require("qs");
          req.body = qs.parse(req.body);
          
          // Ensure that the user name is lower case since LDAP is case
          // insensitive, and we want only a single version of the name (and a
          // single ObjUser UID) in the database.
          req.body.username = req.body.username.toLowerCase();

          // Call the RPC to request a new user
          sync.fiber(
            function()
            {
              if (dbif.resetPassword(req.body.username, req.body.password) != 0)
              {
                // Failure. This should not occur. Just redirect to same page.
                res.redirect("/login");
                return;
              }
              
              // Let 'em know we're done
              res.send("0");
            });
        },
Пример #2
0
            function(error, info)
            {
              var             sync = require("synchronize");

              console.log("Failed to send confirmation message to " +
                          username + ": " + error);

              // We couldn't send the email, so there's no reason to keep
              // the pendingAuthLocal object around any longer.
              //
              // NOTE: This will happen outside of the transaction, and
              // outside of the original fiber created in Application.js
              // most of the time. If the original fiber is still running,
              // we'll get a transaction-within-a-transaction error which we
              // must just ignore for now.
              try
              {
                sync.fiber(
                  function()
                  {
                    pendingAuthLocalObj.removeSelf();
                  });
              }
              catch(e)
              {
                console.log("Could not remove pendingAuthLocal object: " + e);
              }
              
            });
Пример #3
0
function generateFile(themePath, originPath, destinationFile, cb) {
  var stylesPath = path.join(__dirname, themePath, originPath);
  sync(fs, 'readdir', 'stat', 'readFile', 'writeFile');
  sync.fiber(function() {
    var i, paths, path, stat, data = '';
    paths = fs.readdir(stylesPath);
    //Read css files
    for (i = 0; i < paths.length; i++) {
      path = paths[i];
      console.log(chalk.green('\tConcatenating ' + path));
      stat = fs.stat(stylesPath + path);
      if (!stat.isFile())
        continue
      data += fs.readFile(stylesPath + path, 'utf8') + '\n';
    }
    //Write css file
    fs.writeFile(__dirname + themePath + '/' + destinationFile, data, function(err) {
      if (err) {
        console.log(err);
      } else {
        cb(true);
      }
    });
  });
}
Пример #4
0
exports.getStockCode = function(isu_nm, callback) {
    var stockCodeURL = 'http://marketdata.krx.co.kr/contents/MKD/99/MKD99000001.jspx';
    sync.fiber(function() {
        console.log('getStockCode');
        var code = sync.await(otplib.requestStockCodeOTP(sync.defer())).text;
        var body = {
            isu_cd : null,
            no: 'P1',
            mktsel: 'ALL',
            searchText: isu_nm,
            pagePath: '/contents/COM/FinderStkIsu.jsp',
            code: code
        };

        request
            .post(stockCodeURL)
            .type('form')
            .send(body)
            .end(sync.defer());

        var result = sync.await();
        result = JSON.parse(result.text);

        for(var i=0; i<result.block1.length; i++) {
            var stock = result.block1[i];
            if(stock.codeName === isu_nm) {
                return stock;
            }
        }

    }, function(err, res) {
        callback(err, res);
    });
};
Пример #5
0
function createTalks(talks) {
    sync(client, 'post');
	var opts = {
		width: 40,
		total: talks.length-1,
		clear: true
	};
    var bar = new ProgressBar('  Creating talks [:bar] :percent :etas', opts);
    var result = {};
    sync.fiber(function() {
        talks.forEach(function(talk) {
            var response = client.post(buildOptions('/talks'), talk).res;
            var talkId = JSON.parse(response.body).id;
            var key = talk.startTime;
            if (key in result) {
                result[key].push(talkId);
            } else {
                result[key] = [talkId];
            }
            bar.tick(1);
        });
        var sortedKeys = Object.keys(result).sort();
        sortedKeys.forEach(function(key) {
            console.log('%s\n%s\n', key, result[key]);
        });
    });
}
Пример #6
0
    new cronJob(global.configure.cron.FIND_TRADING_TIME.TIME, function(){

        var time = timelib.getCurrentTime().format("mm");
        time = parseInt(time, 10);
        console.log('CRON JOB', time);

        sync.fiber(function() {

            var managerSetting = DB.MANAGER_SETTING;
            var findTrading = [
                { time: managerSetting.cron.best,  type: 'best' },
                { time: managerSetting.cron.favorite, type: 'favorite'}
            ];

            sync.await(stocklistlib.findBestStocks(sync.defer()));
            findTrading.forEach(function(trading) {
                if(time % trading.time != 0 ) {
                    return;
                }

                var param = {
                    type: trading.type
                };
                sync.await(tradingService.findTradingList(param, sync.defer()));
            });

        }, function(err, result) {
            if(err) return console.log(err);
        });
    },null, true, 'Asia/Seoul');
Пример #7
0
 form.on('end', function () {
   sync.fiber(function () {
     var errors = _validate(req, res)
     if (errors.length > 0) {
       dashboardPage.errors = errors
       res.render('dashboard', dashboardPage)
     } else {
       dashboardPage.errors = null
       fifoData.userId = req.user._id
       fifoData.username = req.user.username
       fifoData.status = 'pending' // status: pending, approved, rejected
       fifo.push(fifoData, 'local', function (err, job) {
         if (err) {
           logger.error('@controllers.roland_milling: ' + err.err)
           dashboardPage.errors = [{ param: 'jobs', msg: err.err, value: undefined }]
         } else {
           dashboardPage.uploadSuccess = true
           var uploadMessage = 'Design succsessfully uploaded to /public/uploads/designs/local. ' + 'User id: ' + req.user._id + ' File: ' + req.body.filename
           req.flash('success_msg', uploadMessage)
           var flashUpload = req.flash('success_msg')[0]
           dashboardPage.flashUpload = flashUpload
           req.session.flash = []
         }
         res.render('dashboard', dashboardPage)
       })
     }
   })
 })
Пример #8
0
        function(req, res, next)
        {
          var             sync = require("synchronize");

          sync.fiber(
            function()
            {
              var             secret;

              // The query string is the secret for this new user
              secret = decodeURIComponent(req.query["q"]);

              // Call the RPC to complete new user setup
              if (dbif.completeNewUser(secret) != 0)
              {
                // Failure. This should not occur. Just redirect to same page.
                res.redirect("/newuser");
              }
              else
              {
                // Success. Redirect to the login page
                res.redirect("/login");
              }
            });
        });
Пример #9
0
    doGet : function(request, response)
    {
      var             sync = require("synchronize");
      
      // Run this request in a fiber, to allow for synchronous calls
      sync.fiber(
        function()
        {
          var             dbif=  new playground.dbif.DbifNodeSqlite();
          var             rpcResult;

          // Determine the logged-in user
          dbif.identify(request);

          // Process this request
          rpcResult = dbif.processRequest(request.query);

          // Ignore null results, which occur if the request is a notification.
          if (rpcResult !== null)
          {
            // Generate the response.
            response.set("Content-Type", "application/json");
            response.send(rpcResult);
          }
        });
    }
Пример #10
0
function searchHashTag(req, res) {

	var query = url.parse(req.url).query;
	var jsonQueryString = querystring.parse(query);

	var searchTerm = jsonQueryString;

	// Runs in parallel
	sync.fiber(function() {
		sync.parallel(function() {

			getInstagramInfo(searchTerm, sync.defer());
			getTwitterInfo(searchTerm, sync.defer());
		});

		var results = sync.await();
		// results now contains [{instagram data},{twitter data}] - both arrays.
		// need to join them into one array
		var finalResults = results[0].concat(results[1]);
		
		// writing response
		res.writeHead(200, {
			'Content-Type' : 'application/json',
			'Access-Control-Allow-Origin' : '*'
		});
		res.write(JSON.stringify(finalResults)+ '');
		res.end();

	});
}
Пример #11
0
 return new Promise(function(resolve, reject) {
   sync.fiber(fn.bind(this), function(err, result) {
     if (err) {
       return reject(err);
     }
     resolve(result);
   });
 }.bind(this));
Пример #12
0
 topic: function() {
   sync.fiber(function(){
     var res = context.doGet({ parameter: { format: 'json' }});
     res.content = JSON.parse(res.content);
     
     this.callback(null, res);
   }.bind(this));
 },
Пример #13
0
 topic: function() {
   sync.fiber(function(){
     var res = context.doGet({ parameter: { format: 'xml' }});
     res.doc = new dom().parseFromString(res.content);
     
     this.callback(null, res);
   }.bind(this));
 },
Пример #14
0
http.createServer(function (req, res) {
    sync.fiber(function() {
        csd.main();
    });

    res.writeHead(202);
    res.end();
}).listen(port, '0.0.0.0'); // Listen on any IP address
Пример #15
0
	return function(test) {

		// If NODEUNIT_FLUSH is truey, mark all tests as done immediately
		// Should not be necessary... but just in case killing does not work, omitting all will
		if (process.env.NODEUNIT_FLUSH) {
			console.error(p, "Omitting test...");
			test.done(new Error("Test aborted."));
			return;
		}

		sync.fiber(function() {
			var i = ++index,
				exiter;
			debug('testcase #%s start, using', i, webdriverConfig);
			var error = null;
			try {
				var arr = typeof webdriverConfig === "function" && webdriverConfig() || init(webdriverConfig),
					inst = arr[0],
					excludeList = arr[1];
				for (var name in inst) {
					if (u.isFunction(inst[name]) && (!excludeList || excludeList.indexOf(name) === -1)) {
						sync(inst, name);
					}
				}

				// From this point, init can trigger a browser, which will have to be killed
				exiter = exitHandler.bind(inst, test);
				process.on('SIGINT', exiter);
				if (autorun && inst.init) {
					inst.init();

					// If desired, possible and not flushing, open url
					if (!process.env.NODEUNIT_FLUSH && webdriverConfig.url && inst.url) {
						inst.url(webdriverConfig.url);
					}
				}
				// Unless flushing, start the tests
				if (!process.env.NODEUNIT_FLUSH) {
					testFunction.call(this, test, inst);
				}
			} catch (err) {
				debug('testcase #%s uncaught error (%s)', i, err);
				error = err;
			}
			if (exiter) {
				process.removeListener('SIGINT', exiter);
			}
			if (!process.env.NODEUNIT_FLUSH) {
				if (autorun || error) {
					inst && inst.end && inst.end();
					inst && inst.removeAllListeners && inst.removeAllListeners();
					test.done(error);
				}
			}
			debug('testcase #%s finish', i);
		});

	}
Пример #16
0
exports.longObject = function(stringParsed, cb) {
    let longJSON = [];
    sync.fiber(function() { //Using fiber to make this block sync
        for (let i = 106; i < stringParsed.length; i += 8) {
            longJSON.push(stringParsed[i]);
        }
    });
    cb(longJSON);
}
Пример #17
0
exports.requestBestStock = function(code, date, type, callback) {

    sync.fiber(function() {
        var body = {
            sect_tp_cd: null,
            period_strt_dd: date.format('YYYYMMDD'),
            period_end_dd: date.format('YYYYMMDD'),
            pagePath: '/contents/MKD/10/1002/10020310/MKD10020310.jsp',
            code: code
        };

        if(type === 'kosdaq') {
            body.ind_tp = 'KSQ';
            body.idx_type = 2001;
        } else if(type === 'kospi') {
            body.ind_tp = 'STK';
            body.idx_type =  1001;
        }

        request
            .post(top100StocksURL)
            .type('form')
            .send(body)
            .end(sync.defer());

        var result = sync.await();
        result = JSON.parse(result.text);
        result = result.block1.splice(0, 99);
        result = result.map(function(stock) {
            return {
                kor_shrt_isu_nm: stock.kor_shrt_isu_nm,
                isu_end_pr: stock.isu_end_pr
            }
        });

        result.forEach(function(stock) {
            //새로운 stock정보 저장
            sync.await(stocklistlib.addStock(stock.kor_shrt_isu_nm, sync.defer()));
        });

        //best stock 추가
        sync.await(stocklistlib.addBestStock(date.format('YYYYMMDD'), type, result, sync.defer()));

    }, function(err, res) {
        callback(err, res);
    });
};
Пример #18
0
exports.timeObject = function(stringParsed, shortJSON, longJSON, cb) {
    let timeJSON = [];

    sync.fiber(function() { //Using fiber to make this block sync
        for (let i = 102; i < stringParsed.length; i += 8) {
            timeJSON.push(stringParsed[i]);
        }
        for (let i = 0; i < timeJSON.length; i++) {
            timeJSON[i] = {
                "time": timeJSON[i],
                "short": shortJSON[i],
                "long": longJSON[i]
            };
        }
        cb(timeJSON);
    });
}
Пример #19
0
 it('can fetch', function(done) {
   this.timeout(10000); //give api some time
   const req = new RestFetchRequest({
       config: {
         "username": "******",
         "password": "******",
         "dataKey": "36f71b26bca202c61973809143a58f7b12fe42a8",
         "url": "https://commerce-supportq.qa.gtnexus.com/rest/"
       }
     },
     '$DocPouchInvoiceLinkS1',
     310,
     '157613553'
   );
   sync.fiber(() => {
     const response = req.execute();
     expect(response).to.be.ok;
     expect(response.__metadata.uid).to.equal('157613553');
     done();
   });
 });
Пример #20
0
 .exec(function(err, reservation) {
   if (reservation.length == 0) {
     callback();
   } else {
     sync.fiber(function(){
       var programs = [];
       for (var i=0; i<reservation.length; i++) {
         condition.title = new RegExp('^'+reservation[i].title);
         condition.sid = reservation[i].sid;
         condition.doNotRecord = {$ne: true};
         if (!condition.start) {
           condition.start = {};
         }
         condition.start.$gt = new Date().getTime();
         var program = sync.await(model.program.find(condition)
           .exec(sync.defer()));
         Array.prototype.push.apply(programs, program);
       }
       callback(programs);
     });
   }
 });
Пример #21
0
            function(user, done)
            {
              var             sync = require("synchronize");

              sync.fiber(
                function()
                {
                  var             userInfo;

                  userInfo =
                    {
                      id          : getUserId(user.uid),
                      displayName : user.cn,
                      email       : user.mail,
                      name        : user.uid
                    };

                  console.log("LDAP authenticated user " + userInfo.name +
                                " (" + userInfo.displayName + 
                                ", " + userInfo.email + ")" +
                              ", id " + userInfo.id);
                  return done(null, userInfo);
                });
            }));
Пример #22
0
		try {
			var response = glibrary.uploadAndRegisterSync({
			 	filename: files[i],
			 	repo: 'EEE',
			 	type: 'Bin',
			 	metadata: metadata
			});
			console.log(response);
		} catch(e) {
			console.log(e);
			console.log("Upload failed for " + files[i]);
			return;
		}
	}
}


glibrary.configure({
        //defaultStorage: 'se.reef.man.poznan.pl',
        defaultStorage: 'prod-se-03.ct.infn.it',
        //defaultVO: 'vo.dch-rp.eu',
        defaultVO: 'vo.earthserver.eu',
        //defaultRootPath: '/dpm/reef.man.poznan.pl/home/'      
        defaultRootPath: '/dpm/ct.infn.it/home/'
});



sync.fiber(uploadAndRegisterRawData);

app.use(function(req, res, next) {
  sync.fiber(next);
});
Пример #24
0
	stream.on('data', function (tweet) {
		if (!tweet.text) {
			return;
		}
		
		var statement = unescapeHtml(tweet.text);
		var tokens = lexer.lex(statement);
		var sentences = [];
		// throw away retweet headers
		if (tokens.children.length > 0 && tokens.children[0].lexi == 'retweet') {
			tokens.children.shift();
		}
		for (var i = 0; i < tokens.children.length; i++) {
			var sentence = tokens.children[i];
			sentence.ngrams = []
			
			//build ngrams from sentence
			var base_ngram = [];

			for (j in sentence.children) {
				var node = sentence.children[j];
				if (node.lexi == 'hashtag' || node.lexi == "space") {
					continue;
				} else if (node.lexi == 'user') {
					base_ngram.push(SYMBOLS.user);
				} else {
					base_ngram.push(node.string);
				}
			}
			sentence.ngrams.push(base_ngram);
			
			for (var j = 0; j < base_ngram.length; j++) {
				for (var k = j + 1; k < base_ngram.length; k++) {
					sentence.ngrams.push(base_ngram.slice(j, k))
				}
			}
			
			sentences.push(sentence);
		}

		sync.fiber(function() {
			
			//save tweet
			var tw_doc = db.tweets.insert(tweet);
			
			for (i in sentences) {
				//save ngrams
				sentences[i].ngrams_ids = [];
				for (j in sentences[i].ngrams) {
					var ng_doc = db.ngrams.first({tokens: sentences[i].ngrams[j]});
					if (ng_doc) {
						ng_doc.count = ng_doc.count + 1;
						db.ngrams.update({_id: ng_doc._id}, ng_doc);
					} else {
						ng_doc = db.ngrams.insert({tokens: sentences[i].ngrams[j], count: 1});
					}
					sentences[i].ngrams_ids.push(ng_doc._id);
				}

				//save sentences				
				db.sentences.insert({tweet_id: tw_doc._id, token_tree: sentences[i].children, ngrams: sentences[i].ngram_ids});
			}
		});
	});
Пример #25
0
    // Second user: the shrinksafe/lib/minify/shrinksafe.js, to close children's stdin.
    performCleanup();

    if (runShell) {
        print("Narwhal, Nodejs engine, bootstrap.js version", nodeBootstrapVersion);
        print("N.B. narwhal/node has two distinct implementations of require.");
        print("p=print;k=Object.keys;");
        print("p(require); k(require);                                 // inspect the node require");
        print("p(system.global.require); k.keys(system.global.require);// inspect the narwhal require");
        print("");
        print("To keep them straight: narwhalrequire=system.global.require; noderequire=require;");
        print("noderequire('jake') will fail.");
        print("narwhalrequire('jake') will succeed.");
        print("");
        print("Note this shell has tab completion.");
		const repl = require('repl');
		const r = repl.start('> '); // At the prompt, try '> system' and '> system.nodejs'.

	    // Here node's asynchronous nature shows.  The repl.start() is asynchronous.
	    // Code after this gets executed immediately.
        // print("continue");
    }

};

// Call the bootstrap function with global set to 'this'.
// Call the bootstrap function in its own fiber, so we can leverage the
// sync.await and sync.defer calls, to use node calls synchronously.

sync.fiber( function() {bootstrap.call(global);} );
Пример #26
0
 fiberRoutes: function(req, res, next) {
   var sync = require("synchronize");
   sync.fiber(next);
 }
Пример #27
0
 asyncFn = function(done) {
   sync.fiber(fn.bind(this), done);
 };
Пример #28
0
				}
			} else {
				__findFilesIn(base, dest, dir+file+"/");
			}
		}
	}
	
	function __filterCopyFile(src, dest) {
		var dir = path.dirname(dest);
		if (!fs.existsSync(dir)) {
			mkdirp(dir);
		}
		
		var sfile = fs.createReadStream(src);
		var dfile = fs.createWriteStream(dest);
		var byline = new ByLineReader();
		var process = new ProcessorTransform(function(chunk){
			if (chunk.indexOf("---") == 0) return "";
			if (chunk.indexOf("{% capture") == 0) return "";
			return chunk.replace(/\{\{ baseurl \}\}/g, "");
		});
		
		sfile.pipe(byline).pipe(process).pipe(dfile);
	}
	
}


/////////////////// Finally, call main ///////////////////
sync.fiber(build);
Пример #29
0
var sync = require('synchronize')
var fs   = require('fs')

sync(fs, 'readdir', 'stat', 'readFile')

sync.fiber(function(){
  var i, paths, path, stat, data
  paths = fs.readdir('.')
  for(i = 0; i < paths.length; i++){
    path = paths[i]
    stat = fs.stat(path)
    if(!stat.isFile()) continue
    data = fs.readFile(path, 'utf8')
    console.log(data)
  }
})
Пример #30
0
function stringer(lat, lng, numberOfMonths, threshold, callback) {

  sync.fiber(function() {
    // get last update date, so that we know where to start from.
    var dateJson = sync.await(utils.getTheJSON(
      "http://data.police.uk/api/crime-last-updated", sync.defer()));

    var currentDate = new Date(JSON.parse(dateJson).date);

    var lastUpdateTimeRef = new Date(0);
    try {
      var refJSON = sync.await(utils.readAsset('crime-stringer-reference/lastUpdate ' +
          lat + '-' + lng + '.json', sync.defer()));
      lastUpdateTimeRef = new Date(JSON.parse(refJSON));
    }
    catch(except) {
    }

    if (currentDate <= lastUpdateTimeRef) {
      return;
    }

    utils.writeAsset('crime-stringer-reference/lastUpdate.json', JSON.stringify(currentDate),
    function(err) {
      console.log(err);
    });

    var baseQuery = "http://data.police.uk/api/crimes-street/all-crime?lat=" +
      lat + "&lng=" + lng;

    // query crime stats for each month
    var crimeArray = [];
    while (numberOfMonths) {
      // build query for current month
      var currMonth = currentDate.getMonth() + 1; // months start at 0 ¬_¬
      currMonth = currMonth > 9 ? String(currMonth) : '0' + String(currMonth);
      var timeQuery = "&date=" + currentDate.getFullYear() + "-" + currMonth;

      console.log('police-uk: fetching data for ' + timeQuery);
      try {
        var data = sync.await(crimeQuery(baseQuery + timeQuery, sync.defer()));
        crimeArray.push(data);
      } catch (e) {
        console.log('caught exception while fetching data for ' + currentDate +
          ', skipping to next month');
      }

      currentDate.setMonth(currentDate.getMonth() - 1);
      numberOfMonths--;
    }

    // compute average for each category, over the time range
    var categories = Object.keys(crimeArray[0]);
    numberOfMonths = crimeArray.length;
    var categoryAverages = {};
    for (var c = 0; c < categories.length; c++) {
      var cat = categories[c];
      categoryAverages[cat] = 0;

      for (var i = 0; i < crimeArray.length; i++) {
        if (cat in crimeArray[i]) {
          categoryAverages[cat] += crimeArray[i][cat];
        }
      }

      categoryAverages[cat] /= numberOfMonths;
    }

    // for each category, compute the diff btw crime amount for last month and
    // average.
    // callback if > threshold
    for (var c = 0; c < categories.length; c++) {
      var cat = categories[c];
      var categoryDiff = (crimeArray[0][cat] - categoryAverages[cat]) / categoryAverages[cat] * 100;


      if (Math.abs(categoryDiff) > Math.abs(threshold)) {
        callback('crime-stringer', cat + ', diff: ' + categoryDiff);
      }
    }
  });
} //stringer