<commit_before>/**
 * @info : LOG ACION
 * @author : coverguo
 * @date : 2014-12-16
 */

var LogService = require('../../service/LogService'),
    log4js = require('log4js'),
    http = require('http'),
    logger = log4js.getLogger(),
    isError = function (res, error) {
        if (error) {
            res.json({ret: 1, msg: error});
            return true;
        }
        return false;
    };
var formatArray = function (items, timePeriod, startDate, endDate, isNotWithTime) {
    var resultArr = [];
    var timeCount = Math.ceil((endDate - startDate) / timePeriod);
    for (; timeCount--;) {
        var tag = startDate + timeCount * timePeriod;
        var returnObj = {};
        returnObj.time = tag;
        returnObj.count = 0;
        while (items.length) {
            var data = items.pop();
            logger.debug('tag is '+tag);
	    logger.debug('timePeriod is '+ timePeriod);
	    logger.debug(tag-data.time);
	    if (tag - data.time < timePeriod && tag - data.time >= 0) {
                returnObj.count += parseInt(data.count);
		logger.debug('the match count is '+returnObj.count);
            } else {
                if(startDate <= data.time && data.time < endDate){
	            items.push(data);
                    break;
                }
            }
        }
        if (isNotWithTime) {
	    logger.debug('the catch count is '+returnObj.count);
            resultArr.push(returnObj.count);
        } else {
            resultArr.push(returnObj)
        }
        ;
    }
    return resultArr.reverse();
}

var LogAction = {
    queryLogList: function (params, req, res) {

        var logService = new LogService();

        params['endDate'] -= 0;
        params['startDate'] -= 0;
        params['id'] -= 0;
        delete params.user;
        logService.query(params, function (err, items) {
            if (isError(res, err)) {
                return;
            }
            ;

            res.json({ret: 0, msg: "success-query", data: items});
        });
    },
    queryLogCountOnly: function (params, req, res) {
        var logService = new LogService(),
            endDate = params['endDate'] -= 0,
            startDate = params['startDate'] -= 0,
            timePeriod = (params['timePeriod'] || 1) * 60000,
            resObj = {ret: 0, msg: "success-query"},
            history = params['history'] || 0;
        params['id'] -= 0;
        params['level'] = params['level'] || ['4'];
        delete params.user;
        logService.queryCount(params, function (err, items) {
            if (isError(res, err)) {
                return;
            }
            resObj.data = formatArray(items, timePeriod, startDate, endDate,false) || [];
            if (history) {
                var oneDay = 24 * 60 * 60 * 1000,
                    historyEnd = params['endDate'] = params['endDate'] - oneDay,
                    historyStart = params['startDate'] = params['startDate'] - oneDay;
                logService.queryCount(params, function (err, hisitems) {
                    if (isError(res, err)) {
                        return;
                    }
                    resObj.history = formatArray(hisitems, timePeriod, historyStart, historyEnd,false) || [];
                    logger.info('web query end' + Date.now());
                    res.jsonp(resObj);
                });

            } else {
                logger.info('web query end' + Date.now());
                res.jsonp(resObj);
            }
        });
    },
    querySvgCount: function (params, req, res) {
        var logService = new LogService(),
            endDate = params['endDate'] -= 0,
            startDate = params['startDate'] -= 0,
            timePeriod = (params['timePeriod'] || 1) * 60000,
            resObj = {ret: 0, msg: "success-query"},
            history = params['history'] || 0,
            isNotWithTime = params['withTime'] || false;
        params['id'] -= 0;
        params['level'] = params['level'] || ['4'];
        delete params.user;
        logService.queryHistorySvg(params, function (err, svgitems) {
            if (isError(res, err)) {
                return;
            }
            logger.debug(svgitems);
            resObj.svg = formatArray(svgitems, timePeriod, startDate, endDate, isNotWithTime) || [];
            logger.info('web query end' + Date.now());
            res.jsonp(resObj);
        })
    },
    queryLogCount: function (params, req, res) {
        var logService = new LogService(),
            errorObj = {}, resArr = [],
            endDate = params['endDate'] -= 0,
            startDate = params['startDate'] -= 0,
            contentVisable = params['content'] || false;
        params['id'] -= 0;
        params['level'] = ['4'];
        delete params.user;
        var timePeriod = (params['timePeriod'] || 1) * 60000;
        logService.query(params, function (err, items) {
            if (isError(res, err)) {
                return;
            }
            var timeCount = Math.ceil((endDate - startDate) / timePeriod);
            items.forEach(function (ele) {
                var date = Date.parse(ele.date);
                for (var i = 0; i <= timeCount; i++) {
                    var tag = startDate + i * timePeriod;
                    errorObj[tag] = Array.isArray(errorObj[tag]) ? errorObj[tag] : [];
                    if (date > tag && date < startDate + (i + 1) * timePeriod) {
                        errorObj[tag].push(ele);
                    }
                }
            });
            for (var key in errorObj) {
                if (contentVisable) {
                    errorObj[key] = errorObj[key];
                } else {
                    var item = {
                        time: key,
                        errorCount: errorObj[key].length
                    };
                    resArr.push(item);
                }
            }
            ;
            var resData = contentVisable ? errorObj : resArr;
            res.jsonp({ret: 0, msg: 'success-query', data: resData});
        });
    },
    code: function (params, req, res) {
        http.get(params.target, function (response) {
            var buffer = '';
            response.on('data', function (chunk) {
                buffer += chunk.toString();
            }).on('end', function () {
                res.json({ret: 0, msg: "success-query", data: buffer});
            });
        })
    }
};

module.exports = LogAction;

<commit_msg>add time chenck<commit_after>/**
 * @info : LOG ACION
 * @author : coverguo
 * @date : 2014-12-16
 */

var LogService = require('../../service/LogService'),
    log4js = require('log4js'),
    http = require('http'),
    logger = log4js.getLogger(),
    isError = function (res, error) {
        if (error) {
            res.json({ret: 1, msg: error});
            return true;
        }
        return false;
    };
var formatArray = function (items, timePeriod, startDate, endDate, isNotWithTime) {
    var resultArr = [];
    var timeCount = Math.ceil((endDate - startDate) / timePeriod);
    while (timeCount) {
        var tag = startDate + timeCount * timePeriod;
        var returnObj = {};
        returnObj.time = tag;
        returnObj.count = 0;
        while (items.length) {
            var data = items.pop();
            logger.debug('tag is '+tag);
	    logger.debug('timePeriod is '+ timePeriod);
	    logger.debug(tag-data.time);
	    if (tag - data.time <= timePeriod && tag - data.time >= 0) {
                returnObj.count += parseInt(data.count);
		logger.debug('the match count is '+returnObj.count);
            } else {
                if(startDate <= data.time && data.time <= endDate){
	            items.push(data);
                    break;
                }
            }
        }
        if (isNotWithTime) {
	    logger.debug('the catch count is '+returnObj.count);
            resultArr.push(returnObj.count);
        } else {
            resultArr.push(returnObj);
        }
        timeCount--;
    }
    return resultArr.reverse();
}

var LogAction = {
    queryLogList: function (params, req, res) {

        var logService = new LogService();

        params['endDate'] -= 0;
        params['startDate'] -= 0;
        params['id'] -= 0;
        delete params.user;
        logService.query(params, function (err, items) {
            if (isError(res, err)) {
                return;
            }
            ;

            res.json({ret: 0, msg: "success-query", data: items});
        });
    },
    queryLogCountOnly: function (params, req, res) {
        var logService = new LogService(),
            endDate = params['endDate'] -= 0,
            startDate = params['startDate'] -= 0,
            timePeriod = (params['timePeriod'] || 1) * 60000,
            resObj = {ret: 0, msg: "success-query"},
            history = params['history'] || 0;
        params['id'] -= 0;
        params['level'] = params['level'] || ['4'];
        delete params.user;
	//formate time
	endDate = new Date(endDate);
	endDate = Date.parse(endDate.getFullYear()+'-'+(endDate.getMonth()- -1)+'-'+endDate.getDate()+' '+endDate.getHours()+':'+endDate.getMinutes());
	startDate = new Date(startDate);
        startDate = Date.parse(startDate.getFullYear()+'-'+(startDate.getMonth()- -1)+'-'+startDate.getDate()+' '+startDate.getHours()+':'+startDate.getMinutes());
        //add time check
        if(startDate > endDate ){
        	res.jsonp({'message':'error,endDate shuould > startDate'});
		return;
        }
	logService.queryCount(params, function (err, items) {
            if (isError(res, err)) {
                return;
            }
            resObj.data = formatArray(items, timePeriod, startDate, endDate,false) || [];
            if (history) {
                var oneDay = 24 * 60 * 60 * 1000,
                    historyEnd = params['endDate'] = params['endDate'] - oneDay,
                    historyStart = params['startDate'] = params['startDate'] - oneDay;
                logService.queryCount(params, function (err, hisitems) {
                    if (isError(res, err)) {
                        return;
                    }
                    resObj.history = formatArray(hisitems, timePeriod, historyStart, historyEnd,false) || [];
                    logger.info('web query end' + Date.now());
                    res.jsonp(resObj);
                });

            } else {
                logger.info('web query end' + Date.now());
                res.jsonp(resObj);
            }
        });
    },
    querySvgCount: function (params, req, res) {
        var logService = new LogService(),
            endDate = params['endDate'] -= 0,
            startDate = params['startDate'] -= 0,
            timePeriod = (params['timePeriod'] || 1) * 60000,
            resObj = {ret: 0, msg: "success-query"},
            history = params['history'] || 0,
            isNotWithTime = params['withTime'] || false;
        params['id'] -= 0;
        params['level'] = params['level'] || ['4'];
        delete params.user;
        logService.queryHistorySvg(params, function (err, svgitems) {
            if (isError(res, err)) {
                return;
            }
            logger.debug(svgitems);
            resObj.svg = formatArray(svgitems, timePeriod, startDate, endDate, isNotWithTime) || [];
            logger.info('web query end' + Date.now());
            res.jsonp(resObj);
        })
    },
    queryLogCount: function (params, req, res) {
        var logService = new LogService(),
            errorObj = {}, resArr = [],
            endDate = params['endDate'] -= 0,
            startDate = params['startDate'] -= 0,
            contentVisable = params['content'] || false;
        params['id'] -= 0;
        params['level'] = ['4'];
        delete params.user;
        var timePeriod = (params['timePeriod'] || 1) * 60000;
        logService.query(params, function (err, items) {
            if (isError(res, err)) {
                return;
            }
            var timeCount = Math.ceil((endDate - startDate) / timePeriod);
            items.forEach(function (ele) {
                var date = Date.parse(ele.date);
                for (var i = 0; i <= timeCount; i++) {
                    var tag = startDate + i * timePeriod;
                    errorObj[tag] = Array.isArray(errorObj[tag]) ? errorObj[tag] : [];
                    if (date > tag && date < startDate + (i + 1) * timePeriod) {
                        errorObj[tag].push(ele);
                    }
                }
            });
            for (var key in errorObj) {
                if (contentVisable) {
                    errorObj[key] = errorObj[key];
                } else {
                    var item = {
                        time: key,
                        errorCount: errorObj[key].length
                    };
                    resArr.push(item);
                }
            }
            ;
            var resData = contentVisable ? errorObj : resArr;
            res.jsonp({ret: 0, msg: 'success-query', data: resData});
        });
    },
    code: function (params, req, res) {
        http.get(params.target, function (response) {
            var buffer = '';
            response.on('data', function (chunk) {
                buffer += chunk.toString();
            }).on('end', function () {
                res.json({ret: 0, msg: "success-query", data: buffer});
            });
        })
    }
};

