<commit_before>module.exports = {
  init: function () {
    let port

    try {
      port = require('find-port-sync')()
    } catch (_) {
      port = 62369
    }

    global.DP_TEST_PORT = port
    global.isTest = true

    return (fn, app, title) => {
      const request = require('supertest')

      describe(title || 'WebServer', () => {
        var http

        before(() => {
          http = app.dp.listen(port)

          if (global.__dpModelEngine__.destroyed) {
            global.__dpModelEngine__.registerDsn(app.dp.config.cfg.databaseDsn)
            global.__dpModelEngine__.destroyed = false
          }
        })

        after(() => {
          if (global.__dpModelEngine__ && global.__dpModelEngine__._conn) {
            Object.keys(global.__dpModelEngine__._conn).forEach((key) => {
              global.__dpModelEngine__._conn[key].destroy()
              delete global.__dpModelEngine__._conn[key]
            })
          }

          if (global.__dpSessionEngine__ && global.__dpSessionEngine__.engine) {
            global.__dpSessionEngine__.engine().close()
          }

          global.__dpModelEngine__.destroyed = true

          http.close()
          http = undefined
        })

        fn(() => {
          return request(http)
        })
      })
    }
  }
}
<commit_msg>Add arguments.<commit_after>module.exports = {
  init: function () {
    let port

    try {
      port = require('find-port-sync')()
    } catch (_) {
      port = 62369
    }

    global.DP_TEST_PORT = port
    global.isTest = true

    return (fn, app, title) => {
      const request = require('supertest')

      describe(title || 'WebServer', () => {
        var http

        before(() => {
          http = app.dp.listen(port)

          if (global.__dpModelEngine__.destroyed) {
            global.__dpModelEngine__.registerDsn(app.dp.config.cfg.databaseDsn)
            global.__dpModelEngine__.destroyed = false
          }
        })

        after(() => {
          if (global.__dpModelEngine__ && global.__dpModelEngine__._conn) {
            Object.keys(global.__dpModelEngine__._conn).forEach((key) => {
              global.__dpModelEngine__._conn[key].destroy()
              delete global.__dpModelEngine__._conn[key]
            })
          }

          if (global.__dpSessionEngine__ && global.__dpSessionEngine__.engine) {
            global.__dpSessionEngine__.engine().close()
          }

          global.__dpModelEngine__.destroyed = true

          http.close()
          http = undefined
        })

        fn(() => {
          return request(http)
        }, app.dp.config, app)
      })
    }
  }
}
<|endoftext|>


<commit_before>var config = {
  client_id: process.env.SLACK_CLIENT_ID,
  client_secret: process.env.SLACK_CLIENT_SECRET,
};

var express = require('express');
var router = express.Router();
var request = require('request');

var AUTH_URL = 'https://slack.com/api/oauth.access';
router.post('/tokens', function(req, res, next) {
  var code = req.body.authorizationCode;
  if (!code) {
    res.status(422);
    res.json({ message: 'Missing parameter: authorizationCode' });
    return;
  }

  var redirect_uri = req.body.redirectUri;
  if (!redirect_uri) {
    res.status(422);
    res.json({ message: 'Missing parameter: redirectUri' });
    return;
  }

  var params = {
    client_id: config.client_id,
    client_secret: config.client_secret,
    code: code,
    redirect_uri: redirect_uri
  };

  request.post({ url: AUTH_URL, form: params }, function(error, response, body) {
    if (error || response.statusCode !== 200) {
      res.status(500);
      res.json({ message: 'Unknown error occurred' });
      return;
    }

    data = JSON.parse(body);

    if (!data.ok) {
      res.status(400);
      res.json({ message: body.error || 'Unknown error occurred' });
      return;
    }

    res.status(201);
    res.json({
      accessToken: data.access_token,
      scope: data.scope
    });
  });
});

module.exports = router;
<commit_msg>Add API check<commit_after>var config = {
  client_id: process.env.SLACK_CLIENT_ID,
  client_secret: process.env.SLACK_CLIENT_SECRET,
};

var express = require('express');
var router = express.Router();
var request = require('request');

var AUTH_URL = 'https://slack.com/api/oauth.access';
router.get('/check', function(req, res, next) {
  res.sendStatus(204);
});
router.post('/tokens', function(req, res, next) {
  var code = req.body.authorizationCode;
  if (!code) {
    res.status(422);
    res.json({ message: 'Missing parameter: authorizationCode' });
    return;
  }

  var redirect_uri = req.body.redirectUri;
  if (!redirect_uri) {
    res.status(422);
    res.json({ message: 'Missing parameter: redirectUri' });
    return;
  }

  var params = {
    client_id: config.client_id,
    client_secret: config.client_secret,
    code: code,
    redirect_uri: redirect_uri
  };

  request.post({ url: AUTH_URL, form: params }, function(error, response, body) {
    if (error || response.statusCode !== 200) {
      res.status(500);
      res.json({ message: 'Unknown error occurred' });
      return;
    }

    data = JSON.parse(body);

    if (!data.ok) {
      res.status(400);
      res.json({ message: body.error || 'Unknown error occurred' });
      return;
    }

    res.status(201);
    res.json({
      accessToken: data.access_token,
      scope: data.scope
    });
  });
});

module.exports = router;
<|endoftext|>


<commit_before>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		i, j,
		steps = [],
		durations = [];

/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter
	/*
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
	*/
	spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.filterName]);
	spawn('odbedit', ['-c', "mkdir /Filter/Filters/" + req.body.filterName]);

console.log(filter)

	for(i=0; i<filter.length; i++){
		spawn('odbedit', ['-c', "create string /Filter/Filters/" + req.body.filterName + "/orCondition"+i+"[" + filter[i].length + "]" ]);
		for(j=0; j<filter[i].length; j++){
			console.log(filter[i][j]);

			spawn('odbedit', ['-c', "set /Filter/Filters/" + req.body.filterName + "/orCondition"+i + '['+j+'] ' + JSON.stringify(filter[i][j]) ]);
		}
	}

	/*
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}
*/
	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<commit_msg>fighting with weird ODB writing problems<commit_after>///////////////////////////////////////
//get requests
///////////////////////////////////////

app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

app.get('/Clocks', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Clock.jade');
});

app.get('/Filter', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/Filter.jade');
});

///////////////////////////////////////
//post routes
///////////////////////////////////////

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}

	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});

app.post('/registerFilter', function(req, res){
	var filter = (req.body.filterString) ? JSON.parse(req.body.filterString) : null,
		i, j,
		steps = [],
		durations = [];

/*
	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}
*/
	//register a new filter
	/*
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
	*/
	spawn('odbedit', ['-c', "rm /Filter/Filters/" + req.body.filterName]);
	spawn('odbedit', ['-c', "mkdir /Filter/Filters/" + req.body.filterName]);

	setTimeout(function(){
	for(i=0; i<filter.length; i++){
		spawn('odbedit', ['-c', "create string /Filter/Filters/" + req.body.filterName + "/orCondition"+i+"[" + filter[i].length + "]" ]);
		for(j=0; j<filter[i].length; j++){
			spawn('odbedit', ['-c', "set /Filter/Filters/" + req.body.filterName + "/orCondition"+i + '['+j+'] ' + filter[i][j] ]);
		}
	}
	}, 2000);

	/*
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"]  " + Math.round(steps[i]) ]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"]  " + Math.round(durations[i]) ]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}
*/
	return res.redirect('/Filter');

});

app.post('/updateClock', function(req, res){
	var ClockEnB = 0,
		powerOn,
		stepdown = parseInt(req.body.freqStepdown,10);

	//channel on / off
	for(i=0; i<6; i++){
		powerOn = req.body['eSATAtoggle' + i] == 1
		ClockEnB = ClockEnB | ((powerOn) ? (0xF << 4*i) : 0);
	}
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[0] " + ClockEnB]);

	//freq. stepdown
	if(stepdown && req.body.isMaster=='1'){
		for(i=0; i<8; i++){
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (11+4*i) + "] " + stepdown]);
			spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[" + (12+4*i) + "] " + stepdown]);
		}
	}

	return res.redirect('/Clocks');
});

app.post('/toggleClock', function(req, res){
	spawn('odbedit', ['-c', "set /Equipment/GRIF-Clk" + req.body.clockIndex + "/Variables/Output[1] " + req.body['radio'+req.body.clockIndex] ]);

	return res.redirect('/Clocks');
})

<|endoftext|>


<commit_before>app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

/*
app.get('/rawMSC', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('scratchTools/dumpMSC.jade');
});
*/

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
console.log(cycle)
	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);
	/*
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"] " + steps[i]]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"] " + durations[i]]);
	}
	*/

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations"]);
	spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes " + JSON.stringify(steps)]);
	spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations" + JSON.stringify(durations)]);

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});<commit_msg>weird cycle registration bug<commit_after>app.get('/HV', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/HV.jade');
});

app.get('/GRIFFIN', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('detectors/GRIFFIN.jade');
});

app.get('/DAQ', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/DAQ.jade');
});

app.get('/PPG', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('widgets/PPG.jade');
});

/*
app.get('/rawMSC', function(req, res){
	if(!req.cookies.midas_pwd) res.redirect(MIDAS)

	res.render('scratchTools/dumpMSC.jade');
});
*/

app.post('/postHV', function(req, res){

	spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Variables/Demand["+req.body.chIndex+"] " + req.body.demandVoltage]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Up Speed["+req.body.chIndex+"]' " + req.body.voltageUp]);
	spawn('odbedit', ['-c', "set '/Equipment/HV-"+req.body.crateIndex+"/Settings/Ramp Down Speed["+req.body.chIndex+"]' " + req.body.voltageDown]);

	if(req.body.powerSwitch == 'off')
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 0"]);
	else
		spawn('odbedit', ['-c', "set /Equipment/HV-"+req.body.crateIndex+"/Settings/ChState["+req.body.chIndex+"] 1"]);

	return res.redirect('/HV?crate=0&channel='+req.body.chName);
});

app.post('/registerCycle', function(req, res){
	var cycle = (req.body.cycleString) ? JSON.parse(req.body.cycleString) : null,
		i,
		steps = [],
		durations = [];

	//just load an existing cycle
	if(req.body.loadTarget != 'null'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.loadTarget]);
		return res.redirect('/PPG');
	}

	//delete an existing cycle
	if(req.body.deleteTarget != 'null'){
		spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.deleteTarget]);
		return res.redirect('/PPG');
	}

	//register a new cycle
	for(i=0; i<cycle.length; i++){
		steps[i] = parseInt(cycle[i].PPGcode, 10);
		durations[i] = parseInt(cycle[i].duration, 10);
	}
console.log(cycle)
	spawn('odbedit', ['-c', "rm /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "mkdir /PPG/Cycles/" + req.body.cycleName]);

	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/PPGcodes[" + steps.length + "]"]);
	spawn('odbedit', ['-c', "create int /PPG/Cycles/" + req.body.cycleName + "/durations[" + steps.length + "]"]);
	for(i=0; i<cycle.length; i++){
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/PPGcodes["+ i +"] " + steps[i]]);
		spawn('odbedit', ['-c', "set /PPG/Cycles/" + req.body.cycleName + "/durations["+ i +"] " + durations[i]]);
	}

	if(req.body.applyCycle == 'on'){
		spawn('odbedit', ['-c', "set /PPG/Current " + req.body.cycleName]);
	}

	return res.redirect('/PPG');
});<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *
 * Reverse Proxy Script using Node.js
 *
 * Usage: `sudo node rproxy.js` will open 80 port.
 *        `node rproxy.js 8888` will open 8888 port.
 *        `node rproxy.js 8888 8443` will open 8888 port and 8443 ssl port.
 *
 */

/*============================================================*/
/* Reverse Proxy Server Default Options Configuration         */
/*------------------------------------------------------------*/

var defaultOptions = {
  xfwd: true, // add X-Forwarded-* headers
};

// SSL Key file paths; change those paths if you have those in other paths.
var ssl_private_key_path = './priv.pem';
var ssl_certificate_path = './cert.pem';

/*------------------------------------------------------------*/
/* URL Path Mappings Configuration for Reverse Proxy Targets  */
/*------------------------------------------------------------*/
// You can add edit mappings below!

var mappings = [
  {
    host: '*',
    pathregex: /^\/cms(\/|$)/,
    route: {
      target: 'http://127.0.0.1:8080'
    }
  },
  {
    host: '*',
    pathregex: /^\/site(\/|$)/,
    route: {
      target: 'http://127.0.0.1:8080'
    }
  },
  {
    host: '*',
    pathregex: /^/,
    pathreplace: '/site',
    route: {
      target: 'http://127.0.0.1:8080'
    }
  },
];

/*------------------------------------------------------------*/
/* End of Configuration                                       */
/*============================================================*/

// Normally you don't need to look into the detail below
// in most cases unless you want to debug. :-)

/**************************************************************/
/* Internal Server Handling Code from here                    */
/*------------------------------------------------------------*/

// find out the port number command line argument
var port = 80;
if (process.argv[2]) {
  port = parseInt(process.argv[2]);
}

// build up the ssl options
var sslOptions = {};
var fs = require('fs');
if (fs.existsSync(ssl_private_key_path)) {
  sslOptions.key = fs.readFileSync(ssl_private_key_path, 'utf8');
} else {
  console.log('SSL Disabled. SSL private key file does not exist: ' + ssl_private_key_path);
}
if (fs.existsSync(ssl_certificate_path)) {
  sslOptions.cert = fs.readFileSync(ssl_certificate_path, 'utf8');
} else {
  console.log('SSL Disabled. SSL certificate does not exist: ' + ssl_certificate_path);
}

// let's start building proxy server from here

var http = require('http'),
    httpProxy = require('http-proxy');

//
// function to find a mapping by request path
//
var findMapping = function(req) {
  var host = req.headers['host'];
  for (var i in mappings) {
    var um = mappings[i];
    if (um.host && um.host != '*' && um.host != host) {
      continue;
    }
    if (um.pathregex && req.url.match(um.pathregex)) {
      return um;
    }
  }
  return null;
};

//
// Create a proxy server with custom application logic
//
var proxyServer = httpProxy.createProxyServer(defaultOptions);

//
// proxy handler
//
var proxyHandler = function(req, res) {
  var mapping = findMapping(req);
  if (!mapping) {
    res.writeHead(404);
    res.end();
    console.warn('WARN', req.url, 'Mapping not found');
  } else {
    if (mapping.pathreplace) {
      req.url = req.url.replace(mapping.pathregex, mapping.pathreplace);
    }
    console.log('INFO', req.url, mapping.route.target);
    proxyServer.web(req, res, mapping.route);
  }
};

//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
http.createServer(proxyHandler).listen(port);
console.log('');
console.log('Reverse Proxy Server started at port', port, '...');

// start another server at ssl port if configured
if (sslOptions.key && sslOptions.cert) {
  var sslPort = 443;
  if (process.argv[3]) {
    sslPort = parseInt(process.argv[3]);
  }
  // Create the HTTPS proxy server in front of an HTTP server
  httpProxy.createServer({
    target: {
      host: 'localhost',
      port: port
    },
    ssl: {
      key: sslOptions.key,
      cert: sslOptions.cert
    }
  }).listen(sslPort);
  console.log('Reverse Proxy Server started at SSL port', sslPort, '...');
}