module.exports = LogAction;

<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');

var source = process.argv.splice(2)[0];
var target = source.substring(0, source.lastIndexOf('.')) + '.css';

fs.readFile(source, 'utf-8', function(err, data) {
    if (err) throw err;

    var analyze = function(input) {
        return input.map(function(line) {
            var rPart = line.trimLeft();

            return {l: line.replace(rPart, ''), r: rPart};
        });
    };

    var transform = function(lines) {
        var bracketFound = false;

        return lines.map(function(line) {
            if (line.l) {
                return line.l + line.r + ';';
            }
            else if (line.r) {
                bracketFound = true;

                return line.r + ' {';
            }
            else if (bracketFound) {
                bracketFound = false;

                return '}';
            }
        });
    };

    var output = transform(analyze(data.split('\n'))).join('\n');

    fs.writeFile(target, output, function(err) {
        if (err) throw err;

        console.log('Wrote ' + target + '!');
    });
});

<commit_msg>Implement initial syntax tree generator<commit_after>#!/usr/bin/env node
var fs = require('fs');

var source = process.argv.splice(2)[0];
var target = source.substring(0, source.lastIndexOf('.')) + '.css';

fs.readFile(source, 'utf-8', function(err, data) {
    if (err) throw err;

    var analyze = function(input) {
        return input.map(function(line) {
            var rPart = line.trimLeft();

            return {l: line.replace(rPart, ''), r: rPart};
        });
    };

    var treeify = function(input) {
        var parents = [];

        return input.filter(function(elem) {return elem.l || elem.r;}).
                map(function(line) {
            parent = parents[parents.length - 1] || {ind: 0};

            elem = {name: line.r, children: [], ind: line.l.length};

            if (parent.ind == elem.ind) {
                parents.pop();
                parent = parents[parents.length -1] || {ind: 0};
            }

            if (elem.ind == 0) {
                parents = [elem];
                return elem;
            }
            else if (parent.ind < elem.ind) {
                parents.push(elem);
                parent.children.push(elem);
            }
        }).filter(function(elem) {return elem;});
    }

    var printTree = function(tree, i) {
        i = i || 0;

        tree.forEach(function(k) {
            if (k.children.length > 0) {
                console.log('depth: ' + i);
                console.log(k);

                printTree(k.children, i + 1);
            }
        });
    }

    var transform = function(lines) {
        var bracketFound = false;

        return lines.map(function(line) {
            if (line.l) {
                return line.l + line.r + ';';
            }
            else if (line.r) {
                bracketFound = true;

                return line.r + ' {';
            }
            else if (bracketFound) {
                bracketFound = false;

                return '}';
            }
        });
    };

    var parts = analyze(data.split('\n'));
    var tree = treeify(parts);
    printTree(tree);
    var output = transform(tree).join('\n');

    fs.writeFile(target, output, function(err) {
        if (err) throw err;

        console.log('Wrote ' + target + '!');
    });
});

<|endoftext|>


<commit_before>const _ = require("lodash");
const req = require("tiny_request");
const Telegram = require("telegram-node-bot");
const TelegramBaseController = Telegram.TelegramBaseController;

class StartController extends TelegramBaseController {

    startMenu($) {
        const mainMenu = () =>{
            $.runMenu({
                message: 'Выберите источник',
                layout: 2,
                'НБРБ': () =>{
                    console.log('НБРБ')
                    mainMenu()
                },
                'Другое': () =>{
                    otherBanks()
                }
            })
        }
        const otherBanks = () =>{
            $.runMenu({
                message: 'Выберите банк',
                layout: 2,
                'Мой банк': () => {
                    console.log('мой банк')
                    otherBanks()
                },
                'Назад': () =>{
                    mainMenu()
                }
            })
        }
        mainMenu()
    }
    get routes() {
        return {
            "/start": "startMenu"
        }
    }
}

let that = this;

module.exports = StartController;<commit_msg>Respond with NBRB currencies on button click<commit_after>const _ = require("lodash");
const req = require("tiny_request");
const Telegram = require("telegram-node-bot");
const TelegramBaseController = Telegram.TelegramBaseController;
const urls = ["http://www.nbrb.by/API/ExRates/Rates/145", "http://www.nbrb.by/API/ExRates/Rates/292", "http://www.nbrb.by/API/ExRates/Rates/298"];

class StartController extends TelegramBaseController {

    startMenu($) {
        const mainMenu = () => {
            $.runMenu({
                message: 'Выберите источник',
                layout: 2,
                'НБРБ': () => {
                    console.log('НБРБ')
                    getDefaultCurrencies().then((results) => {
                        console.log(results);
                        let response = "";
                        _.each(results, (result) => {
                            response += `${result.Cur_Abbreviation} - ${result.Cur_OfficialRate} \n`;
                        });
                        $.sendMessage(response).then(() => {
                            mainMenu()
                        });
                    })
                },
                'Другое': () => {
                    otherBanks()
                }
            })
        }
        const otherBanks = () => {
            $.runMenu({
                message: 'Выберите банк',
                layout: 2,
                'Мой банк': () => {
                    console.log('мой банк')
                    otherBanks()
                },
                'Назад': () => {
                    mainMenu()
                }
            })
        }
        mainMenu()
    }
    get routes() {
        return {
            "/start": "startMenu"
        }
    }
}

const getDefaultCurrencies = () => {
    let requests = [];
    _.each(urls, (url) => {
        let req = performRequest(url);
        requests.push(req);
    });
    return Promise.all(requests).then((responses) => {
        return responses;
    });
};

const performRequest = (url) => {
    let request = {
        url: url,
        json: true,
        headers: {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
            "Connection": "keep-alive"
        }
    };
    return new Promise((resolve, reject) => {
        req.get(request, (body, response, err) => {
            if (!err && response.statusCode === 200) {
                //console.log(body);
                resolve(body);
            } else {
                reject(err);
            }
        });
    });
}

module.exports = StartController;<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var newsFeedFilter = ("../engine/newsfeed_filter");
var models = require("../../models");
var auth = require('../authorization');
var log = require('../utils/logger');
var toJson = require('../utils/to_json');
var _ = require('lodash');

var moment = require('moment');

var getRecommendationFor = require('../engine/recommendations/events_manager').getRecommendationFor;
var airbrake = require('airbrake').createClient(process.env.AIRBRAKE_PROJECT_ID, process.env.AIRBRAKE_API_KEY);

var OVERALL_LIMIT=7;

var DATE_OPTIONS = { after: moment().add(-3, 'months').toDate() };

var setupOptions = function (req) {
  var options = {
    user_id: req.user ? req.user.id : -1
  };

  return options;
};

var processRecommendations = function (levelType, req, res, recommendedItemIds, error) {
  var finalIds;

  if (error) {
    finalIds = [];
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus:  500 });
    airbrake.notify(error, function(airbrakeErr, url) {
      if (airbrakeErr) {
        log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
      }
    });
  } else {
    finalIds = _.shuffle(recommendedItemIds);
    finalIds = _.dropRight(finalIds, OVERALL_LIMIT);
  }

  log.info("Recommendations domains status", { recommendedItemIds: recommendedItemIds });

  models.Post.findAll({
    where: {
      id: {
        $in: finalIds
      }
    },
    include: [
      {
        // Category
        model: models.Category,
        required: false,
        include: [
          {
            model: models.Image,
            required: false,
            as: 'CategoryIconImages'
          }
        ]
      },
      // Group
      {
        model: models.Group,
        include: [
          {
            model: models.Category,
            required: false
          },
          {
            model: models.Community,
            attributes: ['id','name','theme_id'],
            required: false
          }
        ]
      },
      // User
      {
        model: models.User,
        required: false,
        attributes: models.User.defaultAttributesWithSocialMediaPublic
      },
      // Image
      {
        model: models.Image,
        required: false,
        as: 'PostHeaderImages'
      },
      // PointRevision
      {
        model: models.PostRevision,
        required: false
      }
    ]
  }).then(function(posts) {
    res.send(posts);
  }).catch(function(error) {
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus: 500 });
    res.sendStatus(500);
  });
};

router.get('/domains/:id', auth.can('view domain'), function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    domain_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("domain", req, res, recommendedItemIds, error);
  });
});

router.get('/communities/:id', auth.can('view community'), auth.isLoggedIn, function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    community_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("community", req, res, recommendedItemIds, error);
  });
});

router.get('/groups/:id', auth.can('view group'), auth.isLoggedIn, function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    group_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("group", req, res, recommendedItemIds, error);
  });
});

module.exports = router;<commit_msg>Fixes<commit_after>var express = require('express');
var router = express.Router();
var newsFeedFilter = ("../engine/newsfeed_filter");
var models = require("../../models");
var auth = require('../authorization');
var log = require('../utils/logger');
var toJson = require('../utils/to_json');
var _ = require('lodash');

var moment = require('moment');

var getRecommendationFor = require('../engine/recommendations/events_manager').getRecommendationFor;
var airbrake = require('airbrake').createClient(process.env.AIRBRAKE_PROJECT_ID, process.env.AIRBRAKE_API_KEY);

var OVERALL_LIMIT=7;

var DATE_OPTIONS = { after: moment().add(-6, 'months').toDate() };