// print out the route mapping information
console.log('');
console.log('Route mappings are as follows:');
console.log('***********************************************************');
console.log(mappings);
console.log('***********************************************************');
console.log('');
<commit_msg>Update rproxy.js<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *
 * Reverse Proxy Script using Node.js
 *
 * Usage: `sudo node rproxy.js` will open 80 port.
 *        `node rproxy.js 8888` will open 8888 port.
 *        `node rproxy.js 8888 8443` will open 8888 port and 8443 ssl port.
 *
 */

/*============================================================*/
/* Reverse Proxy Server Default Options Configuration         */
/*------------------------------------------------------------*/

var defaultOptions = {
  xfwd: true, // add X-Forwarded-* headers
};

// SSL Key file paths; change those paths if you have those in other paths.
var ssl_private_key_path = './priv.pem';
var ssl_certificate_path = './cert.pem';

/*------------------------------------------------------------*/
/* URL Path Mappings Configuration for Reverse Proxy Targets  */
/*------------------------------------------------------------*/
// You can add edit mappings below!

var mappings = [
  {
    host: '*',
    pathregex: /^\/cms(\/|$)/,
    route: {
      target: 'http://127.0.0.1:8080'
    }
  },
  {
    host: '*',
    pathregex: /^\/site(\/|$)/,
    route: {
      target: 'http://127.0.0.1:8080'
    }
  },
  {
    host: '*',
    pathregex: /^/,
    pathreplace: '/site',
    route: {
      target: 'http://127.0.0.1:8080'
    }
  },
];

/*------------------------------------------------------------*/
/* End of Configuration                                       */
/*============================================================*/

// Normally you don't need to look into the detail below
// in most cases unless you want to debug. :-)

var colors = require('colors');

colors.setTheme({
  silly: 'rainbow',
  input: 'grey',
  verbose: 'cyan',
  prompt: 'grey',
  info: 'green',
  data: 'grey',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red'
});

/**************************************************************/
/* Internal Server Handling Code from here                    */
/*------------------------------------------------------------*/

// find out the port number command line argument
var port = 80;
if (process.argv[2]) {
  port = parseInt(process.argv[2]);
}

// build up the ssl options
var sslOptions = {};
var fs = require('fs');
if (fs.existsSync(ssl_private_key_path)) {
  sslOptions.key = fs.readFileSync(ssl_private_key_path, 'utf8');
} else {
  console.log(('SSL Disabled. SSL private key file does not exist: ' + ssl_private_key_path).warn);
}
if (fs.existsSync(ssl_certificate_path)) {
  sslOptions.cert = fs.readFileSync(ssl_certificate_path, 'utf8');
} else {
  console.log(('SSL Disabled. SSL certificate does not exist: ' + ssl_certificate_path).warn);
}

// let's start building proxy server from here

var http = require('http'),
    httpProxy = require('http-proxy');

//
// function to find a mapping by request path
//
var findMapping = function(req) {
  var host = req.headers['host'];
  for (var i in mappings) {
    var um = mappings[i];
    if (um.host && um.host != '*' && um.host != host) {
      continue;
    }
    if (um.pathregex && req.url.match(um.pathregex)) {
      return um;
    }
  }
  return null;
};

//
// Create a proxy server with custom application logic
//
var proxyServer = httpProxy.createProxyServer(defaultOptions);

//
// proxy handler
//
var proxyHandler = function(req, res) {
  var mapping = findMapping(req);
  if (!mapping) {
    res.writeHead(404);
    res.end();
    console.log('WARN'.warn, 'Mapping not found for '.info, req.url.data);
  } else {
    var oldReqUrl = req.url;
    if (mapping.pathreplace) {
      req.url = oldReqUrl.replace(mapping.pathregex, mapping.pathreplace);
    }
    console.log('INFO'.info, oldReqUrl.data, '->'.verbose, ('' + mapping.route.target + req.url).data);
    proxyServer.web(req, res, mapping.route);
  }
};

//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
http.createServer(proxyHandler).listen(port);
console.log('');
console.log(('Reverse Proxy Server started at port ' + port + ' ...').info);

// start another server at ssl port if configured
if (sslOptions.key && sslOptions.cert) {
  var sslPort = 443;
  if (process.argv[3]) {
    sslPort = parseInt(process.argv[3]);
  }
  // Create the HTTPS proxy server in front of an HTTP server
  httpProxy.createServer({
    target: {
      host: 'localhost',
      port: port
    },
    ssl: {
      key: sslOptions.key,
      cert: sslOptions.cert
    }
  }).listen(sslPort);
  console.log(('Reverse Proxy Server started at SSL port ' + sslPort + ' ...').info);
}

// print out the route mapping information
console.log('');
console.log('Route mappings are as follows:'.info);
console.log('***********************************************************'.info);
console.log(mappings);
console.log('***********************************************************'.info);
console.log('');
<|endoftext|>


<commit_before>/**
 * A basic email verification
 * @bg info
 * @param {string} email came in email
 @ @returns {object}
 */
module.exports = (email = 'non', context, callback) => {
  const config = {
    api: {
      baseWebUrl: 'https://cowork.progressbar.sk/'
    }
  }
  const uuidv4 = require('uuid/v4')
  const normalizeEmail = require('validator/lib/normalizeEmail')
  const isEmail = require('validator/lib/isEmail')
  const mailgun = require('mailgun-js')({
    apiKey: process.env.mailgun_apiKey,
    domain: process.env.mailgun_domain
  })

  const firebase = require('firebase-admin')
  const firebaseConfig = {
    type: process.env.firebase_type,
    project_id: process.env.firebase_project_id,
    private_key_id: process.env.firebase_private_key_id,
    private_key: process.env.firebase_private_key,
    client_email: process.env.firebase_client_email,
    client_id: process.env.firebase_client_id,
    auth_uri: process.env.firebase_auth_uri,
    token_uri: process.env.firebase_token_uri,
    auth_provider_x509_cert_url: process.env.firebase_auth_provider_x509_cert_url,
    client_x509_cert_url: process.env.firebase_client_x509_cert_url
  }

  if (firebase.apps.length === 0) {
    firebase.initializeApp({
      credential: firebase.credential.cert(firebaseConfig),
      databaseURL: 'https://coweb-bc478.firebaseio.com'
    })
  }
  const db = firebase.database()
  const ref = db.ref('server')
  const subscribersRef = ref.child('subscribers')

  if (email === 'non') {
    callback(null, {
      code: 'non'
    })
  }

  if (!isEmail(email) || email.length <= 10) {
    callback(null, {
      code: 'Not an email'
    })
  }

  if (isEmail(email) && email.length > 10) {
    let normalizedEmail = normalizeEmail(email)
    const hash = uuidv4()
    const mailmsg = {
      from: `Progressbar Cowork noreply <no-reply@${process.env.mailgun_domain}>`,
      to: normalizedEmail,
      subject: 'Progressbar Cowork Email Verification',
      text:
`Hello, looks like somebody tried use your email as registration mail.
If it was you, please confirm your email address ${normalizedEmail}
by clicking on link ${config.api.baseWebUrl}#/email/${hash}
If you did not request this email, please ignore it.
Humanoid from ${config.api.baseWebUrl}`
    }

    let newSub = {
      [uuidv4()]: {
        email: normalizedEmail,
        createdAt: Date.now(),
        hash
      }
    }

    let emails = []
    subscribersRef.once('value', function (data) {
      let dataRef = data.val()
      for (let uid of Object.keys(dataRef)) {
        emails.push(dataRef[uid].email)
      }

      let seenEmail = emails.find(x => x === normalizedEmail)

      if (seenEmail === normalizedEmail) {
        callback(null, {
          newSubscriberEmail: normalizedEmail,
          error: 'already requested mail',
          code: 'Please confirm your email'
        })
      }

      if (seenEmail === undefined) {
        subscribersRef.update(newSub, function (err) {
          if (err) {
            console.log('err', err)
            callback(null, {
              newSubscriberEmail: normalizedEmail,
              at: 1,
              code: 'Error occured, try later'
            })
          } else {
            mailgun.messages().send(mailmsg, function (error, body) {
              if (error) {
                console.log('mailgunErr', error)
                callback(null, {
                  newSubscriberEmail: normalizedEmail,
                  at: 2,
                  code: 'Error occured, try later'
                })
              }
              if (!error) {
                callback(null, {
                  newSubscriberEmail: normalizedEmail,
                  code: 'Email has been sent'
                })
              }
            })
          }
        })
      }
    })
  }
}
<commit_msg>sanitized email<commit_after>/**
 * A basic email verification
 * @bg info
 * @param {string} email came in email
 @ @returns {object}
 */