var setupOptions = function (req) {
  var options = {
    user_id: req.user ? req.user.id : -1
  };

  return options;
};

var processRecommendations = function (levelType, req, res, recommendedItemIds, error) {
  var finalIds;

  if (error) {
    finalIds = [];
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus:  500 });
    airbrake.notify(error, function(airbrakeErr, url) {
      if (airbrakeErr) {
        log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr, errorStatus: 500 });
      }
    });
  } else {
    finalIds = _.shuffle(recommendedItemIds);
    finalIds = _.dropRight(finalIds, OVERALL_LIMIT);
  }

  log.info("Recommendations domains status", { recommendedItemIds: recommendedItemIds });

  models.Post.findAll({
    where: {
      id: {
        $in: finalIds
      }
    },
    include: [
      {
        // Category
        model: models.Category,
        required: false,
        include: [
          {
            model: models.Image,
            required: false,
            as: 'CategoryIconImages'
          }
        ]
      },
      // Group
      {
        model: models.Group,
        include: [
          {
            model: models.Category,
            required: false
          },
          {
            model: models.Community,
            attributes: ['id','name','theme_id'],
            required: false
          }
        ]
      },
      // User
      {
        model: models.User,
        required: false,
        attributes: models.User.defaultAttributesWithSocialMediaPublic
      },
      // Image
      {
        model: models.Image,
        required: false,
        as: 'PostHeaderImages'
      },
      // PointRevision
      {
        model: models.PostRevision,
        required: false
      }
    ]
  }).then(function(posts) {
    res.send(posts);
  }).catch(function(error) {
    log.error("Recommendation Error "+levelType, { err: error, id: req.params.id, userId:  req.user ? req.user.id : -1, errorStatus: 500 });
    res.sendStatus(500);
  });
};

router.get('/domains/:id', auth.can('view domain'), function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    domain_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("domain", req, res, recommendedItemIds, error);
  });
});

router.get('/communities/:id', auth.can('view community'),  function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    community_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("community", req, res, recommendedItemIds, error);
  });
});

router.get('/groups/:id', auth.can('view group'), function(req, res) {
  var options = setupOptions(req);

  options = _.merge(options, {
    group_id: req.params.id,
    limit: OVERALL_LIMIT*2
  });

  getRecommendationFor(options.user_id, DATE_OPTIONS, options, function (error, recommendedItemIds) {
    processRecommendations("group", req, res, recommendedItemIds, error);
  });
});

module.exports = router;<|endoftext|>


<commit_before>module.exports = function(mongo) {
  if(!mongo) {
		throw "Missing mongo";
	}

	return {
    getAllUsersRouteHandler: getAllUsersRouteHandler,
    getUserRouteHandler: getUserRouteHandler,
    postUserRouteHandler: postUserRouteHandler
  };

  function getAllUsersRouteHandler(req, res, next) {
    mongo.collection('users').find({ }, { name: 1, provider: 1, _id: 1 }).toArray(function(err, items) {
			if (err) {
				var error = new Error("Users not found");
				error.statusCode = 404;
				return next(error);
			}
			res.render('users.html', { user: req.user, users: items });
		});
  }

	function getUserRouteHandler(req, res, next) {
    var ObjectID = require('mongodb').ObjectID;
		mongo.collection('users').findOne({ _id: new ObjectID(req.params.id) }, { name: 1, provider: 1, _id: 1, type: 1 }, function(err, item){
			if(err){
				var error = new Error("User not found");
				error.statusCode = 404;
				return next(error);
			}
			res.render('userDetail.html', { user: req.user, userName: item.name, userProvider: item.provider, userRank: item.type, userId: item._id });
		});
	}

	function postUserRouteHandler(req, res, next) {
		var ObjectID = require('mongodb').ObjectID;
		mongo.collection('users').findOne({ _id: new ObjectID(req.params.id) }, { name: 1, provider: 1, _id: 1 }, function(err, item) {
			if(err){
				var error = new Error("User not found");
				error.statusCode = 404;
				return next(error);
			}
			mongo.collection('users').findAndModify({ _id: new ObjectID(req.params.id) }, [], { $set: { } }, { new: true }, function(err){
				if(err){ console.log(err); }
				// if(err) { return next(err); }
			});
			res.render('userDetail.html', { user: req.user, userName: item.name, userProvider: item.provider, userRank: req.body.type, userId: item._id });
		});
	}
};
<commit_msg>updating user on db<commit_after>module.exports = function(mongo) {
  if(!mongo) {
		throw "Missing mongo";
	}

	return {
    getAllUsersRouteHandler: getAllUsersRouteHandler,
    getUserRouteHandler: getUserRouteHandler,
    postUserRouteHandler: postUserRouteHandler
  };

  function getAllUsersRouteHandler(req, res, next) {
    mongo.collection('users').find({ }, { name: 1, provider: 1, _id: 1 }).toArray(function(err, items) {
			if (err) {
				var error = new Error("Users not found");
				error.statusCode = 404;
				return next(error);
			}
			res.render('users.html', { user: req.user, users: items });
		});
  }

	function getUserRouteHandler(req, res, next) {
    var ObjectID = require('mongodb').ObjectID;
		mongo.collection('users').findOne({ _id: new ObjectID(req.params.id) }, { name: 1, provider: 1, _id: 1, type: 1 }, function(err, item){
			if(err){
				var error = new Error("User not found");
				error.statusCode = 404;
				return next(error);
			}
			res.render('userDetail.html', { user: req.user, userName: item.name, userProvider: item.provider, userRank: item.type, userId: item._id });
		});
	}

	function postUserRouteHandler(req, res, next) {
		var ObjectID = require('mongodb').ObjectID;
		mongo.collection('users').findOne({ _id: new ObjectID(req.params.id) }, { name: 1, provider: 1, _id: 1 }, function(err, item) {
			if(err){
				var error = new Error("User not found");
				error.statusCode = 404;
				return next(error);
			}
			mongo.collection('users').findAndModify({ _id: new ObjectID(req.params.id) }, [], { $set: { role: req.body.type } }, { new: true }, function(err){
				if(err){ console.log(err); }
				// if(err) { return next(err); }
			});
			res.render('userDetail.html', { user: req.user, userName: item.name, userProvider: item.provider, userRank: req.body.type, userId: item._id });
		});
	}
};
<|endoftext|>


<commit_before>'use strict';
	/*
	To use rangepicker prepend following snippet to index.html.tpl
	document
	.write('<scr' + 'ipt data-spa crossorigin defer src="/js/jquery.min.js"></sc' + 'ript>');
	document
	.write('<scr' + 'ipt data-spa crossorigin defer src="/js/jquery-ui.min.js"></sc' + 'ript>');
	document
	.write('<scr' + 'ipt data-spa crossorigin defer src="/js/moment.min.js"></sc' + 'ript>');
	document
	.write('<scr' +
	'ipt data-spa crossorigin defer src="/js/jquery.comiseo.daterangepicker.js"></sc' + 'ript>');
	*/
var _ = require('mano').i18n.bind('Daterange')
  , dateFrom = require('./select-date-from')
  , dateTo = require('./select-date-to')
  , moment = window.moment
  , jQuery = window.jQuery;

module.exports = function (/* opts */) {
	var opts = Object(arguments[0]);

	var dateToString = function (date) {
		return moment(date).format('YYYY-MM-DD').toString();
	};

	var stringToDate = function (string) {
		return moment(string).toDate();
	};

	setTimeout(function () {
		if (!jQuery) {
			console.error('Probably you will have to integrate JQuery and all ' +
				'rangepicker dependencies into into index.html.tpl file. ' +
				'Check select-date-range.js for instructions.');
		}
		var elem = jQuery('[rangepicker]');
		elem.daterangepicker({
			presetRanges: [{
				text: _('Today'),
				dateStart: function () {
					return moment();
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Yesterday'),
				dateStart: function () {
					return moment().subtract('days', 1);
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Week to date'),
				dateStart: function () {
					return moment().startOf('week');
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Month to date'),
				dateStart: function () {
					return moment().startOf('month');
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Last month'),
				dateStart: function () {
					return moment().subtract(1, 'months').startOf('month');
				},
				dateEnd: function () {
					return moment().subtract(1, 'months').endOf('month');
				}
			}, {
				text: _('Year to date'),
				dateStart: function () {
					return moment().startOf('year');
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Since launch'),
				dateStart: function () {
					return moment(("2016-09-01"));
				},
				dateEnd: function () {
					return moment();
				}
			}],
			datepickerOptions: {
				firstDay: 1,
				dayNamesMin: [_('Su'), _('Mo'), _('Tu'), _('We'), _('Th'), _('Fr'), _('Sa')],
				monthNames: [_('January'), _('February'), _('March'), _('April'),
					_('May'), _('June'), _('July'), _('August'),
					_('September'), _('October'), _('November'), _('December')],
				numberOfMonths: 2,
				initialText: _('Select period...')
			},
			applyButtonText: _('Apply'),
			clearButtonText: _('Clear'),
			cancelButtonText: _('Cancel'),
			mirrorOnCollision: true
		});
		elem.daterangepicker("setRange", {
			start: stringToDate(jQuery('#startId').val()),
			end: stringToDate(jQuery('#endId').val())
		});
		elem.on('change', function () {
			var range = elem.daterangepicker("getRange");
			jQuery('#startId').val(dateToString(range.start));
			jQuery('#endId').val(dateToString(range.end));
			$.dispatchEvent($('startId'), 'change');
			$.dispatchEvent($('endId'), 'change');
		});
	});

	return div(
		dateFrom({
			id: 'startId',
			type: 'hidden'
		}),
		dateTo({
			id: 'endId',
			type: 'hidden'
		}),
		input({
			id: opts.id || 'rangepicker',
			rangepicker: ''
		})
	);
};
<commit_msg>#1823 proper week start in selector<commit_after>'use strict';
	/*
	To use rangepicker prepend following snippet to index.html.tpl
	document
	.write('<scr' + 'ipt data-spa crossorigin defer src="/js/jquery.min.js"></sc' + 'ript>');
	document
	.write('<scr' + 'ipt data-spa crossorigin defer src="/js/jquery-ui.min.js"></sc' + 'ript>');
	document
	.write('<scr' + 'ipt data-spa crossorigin defer src="/js/moment.min.js"></sc' + 'ript>');
	document
	.write('<scr' +
	'ipt data-spa crossorigin defer src="/js/jquery.comiseo.daterangepicker.js"></sc' + 'ript>');
	*/
var _ = require('mano').i18n.bind('Daterange')
  , dateFrom = require('./select-date-from')
  , dateTo = require('./select-date-to')
  , moment = window.moment
  , jQuery = window.jQuery;

module.exports = function (/* opts */) {
	var opts = Object(arguments[0]);

	var dateToString = function (date) {
		return moment(date).format('YYYY-MM-DD').toString();
	};

	var stringToDate = function (string) {
		return moment(string).toDate();
	};

	setTimeout(function () {
		if (!jQuery) {
			console.error('Probably you will have to integrate JQuery and all ' +
				'rangepicker dependencies into into index.html.tpl file. ' +
				'Check select-date-range.js for instructions.');
		}
		var elem = jQuery('[rangepicker]');
		elem.daterangepicker({
			presetRanges: [{
				text: _('Today'),
				dateStart: function () {
					return moment();
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Yesterday'),
				dateStart: function () {
					return moment().subtract('days', 1);
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Week to date'),
				dateStart: function () {
					// JS week starts on Sunday
					return moment().startOf('week').add(1, 'days');
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Month to date'),
				dateStart: function () {
					return moment().startOf('month');
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Last month'),
				dateStart: function () {
					return moment().subtract(1, 'months').startOf('month');
				},
				dateEnd: function () {
					return moment().subtract(1, 'months').endOf('month');
				}
			}, {
				text: _('Year to date'),
				dateStart: function () {
					return moment().startOf('year');
				},
				dateEnd: function () {
					return moment();
				}
			}, {
				text: _('Since launch'),
				dateStart: function () {
					return moment(("2016-09-01"));
				},
				dateEnd: function () {
					return moment();
				}
			}],
			datepickerOptions: {
				firstDay: 1,
				dayNamesMin: [_('Su'), _('Mo'), _('Tu'), _('We'), _('Th'), _('Fr'), _('Sa')],
				monthNames: [_('January'), _('February'), _('March'), _('April'),
					_('May'), _('June'), _('July'), _('August'),
					_('September'), _('October'), _('November'), _('December')],
				numberOfMonths: 2,
				initialText: _('Select period...')
			},
			applyButtonText: _('Apply'),
			clearButtonText: _('Clear'),
			cancelButtonText: _('Cancel'),
			mirrorOnCollision: true
		});
		elem.daterangepicker("setRange", {
			start: stringToDate(jQuery('#startId').val()),
			end: stringToDate(jQuery('#endId').val())
		});
		elem.on('change', function () {
			var range = elem.daterangepicker("getRange");
			jQuery('#startId').val(dateToString(range.start));
			jQuery('#endId').val(dateToString(range.end));
			$.dispatchEvent($('startId'), 'change');
			$.dispatchEvent($('endId'), 'change');
		});
	});

	return div(
		dateFrom({
			id: 'startId',
			type: 'hidden'
		}),
		dateTo({
			id: 'endId',
			type: 'hidden'
		}),
		input({
			id: opts.id || 'rangepicker',
			rangepicker: ''
		})
	);
};
<|endoftext|>


<commit_before>'use strict';

var $ = require('../util/jquery');
var platform = require('../util/platform');
var Component = require('./Component');
var Scrollbar = require('./Scrollbar');
var $$ = Component.$$;

/**
  Wraps content in a scroll pane.

  @class ScrollPane
  @component

  @prop {String} scrollbarType 'native' or 'substance' for a more advanced visual scrollbar. Defaults to 'native'
  @prop {String} [scrollbarPosition] 'left' or 'right' only relevant when scrollBarType: 'substance'. Defaults to 'right'
  @prop {ui/Highlights} [highlights] object that maintains highlights and can be manipulated from different sources

  @example

  ```js
  $$(ScrollPane, {
    scrollbarType: 'substance', // defaults to native
    scrollbarPosition: 'left', // defaults to right
    onScroll: this.onScroll.bind(this),
    highlights: myHighlights
  }
  ```
 */
function ScrollPane() {
  Component.apply(this, arguments);

  if (this.props.highlights) {
    this.props.highlights.connect(this, {
      'highlights:updated': this.onHighlightsUpdated
    });
  }
}

ScrollPane.Prototype = function() {
  this.dispose = function() {
    if (this.props.highlights) {
      this.props.highlights.disconnect(this);
    }
  };

  this.onHighlightsUpdated = function(highlights) {
    this.refs.scrollbar.extendProps({
      highlights: highlights
    });
  };

  this.render = function() {
    var el = $$('div')
      .addClass('sc-scroll-pane');

    if (platform.isFF) {
      el.addClass('sm-firefox');
    }

    // Initialize Substance scrollbar (if enabled)
    if (this.props.scrollbarType === 'substance') {
      el.addClass('sm-substance-scrollbar');
      el.addClass('sm-scrollbar-position-'+this.props.scrollbarPosition);

      el.append(
        // TODO: is there a way to pass scrollbar highlights already
        // via props? Currently the are initialized with a delay
        $$(Scrollbar, {
          scrollPane: this
        }).ref('scrollbar')
          .attr('id', 'content-scrollbar')
      );

      // Scanline is debugging purposes, display: none by default.
      el.append(
        $$('div').ref("scanline").addClass('se-scanline')
      );
    }

    el.append(
      $$('div').ref('scrollable').addClass('se-scrollable').append(
        $$('div').ref('content').addClass('se-content').append(
          this.props.children
        )
      ).on('scroll', this.onScroll)
    );
    return el;
  };

  this.onScroll = function() {
    if (this.props.onScroll) {
      this.props.onScroll(this.getScrollPosition());
    }
  };

  /**
    Returns the height of scrollPane (inner content overflows)
  */

  this.getHeight = function() {
    var scrollableEl = this.getScrollableElement();
    return $(scrollableEl).height();
  };

  /**
    Returns the cumulated height of a panel's content
  */
  this.getContentHeight = function() {
    var contentHeight = 0;
    var contentEl = this.refs.content.el;
    $(contentEl).children().each(function() {
     contentHeight += $(this).outerHeight();
    });
    return contentHeight;
  };

  /**
    Get the `.se-content` element
  */
  this.getContentElement = function() {
    return this.refs.content.el;
  };

  /**
    Get the `.se-scrollable` element
  */
  this.getScrollableElement = function() {
    return this.refs.scrollable.el;
  };

  /**
    Get current scroll position (scrollTop) of `.se-scrollable` element
  */
  this.getScrollPosition = function() {
    var scrollableEl = this.getScrollableElement();
    return Math.floor($(scrollableEl).scrollTop() + 1);
  };

  /**
    Get offset relative to `.se-content`.

    @param {DOMNode} el DOM node that lives inside the
  */
  this.getPanelOffsetForElement = function(el) {
    // initial offset
    var offset = $(el).position().top;

    // Now look at the parents
    function addParentOffset(el) {
      var parentEl = el.parentNode;

      // Reached the content wrapper element or the parent el. We are done.
      if ($(el).hasClass('se-content') || !parentEl) return;

      // Found positioned element (calculate offset!)
      if ($(el).css('position') === 'absolute' || $(el).css('position') === 'relative') {
        offset += $(el).position().top;
      }
      addParentOffset(parentEl);
    }

    addParentOffset(el.parentNode);
    return offset;
  };

  /**
    Scroll to a given sub component.

    @param {String} componentId component id, must be present in data-id attribute
  */
  this.scrollTo = function(componentId) {
    var scrollableEl = this.getScrollableElement();
    var targetNode = $(scrollableEl).find('*[data-id="'+componentId+'"]')[0];
    if (targetNode) {
      var offset = this.getPanelOffsetForElement(targetNode);
      $(scrollableEl).scrollTop(offset);
    } else {
      console.warn(componentId, 'not found in scrollable container');
    }
  };
};

Component.extend(ScrollPane);

module.exports = ScrollPane;
<commit_msg>Manage optional TOC instance in ScrollPane.<commit_after>'use strict';

var $ = require('../util/jquery');
var platform = require('../util/platform');
var Component = require('./Component');
var Scrollbar = require('./Scrollbar');
var $$ = Component.$$;

/**
  Wraps content in a scroll pane.

  @class ScrollPane
  @component

  @prop {String} scrollbarType 'native' or 'substance' for a more advanced visual scrollbar. Defaults to 'native'
  @prop {String} [scrollbarPosition] 'left' or 'right' only relevant when scrollBarType: 'substance'. Defaults to 'right'
  @prop {ui/Highlights} [highlights] object that maintains highlights and can be manipulated from different sources
  @prop {ui/TOC} [toc] object that maintains table of content entries

  @example

  ```js
  $$(ScrollPane, {
    scrollbarType: 'substance', // defaults to native
    scrollbarPosition: 'left', // defaults to right
    onScroll: this.onScroll.bind(this),
    highlights: this.contentHighlights,
    toc: this.toc
  })
  ```
 */
function ScrollPane() {
  Component.apply(this, arguments);

  if (this.props.highlights) {
    this.props.highlights.connect(this, {
      'highlights:updated': this.onHighlightsUpdated
    });
  }
}

ScrollPane.Prototype = function() {
  this.dispose = function() {
    if (this.props.highlights) {
      this.props.highlights.disconnect(this);
    }
  };

  this.onHighlightsUpdated = function(highlights) {
    this.refs.scrollbar.extendProps({
      highlights: highlights
    });
  };

  this.render = function() {
    var el = $$('div')
      .addClass('sc-scroll-pane');

    if (platform.isFF) {
      el.addClass('sm-firefox');
    }

    // Initialize Substance scrollbar (if enabled)
    if (this.props.scrollbarType === 'substance') {
      el.addClass('sm-substance-scrollbar');
      el.addClass('sm-scrollbar-position-'+this.props.scrollbarPosition);

      el.append(
        // TODO: is there a way to pass scrollbar highlights already
        // via props? Currently the are initialized with a delay
        $$(Scrollbar, {
          scrollPane: this
        }).ref('scrollbar')
          .attr('id', 'content-scrollbar')
      );

      // Scanline is debugging purposes, display: none by default.
      el.append(
        $$('div').ref("scanline").addClass('se-scanline')
      );
    }

    el.append(
      $$('div').ref('scrollable').addClass('se-scrollable').append(
        $$('div').ref('content').addClass('se-content').append(
          this.props.children
        )
      ).on('scroll', this.onScroll)
    );
    return el;
  };

  this.onScroll = function() {
    if (this.props.onScroll) {
      this.props.onScroll(this.getScrollPosition(), this.refs.scrollable);
    }

    // Update TOC if provided
    if (this.props.toc) {
      this.context.toc.markActiveEntry(this);
    }
  };

  /**
    Returns the height of scrollPane (inner content overflows)
  */
  this.getHeight = function() {
    var scrollableEl = this.getScrollableElement();
    return $(scrollableEl).height();
  };

  /**
    Returns the cumulated height of a panel's content
  */
  this.getContentHeight = function() {
    var contentHeight = 0;
    var contentEl = this.refs.content.el;
    $(contentEl).children().each(function() {
     contentHeight += $(this).outerHeight();
    });
    return contentHeight;
  };

  /**
    Get the `.se-content` element
  */
  this.getContentElement = function() {
    return this.refs.content.el;
  };

  /**
    Get the `.se-scrollable` element
  */
  this.getScrollableElement = function() {
    return this.refs.scrollable.el;
  };

  /**
    Get current scroll position (scrollTop) of `.se-scrollable` element
  */
  this.getScrollPosition = function() {
    var scrollableEl = this.getScrollableElement();
    return Math.floor($(scrollableEl).scrollTop() + 1);
  };

  /**
    Get offset relative to `.se-content`.

    @param {DOMNode} el DOM node that lives inside the
  */
  this.getPanelOffsetForElement = function(el) {
    // initial offset
    var offset = $(el).position().top;

    // Now look at the parents
    function addParentOffset(el) {
      var parentEl = el.parentNode;

      // Reached the content wrapper element or the parent el. We are done.
      if ($(el).hasClass('se-content') || !parentEl) return;

      // Found positioned element (calculate offset!)
      if ($(el).css('position') === 'absolute' || $(el).css('position') === 'relative') {
        offset += $(el).position().top;
      }
      addParentOffset(parentEl);
    }

    addParentOffset(el.parentNode);
    return offset;
  };

  /**
    Scroll to a given sub component.

    @param {String} componentId component id, must be present in data-id attribute
  */
  this.scrollTo = function(componentId) {
    var scrollableEl = this.getScrollableElement();
    var targetNode = $(scrollableEl).find('*[data-id="'+componentId+'"]')[0];
    if (targetNode) {
      var offset = this.getPanelOffsetForElement(targetNode);
      $(scrollableEl).scrollTop(offset);
    } else {
      console.warn(componentId, 'not found in scrollable container');
    }
  };
};

Component.extend(ScrollPane);

module.exports = ScrollPane;
<|endoftext|>


<commit_before>'use strict';

/* Filters */

treeherder.filter('showOrHide', function() {
    // determine whether this is a label for a job group (like mochitest)
    return function(input, isCollapsed) {
        if (isCollapsed == true) {
            return "show" + input;
        } else {
            return "hide" + input;
        }
    };
});

treeherder.filter('platformName', function() {
    // fix the platform name from the raw name in the db, with the more
    // "human read-able" one from Config.js
    return function(input, name) {
            var newName = Config.OSNames[name];
            if (newName) {
                return newName;
            }
            // if it's not found in Config.js, then return it unchanged.
            return name;
    };
})

treeherder.filter('stripHtml', function() {
    return function(input) {
        return input.replace(/<\/?[^>]+>/gi, '');
    };
})

<commit_msg>fix possible exception<commit_after>'use strict';

/* Filters */

treeherder.filter('showOrHide', function() {
    // determine whether this is a label for a job group (like mochitest)
    return function(input, isCollapsed) {
        if (isCollapsed == true) {
            return "show" + input;
        } else {
            return "hide" + input;
        }
    };
});

treeherder.filter('platformName', function() {
    // fix the platform name from the raw name in the db, with the more
    // "human read-able" one from Config.js
    return function(input, name) {
            var newName = Config.OSNames[name];
            if (newName) {
                return newName;
            }
            // if it's not found in Config.js, then return it unchanged.
            return name;
    };
})

treeherder.filter('stripHtml', function() {
    return function(input) {
        var str = input || '';
        return str.replace(/<\/?[^>]+>/gi, '');
    };
})

<|endoftext|>


<commit_before>function HostDetailsControl($scope, $routeParams, $location, resourcesService, authService, statsService) {
    // Ensure logged in
    authService.checkLogin($scope);

    $scope.name = "hostdetails";
    $scope.params = $routeParams;

    $scope.visualization = zenoss.visualization;
    $scope.visualization.url = $location.protocol() + "://" + $location.host() + ':' + $location.port();
    $scope.visualization.urlPath = '/metrics/static/performance/query/';
    $scope.visualization.urlPerformance = '/metrics/api/performance/query/';
    $scope.visualization.debug = false;

    $scope.breadcrumbs = [
        { label: 'breadcrumb_hosts', url: '#/hosts' }
    ];

    // Also ensure we have a list of hosts
    refreshHosts($scope, resourcesService, true);

    $scope.running = buildTable('Name', [
        { id: 'Name', name: 'running_tbl_running' },
        { id: 'StartedAt', name: 'running_tbl_start' },
        { id: 'View', name: 'running_tbl_actions' }
    ]);

    $scope.ip_addresses = buildTable('Interface', [
        { id: 'Interface', name: 'ip_addresses_interface' },
        { id: 'Ip', name: 'ip_addresses_ip' }
    ]);

    $scope.graph = buildTable('Name', [
        { id: 'CPU', name: 'graph_tbl_cpu'},
        { id: 'Memory', name: 'graph_tbl_mem'}
    ]);

    $scope.viewConfig = function(running) {
        $scope.editService = $.extend({}, running);
        $scope.editService.config = 'TODO: Implement';
        $('#editConfig').modal('show');
    };

    $scope.viewLog = function(running) {
        $scope.editService = $.extend({}, running);
        resourcesService.get_service_state_logs(running.ServiceID, running.Id, function(log) {
            $scope.editService.log = log.Detail;
            $('#viewLog').modal('show');
        });
    };

    $scope.click_app = function(instance) {
        $location.path('/services/' + instance.ServiceID);
    };

    $scope.killRunning = function(running) {
        resourcesService.kill_running(running.HostID, running.Id, function() {
            refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
        });
    };

    refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
    refreshHosts($scope, resourcesService, true, function() {
        if ($scope.hosts.current) {
            $scope.breadcrumbs.push({ label: $scope.hosts.current.Name, itemClass: 'active' });
        }
    });

    statsService.is_collecting(function(status) {
        if (status == 200) {
            $scope.collectingStats = true;
        } else {
            $scope.collectingStats = false;
        }
    });

    $scope.cpuconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "color": "#aec7e8",
                "expression": null,
                "fill": false,
                "format": "%6.2f",
                "id": "system",
                "legend": "CPU (System)",
                "metric": "CpuacctStat.system",
                "name": "CPU (System)",
                "rate": true,
                "rateOptions": {},
                "type": "line"
            },
            {
                "aggregator": "avg",
                "color": "#98df8a",
                "expression": null,
                "fill": false,
                "format": "%6.2f",
                "id": "user",
                "legend": "CPU (User)",
                "metric": "CpuacctStat.user",
                "name": "CPU (User)",
                "rate": true,
                "rateOptions": {},
                "type": "line"
            }
        ],
        "footer": false,
        "format": "%6.2f",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "returnset": "EXACT",
        "tags": {},
        "type": "line",
        "downsample": "1m-avg"
    };

    $scope.ofdconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "color": "#aec7e8",
                "expression": null,
                "fill": false,
                "format": "%6.2f",
                "id": "ofd",
                "legend": "Serviced Open File Descriptors",
                "metric": "Serviced.OpenFileDescriptors",
                "name": "Serviced Open File Descriptors",
                "rate": false,
                "rateOptions": {},
                "type": "line"
            },
        ],
        "footer": false,
        "format": "%d",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "returnset": "EXACT",
        "tags": {},
        "type": "line",
        "downsample": "1m-avg"
    };

    $scope.memconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "color": "#aec7e8",
                "expression": null,
                "expression": null,
                "fill": false,
                "format": "%d",
                "id": "pgfault",
                "legend": "Page Faults",
                "metric": "MemoryStat.pgfault",
                "name": "Page Faults",
                "rate": true,
                "rateOptions": {},
                "type": "line"
            }
        ],
        "footer": false,
        "format": "%6.2f",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "returnset": "EXACT",
        "tags": {},
        "type": "line",
        "downsample": "1m-avg"
    };

    $scope.rssconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "expression": "rpn:1024,/,1024,/",
                "fill": false,
                "format": "%6.2f",
                "id": "rssmemory",
                "legend": "RSS Memory",
                "metric": "MemoryStat.rss",
                "name": "RSS Memory",
                "rateOptions": {},
                "type": "line",
                "fill": true
            }
        ],
        "footer": false,
        "format": "%6.2f",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "yAxisLabel": "MB",
        "returnset": "EXACT",
        height: 300,
        width: 300,
        "tags": {},
        "type": "line",
        "downsample": "1m-avg"
    };

    $scope.drawn = {};

    $scope.viz = function(id, config) {
        if (!$scope.drawn[id]) {
            if (window.zenoss === undefined) {
                return "Not collecting stats, graphs unavailable";
            } else {
                zenoss.visualization.chart.create(id, config);
                $scope.drawn[id] = true;
            }
        }
    };
}
<commit_msg>fix plot axis<commit_after>function HostDetailsControl($scope, $routeParams, $location, resourcesService, authService, statsService) {
    // Ensure logged in
    authService.checkLogin($scope);

    $scope.name = "hostdetails";
    $scope.params = $routeParams;

    $scope.visualization = zenoss.visualization;
    $scope.visualization.url = $location.protocol() + "://" + $location.host() + ':' + $location.port();
    $scope.visualization.urlPath = '/metrics/static/performance/query/';
    $scope.visualization.urlPerformance = '/metrics/api/performance/query/';
    $scope.visualization.debug = false;

    $scope.breadcrumbs = [
        { label: 'breadcrumb_hosts', url: '#/hosts' }
    ];

    // Also ensure we have a list of hosts
    refreshHosts($scope, resourcesService, true);

    $scope.running = buildTable('Name', [
        { id: 'Name', name: 'running_tbl_running' },
        { id: 'StartedAt', name: 'running_tbl_start' },
        { id: 'View', name: 'running_tbl_actions' }
    ]);

    $scope.ip_addresses = buildTable('Interface', [
        { id: 'Interface', name: 'ip_addresses_interface' },
        { id: 'Ip', name: 'ip_addresses_ip' }
    ]);

    $scope.graph = buildTable('Name', [
        { id: 'CPU', name: 'graph_tbl_cpu'},
        { id: 'Memory', name: 'graph_tbl_mem'}
    ]);

    $scope.viewConfig = function(running) {
        $scope.editService = $.extend({}, running);
        $scope.editService.config = 'TODO: Implement';
        $('#editConfig').modal('show');
    };

    $scope.viewLog = function(running) {
        $scope.editService = $.extend({}, running);
        resourcesService.get_service_state_logs(running.ServiceID, running.Id, function(log) {
            $scope.editService.log = log.Detail;
            $('#viewLog').modal('show');
        });
    };

    $scope.click_app = function(instance) {
        $location.path('/services/' + instance.ServiceID);
    };

    $scope.killRunning = function(running) {
        resourcesService.kill_running(running.HostID, running.Id, function() {
            refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
        });
    };

    refreshRunningForHost($scope, resourcesService, $scope.params.hostId);
    refreshHosts($scope, resourcesService, true, function() {
        if ($scope.hosts.current) {
            $scope.breadcrumbs.push({ label: $scope.hosts.current.Name, itemClass: 'active' });
        }
    });

    statsService.is_collecting(function(status) {
        if (status == 200) {
            $scope.collectingStats = true;
        } else {
            $scope.collectingStats = false;
        }
    });

    $scope.cpuconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "color": "#aec7e8",
                "expression": null,
                "fill": false,
                "format": "%6.2f",
                "id": "system",
                "legend": "CPU (System)",
                "metric": "CpuacctStat.system",
                "name": "CPU (System)",
                "rate": true,
                "rateOptions": {},
                "type": "line"
            },
            {
                "aggregator": "avg",
                "color": "#98df8a",
                "expression": null,
                "fill": false,
                "format": "%6.2f",
                "id": "user",
                "legend": "CPU (User)",
                "metric": "CpuacctStat.user",
                "name": "CPU (User)",
                "rate": true,
                "rateOptions": {},
                "type": "line"
            }
        ],
        "footer": false,
        "format": "%6.2f",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "returnset": "EXACT",
        "tags": {},
        "type": "line",
        "downsample": "1m-avg",
        "timezone": jstz.determine().name()
    };

    $scope.ofdconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "color": "#aec7e8",
                "expression": null,
                "fill": false,
                "format": "%6.2f",
                "id": "ofd",
                "legend": "Serviced Open File Descriptors",
                "metric": "Serviced.OpenFileDescriptors",
                "name": "Serviced Open File Descriptors",
                "rate": false,
                "rateOptions": {},
                "type": "line"
            },
        ],
        "footer": false,
        "format": "%d",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "returnset": "EXACT",
        "tags": {},
        "type": "line",
        "downsample": "1m-avg",
        "timezone": jstz.determine().name()
    };

    $scope.memconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "color": "#aec7e8",
                "expression": null,
                "expression": null,
                "fill": false,
                "format": "%d",
                "id": "pgfault",
                "legend": "Page Faults",
                "metric": "MemoryStat.pgfault",
                "name": "Page Faults",
                "rate": true,
                "rateOptions": {},
                "type": "line"
            }
        ],
        "footer": false,
        "format": "%6.2f",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "returnset": "EXACT",
        "tags": {},
        "type": "line",
        "downsample": "1m-avg",
        "timezone": jstz.determine().name()
    };

    $scope.rssconfig = {
        "datapoints": [
            {
                "aggregator": "avg",
                "expression": "rpn:1024,/,1024,/",
                "fill": false,
                "format": "%6.2f",
                "id": "rssmemory",
                "legend": "RSS Memory",
                "metric": "MemoryStat.rss",
                "name": "RSS Memory",
                "rateOptions": {},
                "type": "line",
                "fill": true
            }
        ],
        "footer": false,
        "format": "%6.2f",
        "maxy": null,
        "miny": 0,
        "range": {
            "end": "0s-ago",
            "start": "1h-ago"
        },
        "yAxisLabel": "MB",
        "returnset": "EXACT",
        height: 300,
        width: 300,
        "tags": {},
        "type": "line",
        "downsample": "1m-avg",
        "timezone": jstz.determine().name()
    };

    $scope.drawn = {};

    $scope.viz = function(id, config) {
        if (!$scope.drawn[id]) {
            if (window.zenoss === undefined) {
                return "Not collecting stats, graphs unavailable";
            } else {
                zenoss.visualization.chart.create(id, config);
                $scope.drawn[id] = true;
            }
        }
    };
}
<|endoftext|>