module.exports = (email = 'non', context, callback) => {
  const config = {
    api: {
      baseWebUrl: 'https://cowork.progressbar.sk/'
    }
  }
  const uuidv4 = require('uuid/v4')
  const normalizeEmail = require('validator/lib/normalizeEmail')
  const isEmail = require('validator/lib/isEmail')
  const blacklist = require('validator/lib/blacklist')
  const mailgun = require('mailgun-js')({
    apiKey: process.env.mailgun_apiKey,
    domain: process.env.mailgun_domain
  })

  const firebase = require('firebase-admin')
  const firebaseConfig = {
    type: process.env.firebase_type,
    project_id: process.env.firebase_project_id,
    private_key_id: process.env.firebase_private_key_id,
    private_key: process.env.firebase_private_key,
    client_email: process.env.firebase_client_email,
    client_id: process.env.firebase_client_id,
    auth_uri: process.env.firebase_auth_uri,
    token_uri: process.env.firebase_token_uri,
    auth_provider_x509_cert_url: process.env.firebase_auth_provider_x509_cert_url,
    client_x509_cert_url: process.env.firebase_client_x509_cert_url
  }

  if (firebase.apps.length === 0) {
    firebase.initializeApp({
      credential: firebase.credential.cert(firebaseConfig),
      databaseURL: 'https://coweb-bc478.firebaseio.com'
    })
  }
  const db = firebase.database()
  const ref = db.ref('server')
  const subscribersRef = ref.child('subscribers')

  if (email === 'non') {
    callback(null, {
      code: 'non'
    })
  }

  email = blacklist(email, '\',/')

  if (!isEmail(email) || email.length <= 10) {
    callback(null, {
      code: 'Not an email'
    })
  }

  if (isEmail(email) && email.length > 10) {
    let normalizedEmail = normalizeEmail(email)
    const hash = uuidv4()
    const mailmsg = {
      from: `Progressbar Cowork noreply <no-reply@${process.env.mailgun_domain}>`,
      to: normalizedEmail,
      subject: 'Progressbar Cowork Email Verification',
      text:
`Hello, looks like somebody tried use your email as registration mail.
If it was you, please confirm your email address ${normalizedEmail}
by clicking on link ${config.api.baseWebUrl}#/email/${hash}
If you did not request this email, please ignore it.
Humanoid from ${config.api.baseWebUrl}`
    }

    let newSub = {
      [uuidv4()]: {
        email: normalizedEmail,
        createdAt: Date.now(),
        hash
      }
    }

    let emails = []
    subscribersRef.once('value', function (data) {
      let dataRef = data.val()
      for (let uid of Object.keys(dataRef)) {
        emails.push(dataRef[uid].email)
      }

      let seenEmail = emails.find(x => x === normalizedEmail)

      if (seenEmail === normalizedEmail) {
        callback(null, {
          newSubscriberEmail: normalizedEmail,
          error: 'already requested mail',
          code: 'Please confirm your email'
        })
      }

      if (seenEmail === undefined) {
        subscribersRef.update(newSub, function (err) {
          if (err) {
            console.log('err', err)
            callback(null, {
              newSubscriberEmail: normalizedEmail,
              at: 1,
              code: 'Error occured, try later'
            })
          } else {
            mailgun.messages().send(mailmsg, function (error, body) {
              if (error) {
                console.log('mailgunErr', error)
                callback(null, {
                  newSubscriberEmail: normalizedEmail,
                  at: 2,
                  code: 'Error occured, try later'
                })
              }
              if (!error) {
                callback(null, {
                  newSubscriberEmail: normalizedEmail,
                  code: 'Email has been sent'
                })
              }
            })
          }
        })
      }
    })
  }
}
<|endoftext|>


<commit_before>require("./js/mn-sequence.js");
require("./js/mn-midi-device.js");
require("./js/mn-heartbeat.js");
require("./js/mn-scale.js");
require("./js/mn-chord.js");
require("./js/mn-chordprogression.js");
require("./js/mn-note.js");
require("./js/mn-utils.js");

require("./chord-app.js");

{
//var rootNote = "c4"
//var scale = "major"
//var progression = [1, 5 ,4 , 1];
}

var rootNote = "c4"
var scale = "minor"
var progression = [1, 7 ,4 , 6, 1, 3, 6, 6];

// dumps some information about distance between inversions in the progression
var analyseProgression = function(sequence)
{
  console.log("chord sequence = " + JSON.stringify(sequence));
  console.log("analysing distances");

  var sum = 0;

  for (var index = 0; index < sequence.length; index++)
  {
    var next = index < sequence.length -1 ? index + 1 : 0;
    var distance = chordSequence[next].distanceFrom(chordSequence[index]);
    console.log(index + "->" + next + ":" + distance);
    console.log(chordname(chordSequence[index].notes_));
    sum += Math.abs(distance);
  }

  console.log("entropy = " + sum);
}

//-------------------------------------------------------------------

//var cp = new ChordProgression(rootNote, scale);
//var chordSequence = makeChordSequence(rootNote, scale, progression);

var chordSequence = makeChordSequence(["a","cm"]);
chordSequence[0].invert(0);

analyseProgression(chordSequence);

var app = new ChordApp({
  sequence: chordSequence,
  resolution: 64,
  rectify: 2,
  device: "iac",
  tempo: 72,
});
console.log(JSON.stringify(app));
app.run();

<commit_msg>changed test sequence<commit_after>require("./js/mn-sequence.js");
require("./js/mn-midi-device.js");
require("./js/mn-heartbeat.js");
require("./js/mn-scale.js");
require("./js/mn-chord.js");
require("./js/mn-chordprogression.js");
require("./js/mn-note.js");
require("./js/mn-utils.js");

require("./chord-app.js");

{
//var rootNote = "c4"
//var scale = "major"
//var progression = [1, 5 ,4 , 1];
}

var rootNote = "c4"
var scale = "minor"
var progression = [1, 7 ,4 , 6, 1, 3, 6, 6];

// dumps some information about distance between inversions in the progression
var analyseProgression = function(sequence)
{
  console.log("chord sequence = " + JSON.stringify(sequence));
  console.log("analysing distances");

  var sum = 0;

  for (var index = 0; index < sequence.length; index++)
  {
    var next = index < sequence.length -1 ? index + 1 : 0;
    var distance = chordSequence[next].distanceFrom(chordSequence[index]);
    console.log(index + "->" + next + ":" + distance);
    console.log(chordname(chordSequence[index].notes_));
    sum += Math.abs(distance);
  }

  console.log("entropy = " + sum);
}

//-------------------------------------------------------------------

//var cp = new ChordProgression(rootNote, scale);
//var chordSequence = makeChordSequence(rootNote, scale, progression);

var chordSequence = makeChordSequence(["a","d","e","f#","d"]);
chordSequence[0].invert(0);

analyseProgression(chordSequence);

var app = new ChordApp({
  sequence: chordSequence,
  resolution: 64,
  rectify: 2,
  device: "iac",
  tempo: 72,
});
console.log(JSON.stringify(app));
app.run();

<|endoftext|>


<commit_before>/*
	npm install express
*/

var express 	= require('express');
var https 		= require('https');
var url 		= require('url');
var config	    = require('./squino_config');

var app = express();

var HELPSCOUT_USER_AGENT = 'Help Scout API / nodejs Client v0';

app.use(express.logger());

app.get( '/api', function( req, res ) {
	runAPI( req, res );
});

app.listen( config.port );
console.log( 'Started Squino Server');

function runAPI( servRequest, servResponse )
{

	servResponse.header( "Content-Type", "application/json");

	var options = {
   		host: 'api.helpscout.net',
		port: 443,
		path: '/v1/conversations/'+servRequest.query.id+'.json',
		// authentication headers
		headers: {
			'Authorization': 'Basic ' + new Buffer(config.helpscout_key + ':SortOfSecret').toString('base64')
		}
	};

	request = https.get( options, function( res ) {
		var body="";
		res.on('data', function( data ) {
			body += data;
		});

		res.on('end', function( ) {
			console.log( 'complete for '+servRequest.query.id );
			//servResponse.send( '
got it
');

			var obj = JSON.parse( body );

			console.log( obj );
			console.log( obj.item.subject + ' :: '+ obj.item.preview );

			var ideaTitle = obj.item.subject;
			var ideaSummary = obj.item.preview;
			var ideaUrl = 'https://secure.helpscout.net/conversation/'+servRequest.query.id;
			var ideaID = servRequest.query.id ;
			var feedbackName = obj.item.customer.firstName + ' ' + obj.item.customer.lastName;
			var feedbackEmail = obj.item.customer.email;

			// { "name" : "Bill Mahon" , "email" : "bill@example.come", "about" : "Signup after a trade exhibition", "feedback" : "love this product but it would be great if it rotated left as well', }

			var post_feedback_data = '{ "name" : "' + feedbackName + '", "email" : "' + feedbackEmail + '", "about" : "' + ideaTitle + '", "feedback" : "'
				+ ideaSummary + '
Link to Help Scout"}';

			var post_create_data = '{ "title" : "'+ ideaTitle+'", "summary" : "'+ ideaSummary + '", "url" : "'+ ideaUrl +'", "external_id" : "'+ideaID+'" }';
			var options2 = {
				hostname: 'app.prodpad.com',
				port: 443,
				//path: '/api/v1/idea/create?apikey='+config.prodpad_key,
				path: 'api/v1/feedback/create?apikey='+config.prodpad_key,
				method: 'POST',
				headers: {
          			'Content-Type': 'raw',
          			'Content-Length': post_feedback_data.length
      			}
			};

			var req = https.request(options2, function(resInner) {
				var innerBody = "";

	  			console.log('STATUS: ' + resInner.statusCode);
  				resInner.setEncoding('utf8');
  				resInner.on('data', function (chunk) {
	    			innerBody += chunk;
	    			console.log( chunk );
  				});

  				resInner.on( 'end', function( ) {
  					servResponse.send(
  					 	"response was: " + resInner.statusCode
  					 );
  				} );

			});

			req.on('error', function(e) {
  				console.log('problem with request: ' + e.message);
  			});

			console.log( post_feedback_data );
			// write data to request body
			req.write( post_feedback_data );
			req.end();

			/*{ "title" :"testing titles", "summary" : "FWD: Magellen - IM BCG RMBS 2, FTA - European RMBS Transaction :: Hey Zac - still working out the kinks with Kev and the EU folks", "url" : "https://secure.helpscout.net/conversation/15688980", "external_id" : "15688980" }*/

		});

		res.on( 'error', function( e ) {
			console.log( 'Got error:'+e.message );
		});
	});

	//servResponse.send( 'Hello World');
}

function createProdPadIdea( ideaSummary, ideaUrl, ideaID )
{
	var options = {
		hostname: 'app.prodpad.com',
		port: 443,
		path: '/api/v1/idea/create?apikey='+PRODPAD_API_KEY,
		method: 'POST'
	};

	var req = https.request(options, function(res) {
  			console.log('STATUS: ' + res.statusCode);
  			console.log('HEADERS: ' + JSON.stringify(res.headers));
  			res.setEncoding('utf8');
  			res.on('data', function (chunk) {
    			console.log('BODY: ' + chunk);
  			});
	});

	req.on('error', function(e) {
  		console.log('problem with request: ' + e.message);
	});

	// write data to request body
	req.write('{ "summary" : "'+ ideaSummary + '", "url" : "'+ ideaUrl +'", "external_id" : "'+ideaID+'" }');
	req.end();
}
<commit_msg>couple bugs in switch to feedback<commit_after>/*
	npm install express
*/

var express 	= require('express');
var https 		= require('https');
var url 		= require('url');
var config	    = require('./squino_config');

var app = express();

var HELPSCOUT_USER_AGENT = 'Help Scout API / nodejs Client v0';

app.use(express.logger());

app.get( '/api', function( req, res ) {
	runAPI( req, res );
});

app.listen( config.port );
console.log( 'Started Squino Server');

function runAPI( servRequest, servResponse )
{

	servResponse.header( "Content-Type", "application/json");

	var options = {
   		host: 'api.helpscout.net',
		port: 443,
		path: '/v1/conversations/'+servRequest.query.id+'.json',
		// authentication headers
		headers: {
			'Authorization': 'Basic ' + new Buffer(config.helpscout_key + ':SortOfSecret').toString('base64')
		}
	};

	request = https.get( options, function( res ) {
		var body="";
		res.on('data', function( data ) {
			body += data;
		});

		res.on('end', function( ) {

			var obj = JSON.parse( body );

			console.log( obj );
			console.log( obj.item.subject + ' :: '+ obj.item.preview );

			var ideaTitle = obj.item.subject;
			var ideaSummary = obj.item.preview;
			var ideaUrl = 'https://secure.helpscout.net/conversation/'+servRequest.query.id;
			var ideaID = servRequest.query.id ;
			var feedbackName = obj.item.customer.firstName + ' ' + obj.item.customer.lastName;
			var feedbackEmail = obj.item.customer.email;

			// { "name" : "Bill Mahon" , "email" : "bill@example.come", "about" : "Signup after a trade exhibition", "feedback" : "love this product but it would be great if it rotated left as well', }

			var post_feedback_data = '{ "name" : "' + feedbackName + '", "email" : "' + feedbackEmail + '", "about" : "' + ideaTitle + '", "feedback" : "'
				+ ideaSummary + '
Link to Help Scout Ticket"}';

			//path: '/api/v1/idea/create?apikey='+config.prodpad_key,

			var post_create_data = '{ "title" : "'+ ideaTitle+'", "summary" : "'+ ideaSummary + '", "url" : "'+ ideaUrl +'", "external_id" : "'+ideaID+'" }';
			var options2 = {
				hostname: 'app.prodpad.com',
				port: 443,
				path: '/api/v1/feedback/create?apikey='+config.prodpad_key,
				method: 'POST',
				headers: {
          			'Content-Type': 'raw',
          			'Content-Length': post_feedback_data.length
      			}
			};

			var req = https.request(options2, function(resInner) {
				var innerBody = "";

	  			console.log('STATUS: ' + resInner.statusCode);
  				resInner.setEncoding('utf8');
  				resInner.on('data', function (chunk) {
	    			innerBody += chunk;
	    			console.log( chunk );
  				});

  				resInner.on( 'end', function( ) {
  					servResponse.send(
  					 	"response was: " + resInner.statusCode
  					 );
  				} );

			});

			req.on('error', function(e) {
  				console.log('problem with request: ' + e.message);
  			});

			// write data to request body
			req.write( post_feedback_data );
			console.log( post_feedback_data );
			req.end();

			/*{ "title" :"testing titles", "summary" : "FWD: Magellen - IM BCG RMBS 2, FTA - European RMBS Transaction :: Hey Zac - still working out the kinks with Kev and the EU folks", "url" : "https://secure.helpscout.net/conversation/15688980", "external_id" : "15688980" }*/

		});

		res.on( 'error', function( e ) {
			console.log( 'Got error:'+e.message );
		});
	});

	//servResponse.send( 'Hello World');
}