<commit_before>(function() {

  if (typeof document !== 'undefined' && typeof window !== 'undefined') {
    return;
  }

  var DOMParser = new require('xmldom').DOMParser,
      URL = require('url'),
      HTTP = require('http'),
      HTTPS = require('https'),

      Canvas = require('canvas'),
      Image = require('canvas').Image;

  /** @private */
  function request(url, encoding, callback) {
    var oURL = URL.parse(url);

    // detect if http or https is used
    if ( !oURL.port ) {
      oURL.port = ( oURL.protocol.indexOf('https:') === 0 ) ? 443 : 80;
    }

    // assign request handler based on protocol
    var reqHandler = ( oURL.port === 443 ) ? HTTPS : HTTP;

    var req = reqHandler.request({
      hostname: oURL.hostname,
      port: oURL.port,
      path: oURL.path,
      method: 'GET'
    }, function(response){
      var body = "";
      if (encoding) {
        response.setEncoding(encoding);
      }
      response.on('end', function () {
        callback(body);
      });
      response.on('data', function (chunk) {
        if (response.statusCode === 200) {
          body += chunk;
        }
      });
    });

    req.on('error', function(err) {
      if (err.errno === process.ECONNREFUSED) {
        fabric.log('ECONNREFUSED: connection refused to ' + oURL.hostname + ':' + oURL.port);
      }
      else {
        fabric.log(err.message);
      }
    });

    req.end();
  }

  /** @private */
  function request_fs(path, callback){
    var fs = require('fs');
    fs.readFile(path, function (err, data) {
      if (err) {
        fabric.log(err);
        throw err;
      } else {
        callback(data);
      }
    });
  }

  fabric.util.loadImage = function(url, callback, context) {
    var createImageAndCallBack = function(data){
      img.src = new Buffer(data, 'binary');
      // preserving original url, which seems to be lost in node-canvas
      img._src = url;
      callback && callback.call(context, img);
    };
    var img = new Image();
    if (url && (url instanceof Buffer || url.indexOf('data') === 0)) {
      img.src = img._src = url;
      callback && callback.call(context, img);
    }
    else if (url && url.indexOf('http') !== 0) {
      request_fs(url, createImageAndCallBack);
    }
    else if (url) {
      request(url, 'binary', createImageAndCallBack);
    }
    else {
      callback && callback.call(context, url);
    }
  };

  fabric.loadSVGFromURL = function(url, callback, reviver) {
    url = url.replace(/^\n\s*/, '').replace(/\?.*$/, '').trim();
    if (url.indexOf('http') !== 0) {
      request_fs(url, function(body) {
        fabric.loadSVGFromString(body.toString(), callback, reviver);
      });
    }
    else {
      request(url, '', function(body) {
        fabric.loadSVGFromString(body, callback, reviver);
      });
    }
  };

  fabric.loadSVGFromString = function(string, callback, reviver) {
    var doc = new DOMParser().parseFromString(string);
    fabric.parseSVGDocument(doc.documentElement, function(results, options) {
      callback && callback(results, options);
    }, reviver);
  };

  fabric.util.getScript = function(url, callback) {
    request(url, '', function(body) {
      eval(body);
      callback && callback();
    });
  };

  fabric.Image.fromObject = function(object, callback) {
    fabric.util.loadImage(object.src, function(img) {
      var oImg = new fabric.Image(img);

      oImg._initConfig(object);
      oImg._initFilters(object, function(filters) {
        oImg.filters = filters || [ ];
        callback && callback(oImg);
      });
    });
  };

  /**
   * Only available when running fabric on node.js
   * @param width Canvas width
   * @param height Canvas height
   * @param {Object} options to pass to FabricCanvas.
   * @return {Object} wrapped canvas instance
   */
  fabric.createCanvasForNode = function(width, height, options) {

    var canvasEl = fabric.document.createElement('canvas'),
        nodeCanvas = new Canvas(width || 600, height || 600);

    // jsdom doesn't create style on canvas element, so here be temp. workaround
    canvasEl.style = { };

    canvasEl.width = nodeCanvas.width;
    canvasEl.height = nodeCanvas.height;

    var FabricCanvas = fabric.Canvas || fabric.StaticCanvas;
    var fabricCanvas = new FabricCanvas(canvasEl, options);
    fabricCanvas.contextContainer = nodeCanvas.getContext('2d');
    fabricCanvas.nodeCanvas = nodeCanvas;
    fabricCanvas.Font = Canvas.Font;

    return fabricCanvas;
  };

  /** @ignore */
  fabric.StaticCanvas.prototype.createPNGStream = function() {
    return this.nodeCanvas.createPNGStream();
  };

  fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {
    return this.nodeCanvas.createJPEGStream(opts);
  };

  var origSetWidth = fabric.StaticCanvas.prototype.setWidth;
  fabric.StaticCanvas.prototype.setWidth = function(width) {
    origSetWidth.call(this, width);
    this.nodeCanvas.width = width;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setWidth = fabric.StaticCanvas.prototype.setWidth;
  }

  var origSetHeight = fabric.StaticCanvas.prototype.setHeight;
  fabric.StaticCanvas.prototype.setHeight = function(height) {
    origSetHeight.call(this, height);
    this.nodeCanvas.height = height;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setHeight = fabric.StaticCanvas.prototype.setHeight;
  }

})();
<commit_msg>Options for node-canvas<commit_after>(function() {

  if (typeof document !== 'undefined' && typeof window !== 'undefined') {
    return;
  }

  var DOMParser = new require('xmldom').DOMParser,
      URL = require('url'),
      HTTP = require('http'),
      HTTPS = require('https'),

      Canvas = require('canvas'),
      Image = require('canvas').Image;

  /** @private */
  function request(url, encoding, callback) {
    var oURL = URL.parse(url);

    // detect if http or https is used
    if ( !oURL.port ) {
      oURL.port = ( oURL.protocol.indexOf('https:') === 0 ) ? 443 : 80;
    }

    // assign request handler based on protocol
    var reqHandler = ( oURL.port === 443 ) ? HTTPS : HTTP;

    var req = reqHandler.request({
      hostname: oURL.hostname,
      port: oURL.port,
      path: oURL.path,
      method: 'GET'
    }, function(response){
      var body = "";
      if (encoding) {
        response.setEncoding(encoding);
      }
      response.on('end', function () {
        callback(body);
      });
      response.on('data', function (chunk) {
        if (response.statusCode === 200) {
          body += chunk;
        }
      });
    });

    req.on('error', function(err) {
      if (err.errno === process.ECONNREFUSED) {
        fabric.log('ECONNREFUSED: connection refused to ' + oURL.hostname + ':' + oURL.port);
      }
      else {
        fabric.log(err.message);
      }
    });

    req.end();
  }

  /** @private */
  function request_fs(path, callback){
    var fs = require('fs');
    fs.readFile(path, function (err, data) {
      if (err) {
        fabric.log(err);
        throw err;
      } else {
        callback(data);
      }
    });
  }

  fabric.util.loadImage = function(url, callback, context) {
    var createImageAndCallBack = function(data){
      img.src = new Buffer(data, 'binary');
      // preserving original url, which seems to be lost in node-canvas
      img._src = url;
      callback && callback.call(context, img);
    };
    var img = new Image();
    if (url && (url instanceof Buffer || url.indexOf('data') === 0)) {
      img.src = img._src = url;
      callback && callback.call(context, img);
    }
    else if (url && url.indexOf('http') !== 0) {
      request_fs(url, createImageAndCallBack);
    }
    else if (url) {
      request(url, 'binary', createImageAndCallBack);
    }
    else {
      callback && callback.call(context, url);
    }
  };

  fabric.loadSVGFromURL = function(url, callback, reviver) {
    url = url.replace(/^\n\s*/, '').replace(/\?.*$/, '').trim();
    if (url.indexOf('http') !== 0) {
      request_fs(url, function(body) {
        fabric.loadSVGFromString(body.toString(), callback, reviver);
      });
    }
    else {
      request(url, '', function(body) {
        fabric.loadSVGFromString(body, callback, reviver);
      });
    }
  };

  fabric.loadSVGFromString = function(string, callback, reviver) {
    var doc = new DOMParser().parseFromString(string);
    fabric.parseSVGDocument(doc.documentElement, function(results, options) {
      callback && callback(results, options);
    }, reviver);
  };

  fabric.util.getScript = function(url, callback) {
    request(url, '', function(body) {
      eval(body);
      callback && callback();
    });
  };

  fabric.Image.fromObject = function(object, callback) {
    fabric.util.loadImage(object.src, function(img) {
      var oImg = new fabric.Image(img);

      oImg._initConfig(object);
      oImg._initFilters(object, function(filters) {
        oImg.filters = filters || [ ];
        callback && callback(oImg);
      });
    });
  };

  /**
   * Only available when running fabric on node.js
   * @param width Canvas width
   * @param height Canvas height
   * @param {Object} options to pass to FabricCanvas.
   * @param {Object} options to pass to NodeCanvas.
   * @return {Object} wrapped canvas instance
   */
  fabric.createCanvasForNode = function(width, height, options, nodeCanvasOptions) {
    nodeCanvasOptions = nodeCanvasOptions || options;

    var canvasEl = fabric.document.createElement('canvas'),
        nodeCanvas = new Canvas(width || 600, height || 600, nodeCanvasOptions);

    // jsdom doesn't create style on canvas element, so here be temp. workaround
    canvasEl.style = { };

    canvasEl.width = nodeCanvas.width;
    canvasEl.height = nodeCanvas.height;

    var FabricCanvas = fabric.Canvas || fabric.StaticCanvas;
    var fabricCanvas = new FabricCanvas(canvasEl, options);
    fabricCanvas.contextContainer = nodeCanvas.getContext('2d');
    fabricCanvas.nodeCanvas = nodeCanvas;
    fabricCanvas.Font = Canvas.Font;

    return fabricCanvas;
  };

  /** @ignore */
  fabric.StaticCanvas.prototype.createPNGStream = function() {
    return this.nodeCanvas.createPNGStream();
  };

  fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {
    return this.nodeCanvas.createJPEGStream(opts);
  };

  var origSetWidth = fabric.StaticCanvas.prototype.setWidth;
  fabric.StaticCanvas.prototype.setWidth = function(width) {
    origSetWidth.call(this, width);
    this.nodeCanvas.width = width;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setWidth = fabric.StaticCanvas.prototype.setWidth;
  }

  var origSetHeight = fabric.StaticCanvas.prototype.setHeight;
  fabric.StaticCanvas.prototype.setHeight = function(height) {
    origSetHeight.call(this, height);
    this.nodeCanvas.height = height;
    return this;
  };
  if (fabric.Canvas) {
    fabric.Canvas.prototype.setHeight = fabric.StaticCanvas.prototype.setHeight;
  }

})();
<|endoftext|>