function createProdPadIdea( ideaSummary, ideaUrl, ideaID )
{
	var options = {
		hostname: 'app.prodpad.com',
		port: 443,
		path: '/api/v1/idea/create?apikey='+PRODPAD_API_KEY,
		method: 'POST'
	};

	var req = https.request(options, function(res) {
  			console.log('STATUS: ' + res.statusCode);
  			console.log('HEADERS: ' + JSON.stringify(res.headers));
  			res.setEncoding('utf8');
  			res.on('data', function (chunk) {
    			console.log('BODY: ' + chunk);
  			});
	});

	req.on('error', function(e) {
  		console.log('problem with request: ' + e.message);
	});

	// write data to request body
	req.write('{ "summary" : "'+ ideaSummary + '", "url" : "'+ ideaUrl +'", "external_id" : "'+ideaID+'" }');
	req.end();
}
<|endoftext|>


<commit_before>import * as THREE from 'three';
import { runBenchmark } from './utils.js';
import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree, CENTER, AVERAGE, SAH, estimateMemoryInBytes, getBVHExtremes, MeshBVH } from '../src/index.js';

THREE.Mesh.prototype.raycast = acceleratedRaycast;
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;

const sphere = new THREE.Sphere( undefined, 3 );
const boxMat = new THREE.Matrix4().identity();
const box = new THREE.Box3();
box.min.set( - 1, - 1, - 1 );
box.min.set( 1, 1, 1 );

const intersectGeometry = new THREE.TorusBufferGeometry( 5, 5, 100, 50 );
const geomMat = new THREE.Matrix4().compose( new THREE.Vector3(), new THREE.Quaternion(), new THREE.Vector3( 0.1, 0.1, 0.1 ) );

const target1 = new THREE.Vector3();
const target2 = new THREE.Vector3();

const geometry = new THREE.TorusBufferGeometry( 5, 5, 700, 300 );
const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
const raycaster = new THREE.Raycaster();
raycaster.ray.origin.set( 0, 0, - 10 );
raycaster.ray.direction.set( 0, 0, 1 );

function logExtremes( bvh, geometry ) {

	const extremes = getBVHExtremes( bvh )[ 0 ];
	const bvhSize = estimateMemoryInBytes( bvh._roots );
	const serializedSize = estimateMemoryInBytes( MeshBVH.serialize( bvh, geometry ).roots );

	console.log(
		`\tExtremes:\n` +
		`\t\tmemory: ${ bvhSize / 1000 } kb\n` +
		`\t\tserialized: ${ serializedSize / 1000 } kb\n` +
		`\t\ttotal nodes: ${ extremes.total }\n` +
		`\t\ttris: ${extremes.tris.min}, ${extremes.tris.max}\n` +
		`\t\tdepth: ${extremes.depth.min}, ${extremes.depth.max}\n` +
		`\t\tsplits: ${extremes.splits[ 0 ]}, ${extremes.splits[ 1 ]}, ${extremes.splits[ 2 ]}\n`
	);

}

function runSuite( strategy, lazyGeneration = false ) {

	const options = { lazyGeneration, strategy };
	let preFunc = lazyGeneration ? () => geometry.computeBoundsTree( options ) : null;

	geometry.computeBoundsTree( options );
	logExtremes( geometry.boundsTree, geometry );

	runBenchmark(

		'Compute BVH',
		null,
		() => {

			geometry.computeBoundsTree( options );
			geometry.boundsTree = null;

		},
		3000,
		50

	);

	geometry.computeBoundsTree( options );
	runBenchmark(

		'Serialize',
		preFunc,
		() => {

			MeshBVH.serialize( geometry.boundsTree, geometry );

		},
		3000,
		50

	);

	const serialized = MeshBVH.serialize( geometry.boundsTree, geometry );
	runBenchmark(

		'Deserialize',
		preFunc,
		() => {

			MeshBVH.deserialize( serialized, geometry );

		},
		3000,
		50

	);

	geometry.computeBoundsTree( options );
	raycaster.firstHitOnly = false;
	runBenchmark(

		'BVH Raycast',
		preFunc,
		() => mesh.raycast( raycaster, [] ),
		3000

	);

	raycaster.firstHitOnly = true;
	runBenchmark(

		'First Hit Raycast',
		preFunc,
		() => mesh.raycast( raycaster, [] ),
		3000

	);

	console.log( '' );

	runBenchmark(

		'IntersectsSphere',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsSphere( mesh, sphere ),
		3000

	);

	runBenchmark(

		'IntersectsBox',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsBox( mesh, box, boxMat ),
		3000

	);

	runBenchmark(

		'DistanceToGeometry',
		preFunc,
		() => mesh.geometry.boundsTree.closestPointToGeometry( mesh, intersectGeometry, geomMat, target1, target2 ),
		3000

	);

	const vec = new THREE.Vector3();
	runBenchmark(

		'DistanceToPoint',
		preFunc,
		() => mesh.geometry.boundsTree.closestPointToPoint( mesh, vec, target1 ),
		3000

	);

	console.log( '' );

	intersectGeometry.computeBoundsTree( options );
	runBenchmark(

		'IntersectsGeometry with BVH',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsGeometry( mesh, intersectGeometry, geomMat ),
		3000

	);

	intersectGeometry.disposeBoundsTree();
	runBenchmark(

		'IntersectsGeometry without BVH',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsGeometry( mesh, intersectGeometry, geomMat ),
		3000

	);

}

console.log( '*Strategy: CENTER*' );
runSuite( CENTER );

console.log( '' );
console.log( '*Strategy: Lazy CENTER*' );
runSuite( CENTER, true );

console.log( '' );
console.log( '*Strategy: AVERAGE*' );
runSuite( AVERAGE );

console.log( '' );
console.log( '*Strategy: SAH*' );
runSuite( SAH );

//

console.log( '' );
console.log( '*Strategy: NONE*' );

geometry.boundsTree = null;
raycaster.firstHitOnly = false;
runBenchmark(

	'Default Raycast',
	null,
	() => mesh.raycast( raycaster, [] ),
	3000

);

console.log( '' );

console.log( 'Extreme Case Tower Geometry' );

const towerGeometry = new THREE.PlaneBufferGeometry( 10, 10, 400, 400 );
const posAttr = towerGeometry.getAttribute( 'position' );
for ( let x = 0; x <= 100; x ++ ) {

	for ( let y = 0; y <= 100; y ++ ) {

		const inCenter = x > 100 && x < 300 && y > 100 && y < 300;
		const i = x * 100 + y;
		const z = inCenter ? 50 : - 50;
		posAttr.setZ( i, z + x * 0.01 );

	}

}

raycaster.firstHitOnly = false;
raycaster.ray.origin.set( 100, 100, 100 );
raycaster.ray.direction.set( - 1, - 1, - 1 );
mesh.geometry = towerGeometry;

towerGeometry.computeBoundsTree( { strategy: CENTER } );
runBenchmark(

	'CENTER raycast',
	null,
	() => mesh.raycast( raycaster ),
	3000

);
logExtremes( towerGeometry.boundsTree, towerGeometry );

towerGeometry.computeBoundsTree( { strategy: AVERAGE } );
runBenchmark(

	'AVERAGE raycast',
	null,
	() => mesh.raycast( raycaster ),
	3000

);
logExtremes( towerGeometry.boundsTree, towerGeometry );

towerGeometry.computeBoundsTree( { strategy: SAH } );
runBenchmark(

	'SAH raycast',
	null,
	() => mesh.raycast( raycaster ),
	3000

);
logExtremes( towerGeometry.boundsTree, towerGeometry );
<commit_msg>Update benchmark<commit_after>import * as THREE from 'three';
import { runBenchmark } from './utils.js';
import { acceleratedRaycast, computeBoundsTree, disposeBoundsTree, CENTER, AVERAGE, SAH, estimateMemoryInBytes, getBVHExtremes, MeshBVH } from '../src/index.js';

THREE.Mesh.prototype.raycast = acceleratedRaycast;
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;

const sphere = new THREE.Sphere( undefined, 3 );
const boxMat = new THREE.Matrix4().identity();
const box = new THREE.Box3();
box.min.set( - 1, - 1, - 1 );
box.min.set( 1, 1, 1 );

const intersectGeometry = new THREE.TorusBufferGeometry( 5, 5, 100, 50 );
const geomMat = new THREE.Matrix4().compose( new THREE.Vector3(), new THREE.Quaternion(), new THREE.Vector3( 0.1, 0.1, 0.1 ) );

const target1 = new THREE.Vector3();
const target2 = new THREE.Vector3();

const geometry = new THREE.TorusBufferGeometry( 5, 5, 700, 300 );
const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
const raycaster = new THREE.Raycaster();
raycaster.ray.origin.set( 0, 0, - 10 );
raycaster.ray.direction.set( 0, 0, 1 );

function logExtremes( bvh, geometry ) {

	const extremes = getBVHExtremes( bvh )[ 0 ];
	const bvhSize = estimateMemoryInBytes( bvh._roots );
	const serializedSize = estimateMemoryInBytes( MeshBVH.serialize( bvh, geometry ).roots );

	console.log(
		`\tExtremes:\n` +
		`\t\tmemory: ${ bvhSize / 1000 } kb\n` +
		`\t\tserialized: ${ serializedSize / 1000 } kb\n` +
		`\t\ttotal nodes: ${ extremes.total }\n` +
		`\t\ttris: ${extremes.tris.min}, ${extremes.tris.max}\n` +
		`\t\tdepth: ${extremes.depth.min}, ${extremes.depth.max}\n` +
		`\t\tsplits: ${extremes.splits[ 0 ]}, ${extremes.splits[ 1 ]}, ${extremes.splits[ 2 ]}\n`
	);

}

function runSuite( strategy, lazyGeneration = true ) {

	const options = { lazyGeneration, strategy };
	let preFunc = lazyGeneration ? () => geometry.computeBoundsTree( options ) : null;

	geometry.computeBoundsTree( options );
	logExtremes( geometry.boundsTree, geometry );

	runBenchmark(

		'Compute BVH',
		null,
		() => {

			geometry.computeBoundsTree( options );
			geometry.boundsTree = null;

		},
		3000,
		50

	);

	geometry.computeBoundsTree( options );
	runBenchmark(

		'Serialize',
		preFunc,
		() => {

			MeshBVH.serialize( geometry.boundsTree, geometry );

		},
		3000,
		50

	);

	const serialized = MeshBVH.serialize( geometry.boundsTree, geometry );
	runBenchmark(

		'Deserialize',
		preFunc,
		() => {

			MeshBVH.deserialize( serialized, geometry );

		},
		3000,
		50

	);

	geometry.computeBoundsTree( options );
	raycaster.firstHitOnly = false;
	runBenchmark(

		'BVH Raycast',
		preFunc,
		() => mesh.raycast( raycaster, [] ),
		3000

	);

	raycaster.firstHitOnly = true;
	runBenchmark(

		'First Hit Raycast',
		preFunc,
		() => mesh.raycast( raycaster, [] ),
		3000

	);

	console.log( '' );

	runBenchmark(

		'IntersectsSphere',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsSphere( mesh, sphere ),
		3000

	);

	runBenchmark(

		'IntersectsBox',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsBox( mesh, box, boxMat ),
		3000

	);

	runBenchmark(

		'DistanceToGeometry',
		preFunc,
		() => mesh.geometry.boundsTree.closestPointToGeometry( mesh, intersectGeometry, geomMat, target1, target2 ),
		3000

	);

	const vec = new THREE.Vector3();
	runBenchmark(

		'DistanceToPoint',
		preFunc,
		() => mesh.geometry.boundsTree.closestPointToPoint( mesh, vec, target1 ),
		3000

	);

	console.log( '' );

	intersectGeometry.computeBoundsTree( options );
	runBenchmark(

		'IntersectsGeometry with BVH',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsGeometry( mesh, intersectGeometry, geomMat ),
		3000

	);

	intersectGeometry.disposeBoundsTree();
	runBenchmark(

		'IntersectsGeometry without BVH',
		preFunc,
		() => mesh.geometry.boundsTree.intersectsGeometry( mesh, intersectGeometry, geomMat ),
		3000

	);

}

console.log( '*Strategy: CENTER*' );
runSuite( CENTER );

console.log( '' );
console.log( '*Strategy: Non-Lazy CENTER*' );
runSuite( CENTER, false );

console.log( '' );
console.log( '*Strategy: AVERAGE*' );
runSuite( AVERAGE );

console.log( '' );
console.log( '*Strategy: SAH*' );
runSuite( SAH );

//

console.log( '' );
console.log( '*Strategy: NONE*' );

geometry.boundsTree = null;
raycaster.firstHitOnly = false;
runBenchmark(

	'Default Raycast',
	null,
	() => mesh.raycast( raycaster, [] ),
	3000

);

console.log( '' );

console.log( 'Extreme Case Tower Geometry' );

const towerGeometry = new THREE.PlaneBufferGeometry( 10, 10, 400, 400 );
const posAttr = towerGeometry.getAttribute( 'position' );
for ( let x = 0; x <= 100; x ++ ) {

	for ( let y = 0; y <= 100; y ++ ) {

		const inCenter = x > 100 && x < 300 && y > 100 && y < 300;
		const i = x * 100 + y;
		const z = inCenter ? 50 : - 50;
		posAttr.setZ( i, z + x * 0.01 );

	}

}

raycaster.firstHitOnly = false;
raycaster.ray.origin.set( 100, 100, 100 );
raycaster.ray.direction.set( - 1, - 1, - 1 );
mesh.geometry = towerGeometry;

towerGeometry.computeBoundsTree( { strategy: CENTER } );
runBenchmark(

	'CENTER raycast',
	null,
	() => mesh.raycast( raycaster ),
	3000

);
logExtremes( towerGeometry.boundsTree, towerGeometry );

towerGeometry.computeBoundsTree( { strategy: AVERAGE } );
runBenchmark(

	'AVERAGE raycast',
	null,
	() => mesh.raycast( raycaster ),
	3000

);
logExtremes( towerGeometry.boundsTree, towerGeometry );

towerGeometry.computeBoundsTree( { strategy: SAH } );
runBenchmark(

	'SAH raycast',
	null,
	() => mesh.raycast( raycaster ),
	3000

);
logExtremes( towerGeometry.boundsTree, towerGeometry );
<|endoftext|>


<commit_before>import Ember from "ember";
import PouchAdapterUtils from "hospitalrun/mixins/pouch-adapter-utils";