<commit_before>'use strict'

const NR = require('node-resque')

module.exports = {
  startPriority: 200,
  stopPriority: 100,
  loadPriority: 600,
  initialize: function (api, next) {
    const resqueOverrides = api.config.tasks.resque_overrides

    api.resque = {
      verbose: false,
      queue: null,
      multiWorker: null,
      scheduler: null,
      connectionDetails: {redis: api.redis.clients.tasks},

      startQueue: function (callback) {
        let Queue = NR.queue
        if (resqueOverrides && resqueOverrides.queue) { Queue = resqueOverrides.queue }
        this.queue = new Queue({connection: this.connectionDetails}, api.tasks.jobs)

        this.queue.on('error', (error) => {
          api.log(error, 'error', '[api.resque.queue]')
        })

        this.queue.connect(callback)
      },

      stopQueue: function (callback) {
        if (api.resque.queue) { api.resque.queue.end(callback) } else { callback() }
      },

      startScheduler: function (callback) {
        let Scheduler = NR.scheduler
        if (resqueOverrides && resqueOverrides.scheduler) { Scheduler = resqueOverrides.scheduler }
        if (api.config.tasks.scheduler === true) {
          this.schedulerLogging = api.config.tasks.schedulerLogging
          this.scheduler = new Scheduler({connection: this.connectionDetails, timeout: api.config.tasks.timeout})

          this.scheduler.on('error', (error) => {
            api.log(error, 'error', '[api.resque.scheduler]')
          })

          this.scheduler.connect(() => {
            this.scheduler.on('start', () => { api.log('resque scheduler started', this.schedulerLogging.start) })
            this.scheduler.on('end', () => { api.log('resque scheduler ended', this.schedulerLogging.end) })
            this.scheduler.on('poll', () => { api.log('resque scheduler polling', this.schedulerLogging.poll) })
            this.scheduler.on('working_timestamp', (timestamp) => { api.log(`resque scheduler working timestamp ${timestamp}`, this.schedulerLogging.working_timestamp) })
            this.scheduler.on('transferred_job', (timestamp, job) => { api.log(`resque scheduler enqueuing job ${timestamp}`, this.schedulerLogging.transferred_job, job) })
            this.scheduler.on('master', (state) => { api.log('This node is now the Resque scheduler master') })

            this.scheduler.start()
            callback()
          })
        } else {
          callback()
        }
      },

      stopScheduler: function (callback) {
        if (!this.scheduler) {
          callback()
        } else {
          this.scheduler.end(() => {
            delete this.scheduler
            callback()
          })
        }
      },

      startMultiWorker: function (callback) {
        let MultiWorker = NR.multiWorker
        if (resqueOverrides && resqueOverrides.multiWorker) { MultiWorker = resqueOverrides.multiWorker }
        this.workerLogging = api.config.tasks.workerLogging
        this.schedulerLogging = api.config.tasks.schedulerLogging

        this.multiWorker = new MultiWorker({
          connection: api.resque.connectionDetails,
          queues: api.config.tasks.queues,
          timeout: api.config.tasks.timeout,
          checkTimeout: api.config.tasks.checkTimeout,
          minTaskProcessors: api.config.tasks.minTaskProcessors,
          maxTaskProcessors: api.config.tasks.maxTaskProcessors,
          maxEventLoopDelay: api.config.tasks.maxEventLoopDelay,
          toDisconnectProcessors: api.config.tasks.toDisconnectProcessors
        }, api.tasks.jobs)

        // normal worker emitters
        this.multiWorker.on('start', (workerId) => { api.log('worker: started', this.workerLogging.start, {workerId: workerId}) })
        this.multiWorker.on('end', (workerId) => { api.log('worker: ended', this.workerLogging.end, {workerId: workerId}) })
        this.multiWorker.on('cleaning_worker', (workerId, worker, pid) => { api.log(`worker: cleaning old worker ${worker}, (${pid})`, this.workerLogging.cleaning_worker) })
        this.multiWorker.on('poll', (workerId, queue) => { api.log(`worker: polling ${queue}`, this.workerLogging.poll, {workerId: workerId}) })
        this.multiWorker.on('job', (workerId, queue, job) => { api.log(`worker: working job ${queue}`, this.workerLogging.job, {workerId: workerId, job: {class: job['class'], queue: job.queue}}) })
        this.multiWorker.on('reEnqueue', (workerId, queue, job, plugin) => { api.log('worker: reEnqueue job', this.workerLogging.reEnqueue, {workerId: workerId, plugin: plugin, job: {class: job['class'], queue: job.queue}}) })
        this.multiWorker.on('success', (workerId, queue, job, result) => { api.log(`worker: job success ${queue}`, this.workerLogging.success, {workerId: workerId, job: {class: job['class'], queue: job.queue}, result: result}) })
        this.multiWorker.on('pause', (workerId) => { api.log('worker: paused', this.workerLogging.pause, {workerId: workerId}) })

        this.multiWorker.on('failure', (workerId, queue, job, failure) => { api.exceptionHandlers.task(failure, queue, job, workerId) })
        this.multiWorker.on('error', (workerId, queue, job, error) => { api.exceptionHandlers.task(error, queue, job, workerId) })

        // multiWorker emitters
        this.multiWorker.on('internalError', (error) => { api.log(error, this.workerLogging.internalError) })
        this.multiWorker.on('multiWorkerAction', (verb, delay) => { api.log(`*** checked for worker status: ${verb} (event loop delay: ${delay}ms)`, this.workerLogging.multiWorkerAction) })

        if (api.config.tasks.minTaskProcessors > 0) {
          this.multiWorker.start(() => {
            if (typeof callback === 'function') { callback() }
          })
        } else {
          if (typeof callback === 'function') { callback() }
        }
      },

      stopMultiWorker: function (callback) {
        if (this.multiWorker && api.config.tasks.minTaskProcessors > 0) {
          this.multiWorker.stop(() => {
            api.log('task workers stopped')
            callback()
          })
        } else {
          callback()
        }
      }
    }

    next()
  },

  start: function (api, next) {
    if (api.config.tasks.minTaskProcessors === 0 && api.config.tasks.maxTaskProcessors > 0) {
      api.config.tasks.minTaskProcessors = 1
    }

    api.resque.startQueue(function () {
      api.resque.startScheduler(function () {
        api.resque.startMultiWorker(function () {
          next()
        })
      })
    })
  },

  stop: function (api, next) {
    api.resque.stopScheduler(function () {
      api.resque.stopMultiWorker(function () {
        api.resque.stopQueue(function () {
          next()
        })
      })
    })
  }
}
<commit_msg>update worker logging to [ worker ] to match [ action ]<commit_after>'use strict'