export default DS.PouchDBAdapter.extend(PouchAdapterUtils, {
    _specialQueries: [
        'containsValue',
        'keyValues',
        'mapReduce',
        'options.startkey',
        'options.endkey'
    ],

    databaseName: 'main',

    _createMapFunction: function(type, query, keys) {
        return function(doc, emit) {
            var found_doc = false,
                doctype,
                queryValue,
                uidx;

            if (doc._id && (uidx = doc._id.indexOf("_")) > 0) {
                try {
                    doctype = doc._id.substring(0, uidx);
                    if(doctype === type.typeKey) {
                        if (query.containsValue && query.containsValue.value) {
                            queryValue = query.containsValue.value.toLowerCase();
                            query.containsValue.keys.forEach(function(key) {
                                if (doc[key] && doc[key].toLowerCase().indexOf(queryValue) >= 0) {
                                    found_doc = true;
                                }
                            });
                        } else {
                            found_doc = true;
                        }
                        if (found_doc === true) {
                            if (query.keyValues) {
                                var emitKeys = Ember.ArrayPolyfills.map.call(keys, function(key) {
                                    return doc[key];
                                });
                                emit(emitKeys);
                            } else {
                                emit(doc._id, null);
                            }
                        }
                    }
                } catch (e) {
                    console.log("Got exception:",e);
                }
            }
        };
    },

    _handleQueryResponse: function(resolve, response, store, type, options) {
        if (response.rows) {
            var data = Ember.A(response.rows).mapBy('doc');
            if(Ember.isNone(options.embed)) {
                options.embed = true;
            }
            Ember.run(function(){
                this._resolveRelationships(store, type, data, options).then(function(data){
                    Ember.run(null, resolve, data);
                });
            }.bind(this));
        }
    },

    findQuery: function(store, type, query, options) {
        var specialQuery = false;
        for (var i=0;i< this._specialQueries.length; i++) {
            if (Ember.get(query,this._specialQueries[i])) {
                specialQuery = true;
                break;
            }
        }
        if (!specialQuery) {
            if (query.options) {
                var newQuery = Ember.copy(query);
                delete newQuery.options;
                return this._super(store, type, newQuery, query.options);
            } else {
                return this._super(store, type, query, options);
            }
        } else {
            var keys = [],
                mapReduce = null,
                queryKeys = [],
                queryParams = {};
            if (query.options) {
                queryParams = Ember.copy(query.options);
            }
            queryParams.reduce  = false;
            queryParams.include_docs = true;
            if (query.keyValues) {
                for (var key in query.keyValues) {
                    if (query.keyValues.hasOwnProperty(key)) {
                        keys.push(key);
                    }
                }
                queryKeys = keys.map(function(key) {
                    if(key.substring(key.length - 3) === "_id" ||
                       key.substring(key.length - 4) === "_ids" ||
                       key === "id") {
                        return this._idToPouchId(query.keyValues[key], type);
                    }
                    return query.keyValues[key];
                }.bind(this));
                if(!Ember.isEmpty(queryKeys)){
                    queryParams["key"] = [].concat(queryKeys);
                }
            }

            if (query.mapReduce) {
                mapReduce = query.mapReduce;
            } else if (query.containsValue ||query.keyValues) {
                mapReduce = this._createMapFunction(type, query, keys);
            }

            return new Ember.RSVP.Promise(function(resolve, reject){
                this._getDb().then(function(db){
                    try {
                        if (mapReduce) {

                            db.query(mapReduce, queryParams, function(err, response) {
                                if (err) {
                                    this._pouchError(reject)(err);
                                }
                                this._handleQueryResponse(resolve, response, store, type, options);
                            }.bind(this));
                        } else {
                            db.allDocs(queryParams, function(err, response) {
                                if (err) {
                                    this._pouchError(reject)(err);
                                }
                                this._handleQueryResponse(resolve, response, store, type, options);
                            }.bind(this));
                        }
                    } catch (err){
                        this._pouchError(reject)(err);
                    }
                }.bind(this), this._pouchError(reject));
            }.bind(this), "findQuery in application-pouchdb-adapter");
        }
    }
});<commit_msg>Fixed issue when error occurs<commit_after>import Ember from "ember";
import PouchAdapterUtils from "hospitalrun/mixins/pouch-adapter-utils";

export default DS.PouchDBAdapter.extend(PouchAdapterUtils, {
    _specialQueries: [
        'containsValue',
        'keyValues',
        'mapReduce',
        'options.startkey',
        'options.endkey'
    ],

    databaseName: 'main',

    _createMapFunction: function(type, query, keys) {
        return function(doc, emit) {
            var found_doc = false,
                doctype,
                queryValue,
                uidx;

            if (doc._id && (uidx = doc._id.indexOf("_")) > 0) {
                try {
                    doctype = doc._id.substring(0, uidx);
                    if(doctype === type.typeKey) {
                        if (query.containsValue && query.containsValue.value) {
                            queryValue = query.containsValue.value.toLowerCase();
                            query.containsValue.keys.forEach(function(key) {
                                if (doc[key] && doc[key].toLowerCase().indexOf(queryValue) >= 0) {
                                    found_doc = true;
                                }
                            });
                        } else {
                            found_doc = true;
                        }
                        if (found_doc === true) {
                            if (query.keyValues) {
                                var emitKeys = Ember.ArrayPolyfills.map.call(keys, function(key) {
                                    return doc[key];
                                });
                                emit(emitKeys);
                            } else {
                                emit(doc._id, null);
                            }
                        }
                    }
                } catch (e) {
                    console.log("Got exception:",e);
                }
            }
        };
    },

    _handleQueryResponse: function(resolve, response, store, type, options) {
        if (response.rows) {
            var data = Ember.A(response.rows).mapBy('doc');
            if(Ember.isNone(options.embed)) {
                options.embed = true;
            }
            Ember.run(function(){
                this._resolveRelationships(store, type, data, options).then(function(data){
                    Ember.run(null, resolve, data);
                });
            }.bind(this));
        }
    },

    findQuery: function(store, type, query, options) {
        var specialQuery = false;
        for (var i=0;i< this._specialQueries.length; i++) {
            if (Ember.get(query,this._specialQueries[i])) {
                specialQuery = true;
                break;
            }
        }
        if (!specialQuery) {
            if (query.options) {
                var newQuery = Ember.copy(query);
                delete newQuery.options;
                return this._super(store, type, newQuery, query.options);
            } else {
                return this._super(store, type, query, options);
            }
        } else {
            var keys = [],
                mapReduce = null,
                queryKeys = [],
                queryParams = {};
            if (query.options) {
                queryParams = Ember.copy(query.options);
            }
            queryParams.reduce  = false;
            queryParams.include_docs = true;
            if (query.keyValues) {
                for (var key in query.keyValues) {
                    if (query.keyValues.hasOwnProperty(key)) {
                        keys.push(key);
                    }
                }
                queryKeys = keys.map(function(key) {
                    if(key.substring(key.length - 3) === "_id" ||
                       key.substring(key.length - 4) === "_ids" ||
                       key === "id") {
                        return this._idToPouchId(query.keyValues[key], type);
                    }
                    return query.keyValues[key];
                }.bind(this));
                if(!Ember.isEmpty(queryKeys)){
                    queryParams["key"] = [].concat(queryKeys);
                }
            }

            if (query.mapReduce) {
                mapReduce = query.mapReduce;
            } else if (query.containsValue ||query.keyValues) {
                mapReduce = this._createMapFunction(type, query, keys);
            }

            return new Ember.RSVP.Promise(function(resolve, reject){
                this._getDb().then(function(db){
                    try {
                        if (mapReduce) {

                            db.query(mapReduce, queryParams, function(err, response) {
                                if (err) {
                                    this._pouchError(reject)(err);
                                } else {
                                    this._handleQueryResponse(resolve, response, store, type, options);
                                }
                            }.bind(this));
                        } else {
                            db.allDocs(queryParams, function(err, response) {
                                if (err) {
                                    this._pouchError(reject)(err);
                                } else {
                                    this._handleQueryResponse(resolve, response, store, type, options);
                                }
                            }.bind(this));
                        }
                    } catch (err){
                        this._pouchError(reject)(err);
                    }
                }.bind(this), this._pouchError(reject));
            }.bind(this), "findQuery in application-pouchdb-adapter");
        }
    }
});<|endoftext|>