const NR = require('node-resque')

module.exports = {
  startPriority: 200,
  stopPriority: 100,
  loadPriority: 600,
  initialize: function (api, next) {
    const resqueOverrides = api.config.tasks.resque_overrides

    api.resque = {
      verbose: false,
      queue: null,
      multiWorker: null,
      scheduler: null,
      connectionDetails: {redis: api.redis.clients.tasks},

      startQueue: function (callback) {
        let Queue = NR.queue
        if (resqueOverrides && resqueOverrides.queue) { Queue = resqueOverrides.queue }
        this.queue = new Queue({connection: this.connectionDetails}, api.tasks.jobs)

        this.queue.on('error', (error) => {
          api.log(error, 'error', '[api.resque.queue]')
        })

        this.queue.connect(callback)
      },

      stopQueue: function (callback) {
        if (api.resque.queue) { api.resque.queue.end(callback) } else { callback() }
      },

      startScheduler: function (callback) {
        let Scheduler = NR.scheduler
        if (resqueOverrides && resqueOverrides.scheduler) { Scheduler = resqueOverrides.scheduler }
        if (api.config.tasks.scheduler === true) {
          this.schedulerLogging = api.config.tasks.schedulerLogging
          this.scheduler = new Scheduler({connection: this.connectionDetails, timeout: api.config.tasks.timeout})

          this.scheduler.on('error', (error) => {
            api.log(error, 'error', '[api.resque.scheduler]')
          })

          this.scheduler.connect(() => {
            this.scheduler.on('start', () => { api.log('resque scheduler started', this.schedulerLogging.start) })
            this.scheduler.on('end', () => { api.log('resque scheduler ended', this.schedulerLogging.end) })
            this.scheduler.on('poll', () => { api.log('resque scheduler polling', this.schedulerLogging.poll) })
            this.scheduler.on('working_timestamp', (timestamp) => { api.log(`resque scheduler working timestamp ${timestamp}`, this.schedulerLogging.working_timestamp) })
            this.scheduler.on('transferred_job', (timestamp, job) => { api.log(`resque scheduler enqueuing job ${timestamp}`, this.schedulerLogging.transferred_job, job) })
            this.scheduler.on('master', (state) => { api.log('This node is now the Resque scheduler master') })

            this.scheduler.start()
            callback()
          })
        } else {
          callback()
        }
      },

      stopScheduler: function (callback) {
        if (!this.scheduler) {
          callback()
        } else {
          this.scheduler.end(() => {
            delete this.scheduler
            callback()
          })
        }
      },

      startMultiWorker: function (callback) {
        let MultiWorker = NR.multiWorker
        if (resqueOverrides && resqueOverrides.multiWorker) { MultiWorker = resqueOverrides.multiWorker }
        this.workerLogging = api.config.tasks.workerLogging
        this.schedulerLogging = api.config.tasks.schedulerLogging

        this.multiWorker = new MultiWorker({
          connection: api.resque.connectionDetails,
          queues: api.config.tasks.queues,
          timeout: api.config.tasks.timeout,
          checkTimeout: api.config.tasks.checkTimeout,
          minTaskProcessors: api.config.tasks.minTaskProcessors,
          maxTaskProcessors: api.config.tasks.maxTaskProcessors,
          maxEventLoopDelay: api.config.tasks.maxEventLoopDelay,
          toDisconnectProcessors: api.config.tasks.toDisconnectProcessors
        }, api.tasks.jobs)

        // normal worker emitters
        this.multiWorker.on('start', (workerId) => { api.log('[ worker ] started', this.workerLogging.start, {workerId: workerId}) })
        this.multiWorker.on('end', (workerId) => { api.log('[ worker ] ended', this.workerLogging.end, {workerId: workerId}) })
        this.multiWorker.on('cleaning_worker', (workerId, worker, pid) => { api.log(`[ worker ] cleaning old worker ${worker}, (${pid})`, this.workerLogging.cleaning_worker) })
        this.multiWorker.on('poll', (workerId, queue) => { api.log(`[ worker ] polling ${queue}`, this.workerLogging.poll, {workerId: workerId}) })
        this.multiWorker.on('job', (workerId, queue, job) => { api.log(`[ worker ] working job ${queue}`, this.workerLogging.job, {workerId: workerId, job: {class: job['class'], queue: job.queue}}) })
        this.multiWorker.on('reEnqueue', (workerId, queue, job, plugin) => { api.log('[ worker ] reEnqueue job', this.workerLogging.reEnqueue, {workerId: workerId, plugin: plugin, job: {class: job['class'], queue: job.queue}}) })
        this.multiWorker.on('success', (workerId, queue, job, result) => { api.log(`[ worker ] job success ${queue}`, this.workerLogging.success, {workerId: workerId, job: {class: job['class'], queue: job.queue}, result: result}) })
        this.multiWorker.on('pause', (workerId) => { api.log('[ worker ] paused', this.workerLogging.pause, {workerId: workerId}) })

        this.multiWorker.on('failure', (workerId, queue, job, failure) => { api.exceptionHandlers.task(failure, queue, job, workerId) })
        this.multiWorker.on('error', (workerId, queue, job, error) => { api.exceptionHandlers.task(error, queue, job, workerId) })

        // multiWorker emitters
        this.multiWorker.on('internalError', (error) => { api.log(error, this.workerLogging.internalError) })
        this.multiWorker.on('multiWorkerAction', (verb, delay) => { api.log(`[ multiworker ] checked for worker status: ${verb} (event loop delay: ${delay}ms)`, this.workerLogging.multiWorkerAction) })

        if (api.config.tasks.minTaskProcessors > 0) {
          this.multiWorker.start(() => {
            if (typeof callback === 'function') { callback() }
          })
        } else {
          if (typeof callback === 'function') { callback() }
        }
      },

      stopMultiWorker: function (callback) {
        if (this.multiWorker && api.config.tasks.minTaskProcessors > 0) {
          this.multiWorker.stop(() => {
            api.log('task workers stopped')
            callback()
          })
        } else {
          callback()
        }
      }
    }

    next()
  },

  start: function (api, next) {
    if (api.config.tasks.minTaskProcessors === 0 && api.config.tasks.maxTaskProcessors > 0) {
      api.config.tasks.minTaskProcessors = 1
    }

    api.resque.startQueue(function () {
      api.resque.startScheduler(function () {
        api.resque.startMultiWorker(function () {
          next()
        })
      })
    })
  },

  stop: function (api, next) {
    api.resque.stopScheduler(function () {
      api.resque.stopMultiWorker(function () {
        api.resque.stopQueue(function () {
          next()
        })
      })
    })
  }
}
<|endoftext|>


<commit_before>var async = require('async');
var path = require('path');

// var isWin = /^win/.test(process.platform);
// var isMac = /^darwin/.test(process.platform);

module.exports.connect = function (config, logger, cb) {
	var pgOptions = {
		pgNative: true
	};

	var pgp = require('pg-promise')(pgOptions);
	var monitor = require('pg-monitor');

	monitor.attach(pgOptions, config.logEvents);
	monitor.setTheme('matrix');

	monitor.log = function(msg, info){
		logger.log(info.event, info.text);
		info.display = false;
	};

	config.user = config.user || process.env['USER'];

	var db = pgp(config);

	var files = ['schema.sql'];
	var post = [];

	async.eachSeries(files, function (file, cb) {
		var sql = new pgp.QueryFile(path.join('sql', file), { minify: true });

		db.query(sql).then(function (data) {
			cb(null, data);
		}).catch(function (err) {
			cb(err);
		});
	}, function (err) {
		if (err) {
			return cb(err);
		}

		var migration = {};

		var currentVersion = 0;

		var nextVersions = Object.keys(migration).sort().filter(function (ver) {
			return ver > currentVersion;
		});

		async.eachSeries(nextVersions, function (ver, cb) {
			async.eachSeries(migration[ver], function (command, cb) {
				db.query(command).then(function (data) {
					cb(null, data);
				}).catch(function (err) {
					cb(err);
				});
			}, function (err) {
				return cb(err);
			});
		}, function (err) {
			if (err) {
				return cb(err);
			}

			async.eachSeries(post, function (command, cb) {
				db.query(command).then(function (data) {
					cb(null, data);
				}).catch(function (err) {
					cb(err);
				});
			}, function (err) {
				cb(err, db);
			});
		});
	});
}
<commit_msg>Removing unused schema migration logic #69.<commit_after>var async = require('async');
var path = require('path');

// var isWin = /^win/.test(process.platform);
// var isMac = /^darwin/.test(process.platform);

module.exports.connect = function (config, logger, cb) {
	var pgOptions = {
		pgNative: true
	};

	var pgp = require('pg-promise')(pgOptions);
	var monitor = require('pg-monitor');

	monitor.attach(pgOptions, config.logEvents);
	monitor.setTheme('matrix');

	monitor.log = function(msg, info){
		logger.log(info.event, info.text);
		info.display = false;
	};

	config.user = config.user || process.env['USER'];

	var db = pgp(config);

	var files = ['schema.sql'];

	async.eachSeries(files, function (file, cb) {
		var sql = new pgp.QueryFile(path.join('sql', file), { minify: true });

		db.query(sql).then(function (data) {
			cb(null, data);
		}).catch(function (err) {
			cb(err);
		});
	}, function (err) {
		return cb(err, db);
	});
}
<|endoftext|>