<commit_before>(function () {
  'use strict';

  /*DELETE INPUT MODALS CONTROLLER */
  angular
    .module('webApp')
    .controller('NewOperatorModalCtrl', NewOperatorModalCtrl);

  NewOperatorModalCtrl.$inject = ['$modalInstance', 'operatorName', 'operatorType', 'operators','PolicyStaticDataFactory','CubeStaticDataFactory', 'UtilsService'];

  function NewOperatorModalCtrl($modalInstance, operatorName, operatorType, operators,PolicyStaticDataFactory,CubeStaticDataFactory, UtilsService) {
    /*jshint validthis: true*/
    var vm = this;

    vm.ok = ok;
    vm.cancel = cancel;

    init();

    function init(){
      vm.operator = {};
      vm.operator.name = operatorName;
      vm.operator.configuration = "";
      vm.operator.type = operatorType;
      vm.configHelpLink = PolicyStaticDataFactory.getConfigurationHelpLink();
      vm.configPlaceholder = PolicyStaticDataFactory.getConfigPlaceholder();
      vm.operator.configuration = CubeStaticDataFactory.getDefaultOperatorConfiguration();
      vm.error = false;
      vm.errorText = "";
    }

    ///////////////////////////////////////

    function isValidConfiguration() {
      var configuration = vm.operator.configuration;
      try {
        vm.operator.configuration = JSON.parse(configuration);
        return true;
      } catch (e) {
        vm.errorText = "_POLICY_._CUBE_._INVALID_CONFIG_";
        vm.operator.configuration = configuration;
        return false;
      }
    }

    function isRepeated() {
      var position = UtilsService.findElementInJSONArray(operators, vm.operator, "name");
      var repeated = position != -1;
      if (repeated) {
        vm.errorText = "_POLICY_._CUBE_._OPERATOR_NAME_EXISTS_";
      }
      return repeated;
    }

    function ok() {
      vm.errorText = "";
      if (vm.form.$valid && !isRepeated() && isValidConfiguration()) {
        $modalInstance.close(vm.operator);
      }
    };

    function cancel() {
      $modalInstance.dismiss('cancel');
    };
  };

})();
<commit_msg>fix(cubes): bug #1030 fixed<commit_after>(function () {
  'use strict';

  /*DELETE INPUT MODALS CONTROLLER */
  angular
    .module('webApp')
    .controller('NewOperatorModalCtrl', NewOperatorModalCtrl);

  NewOperatorModalCtrl.$inject = ['$modalInstance', 'operatorName', 'operatorType', 'operators','PolicyStaticDataFactory','CubeStaticDataFactory', 'UtilsService'];

  function NewOperatorModalCtrl($modalInstance, operatorName, operatorType, operators,PolicyStaticDataFactory,CubeStaticDataFactory, UtilsService) {
    /*jshint validthis: true*/
    var vm = this;

    vm.ok = ok;
    vm.cancel = cancel;

    init();

    function init(){
      vm.operator = {};
      vm.operator.name = operatorName;
      vm.operator.configuration = "";
      vm.operator.type = operatorType;
      vm.configHelpLink = PolicyStaticDataFactory.getConfigurationHelpLink();
      vm.configPlaceholder = PolicyStaticDataFactory.getConfigPlaceholder();
      vm.error = false;
      vm.errorText = "";
      setDefaultConfiguration();
    }

    ///////////////////////////////////////

    function isValidConfiguration() {
      var configuration = vm.operator.configuration;
      try {
        vm.operator.configuration = JSON.parse(configuration);
        return true;
      } catch (e) {
        vm.errorText = "_POLICY_._CUBE_._INVALID_CONFIG_";
        vm.operator.configuration = configuration;
        return false;
      }
    }

    function isRepeated() {
      var position = UtilsService.findElementInJSONArray(operators, vm.operator, "name");
      var repeated = position != -1;
      if (repeated) {
        vm.errorText = "_POLICY_._CUBE_._OPERATOR_NAME_EXISTS_";
      }
      return repeated;
    }

    function setDefaultConfiguration(){
      var defaultConfiguration = '{}';
      var countType = CubeStaticDataFactory.getFunctionNames()[2];
      if (vm.operator.type !== countType){
        defaultConfiguration= CubeStaticDataFactory.getDefaultOperatorConfiguration();
      }
      vm.operator.configuration = defaultConfiguration;
    }

    function ok() {
      vm.errorText = "";
      if (vm.form.$valid && !isRepeated() && isValidConfiguration()) {
        $modalInstance.close(vm.operator);
      }
    };

    function cancel() {
      $modalInstance.dismiss('cancel');
    };
  };

})();
<|endoftext|>


<commit_before>(function () {
    "use strict";

    var express, corser, mongo, app;

    express = require("express");
    corser = require("corser");
    mongo = require("mongodb");

    app = express();

 // Handle CORS
    app.use(corser.create({
        methods: corser.simpleMethods.concat(["DELETE"]),
        requestHeaders: corser.simpleRequestHeaders.concat(["Authorization"])
    }));
    app.use(function (req, res, next) {
        if (req.method === "OPTIONS") {
            res.writeHead(204);
            res.end();
        } else {
            next();
        }
    });

 // Basic auth.
    app.use(function (req, res, next) {
        (express.basicAuth(function (username, password, callback) {
            var client;
            client = new mongo.Db("test", new mongo.Server("127.0.0.1", 27017), {w: "majority"});
            client.open(function (err, db) {
                db.authenticate(username, password, function (err) {
                    if (err !== null) {
                     // Close database if authentication fails
                        db.close();
                        callback(err, null);
                    } else {
                     // Store reference to database in req.db
                        req.db = db;
                        callback(null, username);
                    }
                });
            });
        }, "MongoDB"))(req, res, next);
    });

 // Parse JSON.
    app.use(express.json());

    app.get("/:collection/:item", function (req, res, next) {
        var collectionParam, itemParam;
        collectionParam = req.params.collection;
        itemParam = req.params.item;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(itemParam);
                collection.findOne({
                    _id: id
                }, function (err, item) {
                    res.send(item);
                    req.db.close();
                });
            } catch (e) {
                next(e);
            }
        });
    });

    app.post("/:collection", function (req, res) {
        var collectionParam, payload;
        collectionParam = req.params.collection;
        payload = req.body;
        req.db.collection(collectionParam, function (err, collection) {
            collection.insert(payload, function () {
                res.send(201, "Created");
                req.db.close();
            });
        });
    });

    app.delete("/:collection/:item", function (req, res, next) {
        var collectionParam, itemParam;
        collectionParam = req.params.collection;
        itemParam = req.params.item;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(itemParam);
                collection.remove({
                    _id: new mongo.ObjectID(itemParam)
                }, function () {
                    res.send(200, "Deleted");
                    req.db.close();
                });
            } catch (e) {
                next(e);
            }
        });
    });

    app.use(function(err, req, res, next){
        res.send(500, "Something broke!");
    });

    app.listen(1337);

}());
<commit_msg>Close db in case of error.<commit_after>(function () {
    "use strict";

    var express, corser, mongo, app;

    express = require("express");
    corser = require("corser");
    mongo = require("mongodb");

    app = express();

 // Handle CORS
    app.use(corser.create({
        methods: corser.simpleMethods.concat(["DELETE"]),
        requestHeaders: corser.simpleRequestHeaders.concat(["Authorization"])
    }));
    app.use(function (req, res, next) {
        if (req.method === "OPTIONS") {
            res.writeHead(204);
            res.end();
        } else {
            next();
        }
    });

 // Basic auth.
    app.use(function (req, res, next) {
        (express.basicAuth(function (username, password, callback) {
            var client;
            client = new mongo.Db("test", new mongo.Server("127.0.0.1", 27017), {w: "majority"});
            client.open(function (err, db) {
                db.authenticate(username, password, function (err) {
                    if (err !== null) {
                     // Close database if authentication fails
                        db.close();
                        callback(err, null);
                    } else {
                     // Store reference to database in req.db
                        req.db = db;
                        callback(null, username);
                    }
                });
            });
        }, "MongoDB"))(req, res, next);
    });

 // Parse JSON.
    app.use(express.json());

    app.get("/:collection/:item", function (req, res, next) {
        var collectionParam, itemParam;
        collectionParam = req.params.collection;
        itemParam = req.params.item;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(itemParam);
                collection.findOne({
                    _id: id
                }, function (err, item) {
                    res.send(item);
                    req.db.close();
                });
            } catch (e) {
                next(e);
            }
        });
    });

    app.post("/:collection", function (req, res) {
        var collectionParam, payload;
        collectionParam = req.params.collection;
        payload = req.body;
        req.db.collection(collectionParam, function (err, collection) {
            collection.insert(payload, function () {
                res.send(201, "Created");
                req.db.close();
            });
        });
    });

    app.delete("/:collection/:item", function (req, res, next) {
        var collectionParam, itemParam;
        collectionParam = req.params.collection;
        itemParam = req.params.item;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            try {
                id = new mongo.ObjectID(itemParam);
                collection.remove({
                    _id: new mongo.ObjectID(itemParam)
                }, function () {
                    res.send(200, "Deleted");
                    req.db.close();
                });
            } catch (e) {
                next(e);
            }
        });
    });

    app.use(function(err, req, res, next){
        req.db.close();
        res.send(500, "Something broke!");
    });

    app.listen(1337);

}());
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.leng<commit_msg>Quick fix<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.lengt<|endoftext|>


<commit_before>'use strict';

const request = require('request');
const qs = require('qs');
const fs = require('fs');
const _ = {
  merge: require('lodash.merge'),
  forEach: require('lodash.foreach')
};

var config = require('./config.default');

if (fs.existsSync('./config.override.js')) {
  var configOverrides = require('./config.override');
  config = _.merge(config, configOverrides);
}

module.exports.findCard = (event, context, callback) => {

  var params = qs.parse(event.body);
  var text = params['text'];
  var token = params['token'];

  if (token != config.app.token) {
    callback(null, {
      statusCode: 403,
      body: JSON.stringify({
        'error': 'Forbidden.'
      })
    });
    return;
  }

  request.get({
    url: 'https://api.deckbrew.com/mtg/cards?name=' + text,
    json: true,
    }, (err, res, data) => {

    if(data.length == 0) {
      callback(null, {
        statusCode: 200,
        body: JSON.stringify({
          'text': 'No matching card found.',
          'response_type': 'in_channel',
          'attachments': []
        })
      });
      return;
    }

    var name = data[0]['name'];
    var cardtext = data[0]['text'];
    var imageurl = data[0]['editions'][0]['image_url'];
    var types = data[0]['types'][0];
    var cost = data[0]['cost'];

    _.forEach(config.replacements, (item) => {
      cardtext = cardtext.replace(item.pattern, item.replacement);
      cost = cost.replace(item.pattern, item.replacement);
    });

    var response = {
         'text': name,
         'response_type': 'in_channel',
          'attachments': [{
            'text': cardtext,
            'fields': [
              {
                  'title': 'Types',
                  'value': types,
                  'short': true
              },
              {
                  'title': 'Cost',
                  'value': cost,
                  'short': true
              },
          ],
          'image_url': imageurl
        }]
    };

    callback(null, {
      statusCode: 200,
      body: JSON.stringify(response)
    });
});

};
<commit_msg>changed MTG API<commit_after>'use strict';

const request = require('request');
const qs = require('qs');
const fs = require('fs');
const _ = {
  merge: require('lodash.merge'),
  forEach: require('lodash.foreach')
};

var config = require('./config.default');

if (fs.existsSync('./config.override.js')) {
  var configOverrides = require('./config.override');
  config = _.merge(config, configOverrides);
}

module.exports.findCard = (event, context, callback) => {

  var params = qs.parse(event.body);
  var text = params['text'];
  var token = params['token'];

  if (token != config.app.token) {
    callback(null, {
      statusCode: 403,
      body: JSON.stringify({
        'error': 'Forbidden.'
      })
    });
    return;
  }

  request.get({
    url: 'https://api.magicthegathering.io/v1/cards?name=' + text,
    json: true,
    }, (err, res, data) => {

    if(data.cards.length == 0) {
      callback(null, {
        statusCode: 200,
        body: JSON.stringify({
          'text': 'No matching card found.',
          'response_type': 'in_channel',
          'attachments': []
        })
      });
      return;
    }

    var name = data.cards[0]['name'];
    var cardtext = data.cards[0]['text'];
    var imageurl = data.cards[0]['imageUrl'];
    var types = data.cards[0]['types'][0];
    var cost = data.cards[0]['manaCost'];

    _.forEach(config.replacements, (item) => {
      cardtext = cardtext.replace(item.pattern, item.replacement);
      cost = cost.replace(item.pattern, item.replacement);
    });

    var response = {
         'text': name,
         'response_type': 'in_channel',
          'attachments': [{
            'text': cardtext,
            'fields': [
              {
                  'title': 'Types',
                  'value': types,
                  'short': true
              },
              {
                  'title': 'Cost',
                  'value': cost,
                  'short': true
              },
          ],
          'image_url': imageurl
        }]
    };

    callback(null, {
      statusCode: 200,
      body: JSON.stringify(response)
    });
});

};
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep =<commit_msg>Fixing a typo added in the last readme update<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = <|endoftext|>


<commit_before>'use strict';

const spawn = require('child_process').spawn;
const config = require('./config');

function Gallery() {
    var _gallery = this;

    var configuration = require('./config');
    var fs = require('fs');
    var path = require('path');
    var fullRoot = path.resolve(configuration.galleryRoot);
    const convert = require('./image-convert');

    _gallery.isInRoot = function(candidate) {
        candidate = path.resolve(candidate);

        return candidate.indexOf(fullRoot) === 0;
    }

    _gallery.buildThumbPath = function(relative) {
        var extension = path.extname(relative);
        var fileName = path.basename(relative, extension);

        const thumbPath = path.join(path.dirname(relative), configuration.thumbsDir, extension.replace('.', ''), fileName + ".jpg");
        convert.checkOrCreateThumbnail(relative, thumbPath);

        return thumbPath;
    }

    _gallery.buildList = function(dir, files) {
        var ret = [];
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var fullPath = path.join(dir, file);

            var relative = fullPath.substring(configuration.galleryRoot.length-1);

            var type;
            let scaledRelative = relative;
            switch (path.extname(file).replace('.', '')) {
                case 'webm':
                case 'mp4':
                case 'gif':
                case 'avi':
                    type = 'video';
                    break;
                default:
                    type = 'image';
                    scaledRelative = convert.getRelativeImagePath(relative);
                    break;
            }

            ret.push({
                        name: path.join(configuration.galleryEntryPoint, path.join(scaledRelative)),
                        thumb: path.join(configuration.galleryEntryPoint, _gallery.buildThumbPath(relative)),
                        type: type
            });
        }

        return ret;
    }

    _gallery.buildDirectoriesList = function(dir) {
        var ret = [];
        var files = fs.readdirSync(dir).filter(function(file) {
                return fs.statSync(path.join(dir, file)).isDirectory() && file != configuration.thumbsDir &&
                    file != 'scaled' && file != 'no-scaled';
            });

        for (var i = 0; i < files.length; i++) {
            var relative = path.join(dir, files[i]).substring(configuration.galleryRoot.length-1);
            ret.push({
                path: path.join(relative).replace('/', '%2F'),
                name: path.join(relative)
            });

            ret = ret.concat(_gallery.buildDirectoriesList(path.join(dir, files[i])));
        }

        return ret;
    }

    return {
        list: function(req, res) {
            var requestedDirectory = req.params.directory || '';
            var basedir = path.join(configuration.galleryRoot, requestedDirectory);

            if (!_gallery.isInRoot(basedir)) {
                res.sendStatus(403);
                return;
            }

            var files = fs.readdirSync(basedir).filter(function(file) {
                return !fs.statSync(path.join(basedir, file)).isDirectory();
            });

            res.json(_gallery.buildList(basedir, files));
        },

        listDirectories: function(req, res) {
            res.json(_gallery.buildDirectoriesList(configuration.galleryRoot));
        },

        shutdown: function(req, res) {
            if (config.shutdownEnabled) {
                const stopChrome = spawn('killall', ['chromium-browser']);
                stopChrome.on('close', () => spawn('sudo', ['shutdown', '-h', 'now']));
                res.end('shutdown initiated');
            } else {
                console.log('shutdown rejected due to configuration');
                res.end('shutdown rejected');
            }
        }
    }
}

module.exports = Gallery;<commit_msg>add a delay before shutdown<commit_after>'use strict';

const spawn = require('child_process').spawn;
const config = require('./config');

function Gallery() {
    var _gallery = this;

    var configuration = require('./config');
    var fs = require('fs');
    var path = require('path');
    var fullRoot = path.resolve(configuration.galleryRoot);
    const convert = require('./image-convert');

    _gallery.isInRoot = function(candidate) {
        candidate = path.resolve(candidate);

        return candidate.indexOf(fullRoot) === 0;
    }

    _gallery.buildThumbPath = function(relative) {
        var extension = path.extname(relative);
        var fileName = path.basename(relative, extension);

        const thumbPath = path.join(path.dirname(relative), configuration.thumbsDir, extension.replace('.', ''), fileName + ".jpg");
        convert.checkOrCreateThumbnail(relative, thumbPath);

        return thumbPath;
    }

    _gallery.buildList = function(dir, files) {
        var ret = [];
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var fullPath = path.join(dir, file);

            var relative = fullPath.substring(configuration.galleryRoot.length-1);

            var type;
            let scaledRelative = relative;
            switch (path.extname(file).replace('.', '')) {
                case 'webm':
                case 'mp4':
                case 'gif':
                case 'avi':
                    type = 'video';
                    break;
                default:
                    type = 'image';
                    scaledRelative = convert.getRelativeImagePath(relative);
                    break;
            }

            ret.push({
                        name: path.join(configuration.galleryEntryPoint, path.join(scaledRelative)),
                        thumb: path.join(configuration.galleryEntryPoint, _gallery.buildThumbPath(relative)),
                        type: type
            });
        }

        return ret;
    }

    _gallery.buildDirectoriesList = function(dir) {
        var ret = [];
        var files = fs.readdirSync(dir).filter(function(file) {
                return fs.statSync(path.join(dir, file)).isDirectory() && file != configuration.thumbsDir &&
                    file != 'scaled' && file != 'no-scaled';
            });

        for (var i = 0; i < files.length; i++) {
            var relative = path.join(dir, files[i]).substring(configuration.galleryRoot.length-1);
            ret.push({
                path: path.join(relative).replace('/', '%2F'),
                name: path.join(relative)
            });

            ret = ret.concat(_gallery.buildDirectoriesList(path.join(dir, files[i])));
        }

        return ret;
    }

    function shutdownDelayed() {
        setTimeout(() => spawn('sudo', ['shutdown', '-h', 'now']), 1000);
    }

    return {
        list: function(req, res) {
            var requestedDirectory = req.params.directory || '';
            var basedir = path.join(configuration.galleryRoot, requestedDirectory);

            if (!_gallery.isInRoot(basedir)) {
                res.sendStatus(403);
                return;
            }

            var files = fs.readdirSync(basedir).filter(function(file) {
                return !fs.statSync(path.join(basedir, file)).isDirectory();
            });

            res.json(_gallery.buildList(basedir, files));
        },

        listDirectories: function(req, res) {
            res.json(_gallery.buildDirectoriesList(configuration.galleryRoot));
        },

        shutdown: function(req, res) {
            if (config.shutdownEnabled) {
                const stopChrome = spawn('killall', ['chromium-browser']);
                stopChrome.on('close', shutdownDelayed);
                res.end('shutdown initiated');
            } else {
                console.log('shutdown rejected due to configuration');
                res.end('shutdown rejected');
            }
        }
    }
}

module.exports = Gallery;<|endoftext|>


<commit_before>
/**
 * Module : Kero percent
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-10 10:33:09
 */

import {
    getJSObject
} from 'tinper-sparrow/src/util';
import {
    makeDOM
} from 'tinper-sparrow/src/dom';
import {
    on,
    off,
    stopEvent
} from 'tinper-sparrow/src/event';
import {
    Radio
} from 'tinper-neoui/src/neoui-radio';
import {
    addClass,
    removeClass
} from 'tinper-sparrow/src/dom';
import {
    env
} from 'tinper-sparrow/src/env';

var RadioAdapter = u.BaseAdapter.extend({
    init: function() {
        var self = this;
        this.dynamic = false;
        this.otherValue = this.options['otherValue'] || '其他';
        if (this.options['datasource'] || this.options['hasOther']) {
            // 存在datasource或者有其他选项，将当前dom元素保存，以后用于复制新的dom元素
            if (env.isIE) {
                this.radioTemplateHTML = this.element.innerHTML;
            } else {
                this.radioTemplateArray = [];
                for (var i = 0, count = this.element.childNodes.length; i < count; i++) {
                    this.radioTemplateArray.push(this.element.childNodes[i]);
                }
            }

        }
        if (this.options['datasource']) {
            this.dynamic = true;
            this.datasource = getJSObject(this.viewModel, this.options['datasource']);
            if (this.datasource)
                this.setComboData(this.datasource);
        } else {
            this.comp = new Radio(this.element);
            this.element['u.Radio'] = this.comp;
            this.eleValue = this.comp._btnElement.value;

            this.comp.on('change', function(event) {
                if (self.slice) return;
                var modelValue = self.dataModel.getValue(self.field);
                //var valueArr = modelValue == '' ?  [] : modelValue.split(',');
                if (self.comp._btnElement.checked) {
                    self.dataModel.setValue(self.field, self.eleValue);
                }
            });
        }

        // 如果存在其他
        if (this.options['hasOther']) {
            var node = null;
            if (env.isIE) {
                var nowHtml = this.element.innerHTML;
                this.element.innerHTML = nowHtml + this.radioTemplateHTML;
            } else {
                for (var j = 0; j < this.radioTemplateArray.length; j++) {
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
            }

            var LabelS = this.element.querySelectorAll('.u-radio');
            self.lastLabel = LabelS[LabelS.length - 1];
            var allRadioS = this.element.querySelectorAll('[type=radio]');
            self.lastRadio = allRadioS[allRadioS.length - 1];
            var nameDivs = this.element.querySelectorAll('.u-radio-label');
            self.lastNameDiv = nameDivs[nameDivs.length - 1];
            self.lastNameDiv.innerHTML = '其他';
            self.otherInput = makeDOM('<input type="text" disabled style="vertical-align: middle;line-height: normal;width: 80%">');
            self.lastNameDiv.parentNode.appendChild(self.otherInput);
            self.lastRadio.value = '';

            var comp;
            if (self.lastLabel['u.Radio']) {
                comp = self.lastLabel['u.Radio'];
            } else {
                comp = new Radio(self.lastLabel);
            }
            self.lastLabel['u.Radio'] = comp;
            self.otherComp = comp;
            comp.on('change', function() {
                if (comp._btnElement.checked) {
                    if (self.otherInput.value) {
                        self.dataModel.setValue(self.field, self.otherInput.value);
                    } else {
                        self.dataModel.setValue(self.field, self.otherValue);
                    }
                    // 选中后可编辑
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele) {
                        ele.removeAttribute('disabled');
                    });
                } else {
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele) {
                        ele.setAttribute('disabled', true);
                    });
                }
            });

            on(self.otherInput, 'blur', function(e) {
                self.otherComp.trigger('change');
            })
            on(self.otherInput, 'click', function(e) {
                stopEvent(e);
            })
        }

        this.dataModel.ref(this.field).subscribe(function(value) {
            self.modelValueChange(value)
        })

    },
    setComboData: function(comboData) {

        var self = this;
        this.datasource = comboData;
        this.element.innerHTML = '';
        if (env.isIE) {
            var htmlStr = ''
            for (var i = 0, len = comboData.length; i < len; i++) {
                htmlStr　 += this.radioTemplateHTML;
            }
            this.element.innerHTML = htmlStr;
        } else {
            for (var i = 0, len = comboData.length; i < len; i++) {
                for (var j = 0; j < this.radioTemplateArray.length; j++) {
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
                //this.radioTemplate.clone().appendTo(this.element)
            }
        }

        var allRadio = this.element.querySelectorAll('[type=radio]');
        var allName = this.element.querySelectorAll('.u-radio-label');
        for (var k = 0; k < allRadio.length; k++) {
            allRadio[k].value = comboData[k].pk || comboData[k].value;
            allName[k].innerHTML = comboData[k].name
        }

        this.radioInputName = '';
        if (allRadio.length > 0) {
            this.radioInputName = allRadio[0].name;
        }

        this.element.querySelectorAll('.u-radio').forEach(function(ele) {
            var comp = new Radio(ele);
            ele['u.Radio'] = comp;

            comp.on('change', function(event) {
                if (comp._btnElement.checked) {
                    self.dataModel.setValue(self.field, comp._btnElement.value);
                }
                // 其他元素input输入框不能进行编辑
                var allChild = comp.element.parentNode.children;
                var siblingAry = [];
                for (var i = 0; i < allChild.length; i++) {
                    if (allChild[i] == comp.element) {

                    } else {
                        siblingAry.push(allChild[i])
                    }
                }
                siblingAry.forEach(function(children) {
                    var childinput = children.querySelectorAll('input[type="text"]')
                    if (childinput) {
                        childinput.forEach(function(inputele) {
                            inputele.setAttribute('disabled', 'true')
                        });
                    }
                });
            });
        })
    },

    modelValueChange: function(value) {
        if (this.slice) return;
        var fetch = false,self = this;
        if (this.dynamic) {
            if (this.datasource) {
                this.showValue = '';
                this.trueValue = value;
                this.element.querySelectorAll('.u-radio').forEach(function(ele) {
                    var comp = ele['u.Radio'];
                    if (comp) {
                        var inptuValue = comp._btnElement.value;
                        //解决boolean类型的true和false与"true"和"false"比较
                        if (inptuValue && inptuValue == value.toString()) {
                            fetch = true;
                            addClass(comp.element, 'is-checked')
                            comp._btnElement.click();
                            var nameSpan = ele.querySelector('.u-radio-label');
                            var showValue = $(nameSpan).text();
                            if (showValue) {
                                self.showValue = showValue;
                            }
                        } else {
                            removeClass(comp.element, 'is-checked')
                        }
                    }
                })
            }
        } else {
            if (this.eleValue == value) {
                fetch = true;
                this.slice = true;
                addClass(this.comp.element, 'is-checked')
                //this.comp._btnElement.click(); // https://github.com/iuap-design/tinper.org/issues/41
                this.slice = false;
            }
        }
        if (this.options.hasOther && !fetch && value) {
            this.showValue = value;
            if (!this.enable) {
                this.lastRadio.removeAttribute('disabled');
            }
            u.addClass(this.lastLabel, 'is-checked')
            this.lastRadio.checked = true;
            if (value != this.otherValue) {
                this.otherInput.value = value;
            }
            this.lastRadio.removeAttribute('disabled');
            this.otherInput.removeAttribute('disabled');
            if (!this.enable) {
                this.lastRadio.setAttribute('disabled', true);
            }
        }
    },

    setEnable: function(enable) {
        this.enable = (enable === true || enable === 'true');
        if (this.dynamic) {
            if (this.datasource) {
                if (this.otherInput && !this.enable) {
                    this.otherInput.setAttribute('disabled', true);
                }
                this.element.querySelectorAll('.u-radio').forEach(function(ele) {
                    var comp = ele['u.Radio'];
                    if (comp) {
                        if (enable === true || enable === 'true') {
                            comp.enable();
                        } else {
                            comp.disable();
                        }
                    }
                })
            }
        } else {
            if (this.enable) {
                this.comp.enable();
            } else {
                this.comp.disable();
            }
        }
    }
})

if (u.compMgr)
    u.compMgr.addDataAdapter({
        adapter: RadioAdapter,
        name: 'u-radio'
    });
export {
    RadioAdapter
};
<commit_msg>优化代码逻辑，判断null<commit_after>
/**
 * Module : Kero percent
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-10 10:33:09
 */

import {
    getJSObject
} from 'tinper-sparrow/src/util';
import {
    makeDOM
} from 'tinper-sparrow/src/dom';
import {
    on,
    off,
    stopEvent
} from 'tinper-sparrow/src/event';
import {
    Radio
} from 'tinper-neoui/src/neoui-radio';
import {
    addClass,
    removeClass
} from 'tinper-sparrow/src/dom';
import {
    env
} from 'tinper-sparrow/src/env';

var RadioAdapter = u.BaseAdapter.extend({
    init: function() {
        var self = this;
        this.dynamic = false;
        this.otherValue = this.options['otherValue'] || '其他';
        if (this.options['datasource'] || this.options['hasOther']) {
            // 存在datasource或者有其他选项，将当前dom元素保存，以后用于复制新的dom元素
            if (env.isIE) {
                this.radioTemplateHTML = this.element.innerHTML;
            } else {
                this.radioTemplateArray = [];
                for (var i = 0, count = this.element.childNodes.length; i < count; i++) {
                    this.radioTemplateArray.push(this.element.childNodes[i]);
                }
            }

        }
        if (this.options['datasource']) {
            this.dynamic = true;
            this.datasource = getJSObject(this.viewModel, this.options['datasource']);
            if (this.datasource)
                this.setComboData(this.datasource);
        } else {
            this.comp = new Radio(this.element);
            this.element['u.Radio'] = this.comp;
            this.eleValue = this.comp._btnElement.value;

            this.comp.on('change', function(event) {
                if (self.slice) return;
                var modelValue = self.dataModel.getValue(self.field);
                //var valueArr = modelValue == '' ?  [] : modelValue.split(',');
                if (self.comp._btnElement.checked) {
                    self.dataModel.setValue(self.field, self.eleValue);
                }
            });
        }

        // 如果存在其他
        if (this.options['hasOther']) {
            var node = null;
            if (env.isIE) {
                var nowHtml = this.element.innerHTML;
                this.element.innerHTML = nowHtml + this.radioTemplateHTML;
            } else {
                for (var j = 0; j < this.radioTemplateArray.length; j++) {
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
            }

            var LabelS = this.element.querySelectorAll('.u-radio');
            self.lastLabel = LabelS[LabelS.length - 1];
            var allRadioS = this.element.querySelectorAll('[type=radio]');
            self.lastRadio = allRadioS[allRadioS.length - 1];
            var nameDivs = this.element.querySelectorAll('.u-radio-label');
            self.lastNameDiv = nameDivs[nameDivs.length - 1];
            self.lastNameDiv.innerHTML = '其他';
            self.otherInput = makeDOM('<input type="text" disabled style="vertical-align: middle;line-height: normal;width: 80%">');
            self.lastNameDiv.parentNode.appendChild(self.otherInput);
            self.lastRadio.value = '';

            var comp;
            if (self.lastLabel['u.Radio']) {
                comp = self.lastLabel['u.Radio'];
            } else {
                comp = new Radio(self.lastLabel);
            }
            self.lastLabel['u.Radio'] = comp;
            self.otherComp = comp;
            comp.on('change', function() {
                if (comp._btnElement.checked) {
                    if (self.otherInput.value) {
                        self.dataModel.setValue(self.field, self.otherInput.value);
                    } else {
                        self.dataModel.setValue(self.field, self.otherValue);
                    }
                    // 选中后可编辑
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele) {
                        ele.removeAttribute('disabled');
                    });
                } else {
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele) {
                        ele.setAttribute('disabled', true);
                    });
                }
            });

            on(self.otherInput, 'blur', function(e) {
                self.otherComp.trigger('change');
            })
            on(self.otherInput, 'click', function(e) {
                stopEvent(e);
            })
        }

        this.dataModel.ref(this.field).subscribe(function(value) {
            self.modelValueChange(value)
        })

    },
    setComboData: function(comboData) {

        var self = this;
        this.datasource = comboData;
        this.element.innerHTML = '';
        if (env.isIE) {
            var htmlStr = ''
            for (var i = 0, len = comboData.length; i < len; i++) {
                htmlStr　 += this.radioTemplateHTML;
            }
            this.element.innerHTML = htmlStr;
        } else {
            for (var i = 0, len = comboData.length; i < len; i++) {
                for (var j = 0; j < this.radioTemplateArray.length; j++) {
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
                //this.radioTemplate.clone().appendTo(this.element)
            }
        }

        var allRadio = this.element.querySelectorAll('[type=radio]');
        var allName = this.element.querySelectorAll('.u-radio-label');
        for (var k = 0; k < allRadio.length; k++) {
            allRadio[k].value = comboData[k].pk || comboData[k].value;
            allName[k].innerHTML = comboData[k].name
        }

        this.radioInputName = '';
        if (allRadio.length > 0) {
            this.radioInputName = allRadio[0].name;
        }

        this.element.querySelectorAll('.u-radio').forEach(function(ele) {
            var comp = new Radio(ele);
            ele['u.Radio'] = comp;

            comp.on('change', function(event) {
                if (comp._btnElement.checked) {
                    self.dataModel.setValue(self.field, comp._btnElement.value);
                }
                // 其他元素input输入框不能进行编辑
                var allChild = comp.element.parentNode.children;
                var siblingAry = [];
                for (var i = 0; i < allChild.length; i++) {
                    if (allChild[i] == comp.element) {

                    } else {
                        siblingAry.push(allChild[i])
                    }
                }
                siblingAry.forEach(function(children) {
                    var childinput = children.querySelectorAll('input[type="text"]')
                    if (childinput) {
                        childinput.forEach(function(inputele) {
                            inputele.setAttribute('disabled', 'true')
                        });
                    }
                });
            });
        })
    },

    modelValueChange: function(value) {
        if (this.slice) return;
        var fetch = false,
            self = this;
        if (!value)
            value = '';
        if (this.dynamic) {
            if (this.datasource) {
                this.showValue = '';
                this.trueValue = value;
                this.element.querySelectorAll('.u-radio').forEach(function(ele) {
                    var comp = ele['u.Radio'];
                    if (comp) {
                        var inptuValue = comp._btnElement.value;
                        //解决boolean类型的true和false与"true"和"false"比较
                        if (inptuValue && inptuValue == value.toString()) {
                            fetch = true;
                            addClass(comp.element, 'is-checked')
                            comp._btnElement.click();
                            var nameSpan = ele.querySelector('.u-radio-label');
                            var showValue = $(nameSpan).text();
                            if (showValue) {
                                self.showValue = showValue;
                            }
                        } else {
                            removeClass(comp.element, 'is-checked')
                        }
                    }
                })
            }
        } else {
            if (this.eleValue == value) {
                fetch = true;
                this.slice = true;
                addClass(this.comp.element, 'is-checked')
                //this.comp._btnElement.click(); // https://github.com/iuap-design/tinper.org/issues/41
                this.slice = false;
            }
        }
        if (this.options.hasOther && !fetch && value) {
            this.showValue = value;
            if (!this.enable) {
                this.lastRadio.removeAttribute('disabled');
            }
            u.addClass(this.lastLabel, 'is-checked')
            this.lastRadio.checked = true;
            if (value != this.otherValue) {
                this.otherInput.value = value;
            }
            this.lastRadio.removeAttribute('disabled');
            this.otherInput.removeAttribute('disabled');
            if (!this.enable) {
                this.lastRadio.setAttribute('disabled', true);
            }
        }
    },

    setEnable: function(enable) {
        this.enable = (enable === true || enable === 'true');
        if (this.dynamic) {
            if (this.datasource) {
                if (this.otherInput && !this.enable) {
                    this.otherInput.setAttribute('disabled', true);
                }
                this.element.querySelectorAll('.u-radio').forEach(function(ele) {
                    var comp = ele['u.Radio'];
                    if (comp) {
                        if (enable === true || enable === 'true') {
                            comp.enable();
                        } else {
                            comp.disable();
                        }
                    }
                })
            }
        } else {
            if (this.enable) {
                this.comp.enable();
            } else {
                this.comp.disable();
            }
        }
    }
})

if (u.compMgr)
    u.compMgr.addDataAdapter({
        adapter: RadioAdapter,
        name: 'u-radio'
    });
export {
    RadioAdapter
};
<|endoftext|>


<commit_before>/* eslint-disable */
'use strict';

// const bodyParser = require('body-parser');
const express = require('express');
// const mongoose = require('mongoose');

const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Server Running');
});

app.listen(PORT, ()=>{
  console.log(`Evernode running on port: ${PORT}`);
});
<commit_msg>disabled pre-commit hook<commit_after>'use strict';

// const bodyParser = require('body-parser');
const express = require('express');
// const mongoose = require('mongoose');

const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Server Running');
});

app.listen(PORT, ()=>{
  console.log(`Evernode running on port: ${PORT}`);
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s t<commit_msg>GET A HAIRCUT!<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to<|endoftext|>


<commit_before>var qrcode = require('qrcode-terminal');
var crontab = require('crontab');
var Promise = require('bluebird');
var gitUtils = require('git-utils');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var fetch = require('node-fetch');
var nodeGit = require('nodegit');
var _ = require('lodash');
var mkdirp = Promise.promisify(require('mkdirp'));
var exec = require('child_process').exec;
var nconf = require('nconf');

var CONFIG = {
  NAME: 'gitmonitor',
  SERVER: process.env.GITMONITOR_SERVER || 'http://dockerhost.dev:3000',
  CONFIGFILE: '/.gitmonitor/config.json',
};

module.exports = {
	// for testing only
  removeConfig: removeConfig, // done
  readConfig: readConfig, // done
  writeConfig: writeConfig, // done
  installCron: installCron, // done
  unInstallCron: unInstallCron, // done
  getRepoInfos: getRepoInfos, // done
  installRaw: installRaw, // done
  uninstallRaw: uninstallRaw, // done
  updateRaw: updateRaw, // done
  isInstalled: isInstalled,
  getAppBinaryPath: getAppBinaryPath,
  cronCommand: cronCommand,

	// interface
	install: install,
	uninstall: uninstall,
	update: update,
  CONFIG: CONFIG
};

function cronCommand(binary, repoPath){
  return  binary + ' update ' + repoPath;
}

function updateRaw(repoPath){
  return getRepoInfos(repoPath).bind({}).then(function(repoInfo) {
    this.repoInfo = repoInfo;
    return readConfig(repoPath);
  }).then(function(config) {
    return apiUpdateRepo({
      id: config.id,
      repoData: this.repoInfo
    });
  });
}

function update(args) {
	var repoPath = getPath(args);
  updateRaw(repoPath).then(function() {
    showSuccess('Updated Repo successfully');
  }).catch(function(err) {
    showError(err);
  });
}

function apiCall(call) {
  return fetch(CONFIG.SERVER + call.route, {
    method: call.method,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(call.body)
  });
}

function apiUpdateRepo(data) {
  return apiCall({
    method: 'put',
    route: '/api/Repos/' + data.id,
    body: data.repoData
  });
}

function apiRemoveRepo(id) {
  return apiCall({
    method: 'delete',
    route: '/api/Repos/' + id
  });
}

function filterResponseId(data) {
  return data.json().then(function(dataInner) {
    return new Promise(function(resolve, reject) {
      if (dataInner.id) {
        resolve({
          id: dataInner.id
        });
      } else {
        reject('Failed to get Id from server');
      }
    });
  });
}

function readConfig(repoPath) {
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  return fs.readFileAsync(configFilePath).then(function(data) {
    return new Promise(function(resolve) {
      resolve(JSON.parse(data.toString()));
    });
  });
}

function getDirFromPath(myPath) {
  var dir = myPath.split('/')
  return dir.slice(0, dir.length - 1).join('/');
}

function removeConfig(repoPath) {
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  var dir = getDirFromPath(configFilePath);
  return fs.unlinkAsync(configFilePath).then(function() {
    return fs.rmdirAsync(dir);
  });
}

function writeConfig(config, repoPath) {
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  var dir = getDirFromPath(configFilePath);
  return mkdirp(dir).then(function() {
    return fs.writeFileAsync(configFilePath, JSON.stringify(config)).then(function() {
      return new Promise(function(resolve) {
        resolve(config);
      });
    })
  });
}

function apiAddRepo(data, repoPath) {
  return apiCall({
    method: 'post',
    route: '/api/Repos/',
    body: data
  }).then(filterResponseId).then(function(data){
    return writeConfig(data, repoPath);
  });
}

function promiseFromChildProcess(args) {
  var deferred = Promise.pending();
  exec(args, function(err, out) {
    if (err) {
      deferred.reject(err);
    }
    deferred.resolve(out);
  });
  return deferred.promise;
}

function installCron(repoPath) {
  return Promise.promisify(crontab.load)().then(function(crontabIn) {
    return [
      getAppBinaryPath(),
      crontabIn
    ]
  }).spread(function(appName, crontabInner) {
    var deferred = Promise.pending();
    var command = cronCommand(appName.trim(), repoPath);
    if (crontabInner.jobs({
        command: command
      }).length > 0) {
      deferred.reject('Crontab already exists');
    }
    crontabInner.create(command, '* * * * *', 'added by ' + CONFIG.NAME);
    crontabInner.save(function(err) {
      if (err) {
        deferred.reject(err);
      }
      deferred.resolve();
    });
		return deferred.promise;
  });
};

function getAppBinaryPath(){
  return promiseFromChildProcess('which ' + CONFIG.NAME);
}

function unInstallCron(repoPath) {
  return Promise.promisify(crontab.load)().then(function(crontabIn) {
    return [
      getAppBinaryPath(),
      crontabIn
    ]
  }).spread(function(nodePath, crontabInner) {
    var deferred = Promise.pending();
    var command = cronCommand(nodePath.trim(), repoPath);
    crontabInner.remove({
      command: command
    });
    crontabInner.save(function(err) {
      if (err) {
        deferred.reject(err);
      }
      deferred.resolve();
    });
		return deferred.promise;
  });
};

function getRepoInfos(repoPath) {
  var deferred = Promise.pending();
  var repositoryU = gitUtils.open(repoPath);

  if (repositoryU) {
    nodeGit.Repository.open(repoPath).then(function(repository) {
      return Promise.all([
        repository.getHeadCommit(),
        repository.getCurrentBranch()
      ]);
    }).then(function(res) {
      var commit = res[0];
      var branch = res[1].toString();
      var output = {};
      output.branch = branch;
      output.name = path.basename(repoPath);
      output.author = commit.author().toString();
      output.message = commit.message();
			output.notified = false;
      output.isClean = (_.keys(repositoryU.getStatus()).length === 0);
      output.branches = repositoryU.getReferences().heads;
      output.status = repositoryU.getAheadBehindCount('refs/heads/master');
      deferred.resolve(output);
    }).catch(function() {
      deferred.reject('Could not read repo details');
    });
  } else {
    deferred.reject('Not a git repo');
  }
  return deferred.promise;
}

function install(args) {
  var repoPath = getPath(args);
  installRaw(repoPath).then(function(obj) {
		console.log('Scan the Qrcode with your '+CONFIG.NAME + '-App')
    qrcode.generate(obj.config.id);
  }).catch(function(err) {
    showError(err);
  });
}

function installRaw(repoPath) {
  var obj = {};
  return isInstalled(CONFIG.CONFIGFILE, 'install').then(function() {
    return getRepoInfos(repoPath);
  }).then(function(repoData) {
    return apiAddRepo(repoData, repoPath);
  }).then(function(config) {
    obj.config = config;
    return installCron(repoPath);
  }).then(function(){
    return Promise.resolve(obj);
  })
}

function showSuccess(msg) {
  console.log(msg);
}

function showError(msg) {
  console.error(msg);
}

function uninstall(args) {
	var repoPath = getPath(args);
  uninstallRaw(repoPath)
    .then(function() {
      showSuccess('Sucessfully uninstalled');
    })
    .catch(function(err) {
      showError(err);
    });
}
function uninstallRaw(repoPath){
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  return isInstalled(configFilePath, 'uninstall').then(function() {
      return unInstallCron(repoPath).then(function() {
        return readConfig(repoPath).then(function(config) {
          return apiRemoveRepo(config.id);
        });
      })
    }).then(function(){
      return removeConfig(repoPath);
    })
}

function fExists(file) {
  return new Promise(function(resolve) {
    try {
      fs.lstat(file, function(err) {
        if (err) return resolve(false);
        resolve(true);
      });
    } catch (err) {
      resolve(false);
    }
  });
}

function getPath(args){
	var repoPath = path.resolve('./');
  if (args.argv._[1]) {
    repoPath = path.resolve(args.argv._[1]);
  }
	return repoPath;
}

function isInstalled(file, iOrUi) {
  return fExists(file).then(function(exists) {
    return new Promise(function(resolve, reject) {
      if (exists) {
        if (iOrUi == 'install') {
          reject('Already installed');
        } else {
          resolve();
        }
      } else {
        if (iOrUi == 'uninstall') {
          reject('Already uninstalled');
        } else {
          resolve();
        }
      }
    });
  });
}
<commit_msg>added server to config<commit_after>var qrcode = require('qrcode-terminal');
var crontab = require('crontab');
var Promise = require('bluebird');
var gitUtils = require('git-utils');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var fetch = require('node-fetch');
var nodeGit = require('nodegit');
var _ = require('lodash');
var mkdirp = Promise.promisify(require('mkdirp'));
var exec = require('child_process').exec;
var nconf = require('nconf');

var CONFIG = {
  NAME: 'gitmonitor',
  SERVER: process.env.GITMONITOR_SERVER || 'http://dockerhost.dev:3000',
  CONFIGFILE: '/.gitmonitor/config.json',
};

module.exports = {
	// for testing only
  removeConfig: removeConfig, // done
  readConfig: readConfig, // done
  writeConfig: writeConfig, // done
  installCron: installCron, // done
  unInstallCron: unInstallCron, // done
  getRepoInfos: getRepoInfos, // done
  installRaw: installRaw, // done
  uninstallRaw: uninstallRaw, // done
  updateRaw: updateRaw, // done
  isInstalled: isInstalled,
  getAppBinaryPath: getAppBinaryPath,
  cronCommand: cronCommand,

	// interface
	install: install,
	uninstall: uninstall,
	update: update,
  CONFIG: CONFIG
};

function cronCommand(binary, repoPath){
  return  binary + ' update ' + repoPath;
}

function updateRaw(repoPath){
  return getRepoInfos(repoPath).bind({}).then(function(repoInfo) {
    this.repoInfo = repoInfo;
    return readConfig(repoPath);
  }).then(function(config) {
    return apiUpdateRepo({
      id: config.id,
      repoData: this.repoInfo
    });
  });
}

function update(args) {
	var repoPath = getPath(args);
  readConfig(repoPath).then(function(config){
    if(config.server){
      CONFIG.SERVER = config.server
    }
    return updateRaw(repoPath).then(function() {
      showSuccess('Updated Repo successfully');
    })
  }).catch(function(err) {
    showError(err);
  });
}

function apiCall(call) {
  return fetch(CONFIG.SERVER + call.route, {
    method: call.method,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(call.body)
  });
}

function apiUpdateRepo(data) {
  return apiCall({
    method: 'put',
    route: '/api/Repos/' + data.id,
    body: data.repoData
  });
}

function apiRemoveRepo(id) {
  return apiCall({
    method: 'delete',
    route: '/api/Repos/' + id
  });
}

function filterResponseId(data) {
  return data.json().then(function(dataInner) {
    return new Promise(function(resolve, reject) {
      if (dataInner.id) {
        resolve({
          id: dataInner.id
        });
      } else {
        reject('Failed to get Id from server');
      }
    });
  });
}

function readConfig(repoPath) {
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  return fs.readFileAsync(configFilePath).then(function(data) {
    return new Promise(function(resolve) {
      resolve(JSON.parse(data.toString()));
    });
  });
}

function getDirFromPath(myPath) {
  var dir = myPath.split('/')
  return dir.slice(0, dir.length - 1).join('/');
}

function removeConfig(repoPath) {
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  var dir = getDirFromPath(configFilePath);
  return fs.unlinkAsync(configFilePath).then(function() {
    return fs.rmdirAsync(dir);
  });
}

function writeConfig(config, repoPath) {
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  var dir = getDirFromPath(configFilePath);
  return mkdirp(dir).then(function() {
    return fs.writeFileAsync(configFilePath, JSON.stringify(config)).then(function() {
      return new Promise(function(resolve) {
        resolve(config);
      });
    })
  });
}

function apiAddRepo(data, repoPath) {
  return apiCall({
    method: 'post',
    route: '/api/Repos/',
    body: data
  }).then(filterResponseId).then(function(data){
    data.server = CONFIG.SERVER;
    return writeConfig(data, repoPath);
  });
}

function promiseFromChildProcess(args) {
  var deferred = Promise.pending();
  exec(args, function(err, out) {
    if (err) {
      deferred.reject(err);
    }
    deferred.resolve(out);
  });
  return deferred.promise;
}

function installCron(repoPath) {
  return Promise.promisify(crontab.load)().then(function(crontabIn) {
    return [
      getAppBinaryPath(),
      crontabIn
    ]
  }).spread(function(appName, crontabInner) {
    var deferred = Promise.pending();
    var command = cronCommand(appName.trim(), repoPath);
    if (crontabInner.jobs({
        command: command
      }).length > 0) {
      deferred.reject('Crontab already exists');
    }
    crontabInner.create(command, '* * * * *', 'added by ' + CONFIG.NAME);
    crontabInner.save(function(err) {
      if (err) {
        deferred.reject(err);
      }
      deferred.resolve();
    });
		return deferred.promise;
  });
};

function getAppBinaryPath(){
  return promiseFromChildProcess('which ' + CONFIG.NAME);
}

function unInstallCron(repoPath) {
  return Promise.promisify(crontab.load)().then(function(crontabIn) {
    return [
      getAppBinaryPath(),
      crontabIn
    ]
  }).spread(function(nodePath, crontabInner) {
    var deferred = Promise.pending();
    var command = cronCommand(nodePath.trim(), repoPath);
    crontabInner.remove({
      command: command
    });
    crontabInner.save(function(err) {
      if (err) {
        deferred.reject(err);
      }
      deferred.resolve();
    });
		return deferred.promise;
  });
};

function getRepoInfos(repoPath) {
  var deferred = Promise.pending();
  var repositoryU = gitUtils.open(repoPath);

  if (repositoryU) {
    nodeGit.Repository.open(repoPath).then(function(repository) {
      return Promise.all([
        repository.getHeadCommit(),
        repository.getCurrentBranch()
      ]);
    }).then(function(res) {
      var commit = res[0];
      var branch = res[1].toString();
      var output = {};
      output.branch = branch;
      output.name = path.basename(repoPath);
      output.author = commit.author().toString();
      output.message = commit.message();
			output.notified = false;
      output.isClean = (_.keys(repositoryU.getStatus()).length === 0);
      output.branches = repositoryU.getReferences().heads;
      output.status = repositoryU.getAheadBehindCount('refs/heads/master');
      deferred.resolve(output);
    }).catch(function() {
      deferred.reject('Could not read repo details');
    });
  } else {
    deferred.reject('Not a git repo');
  }
  return deferred.promise;
}

function install(args) {
  var repoPath = getPath(args);
  installRaw(repoPath).then(function(obj) {
		console.log('Scan the Qrcode with your '+CONFIG.NAME + '-App')
    qrcode.generate(obj.config.id);
  }).catch(function(err) {
    showError(err);
  });
}

function installRaw(repoPath) {
  var obj = {};
  return isInstalled(CONFIG.CONFIGFILE, 'install').then(function() {
    return getRepoInfos(repoPath);
  }).then(function(repoData) {
    return apiAddRepo(repoData, repoPath);
  }).then(function(config) {
    obj.config = config;
    return installCron(repoPath);
  }).then(function(){
    return Promise.resolve(obj);
  })
}

function showSuccess(msg) {
  console.log(msg);
}

function showError(msg) {
  console.error(msg);
}

function uninstall(args) {
	var repoPath = getPath(args);
  uninstallRaw(repoPath)
    .then(function() {
      showSuccess('Sucessfully uninstalled');
    })
    .catch(function(err) {
      showError(err);
    });
}
function uninstallRaw(repoPath){
  var configFilePath = path.join(repoPath, CONFIG.CONFIGFILE);
  return isInstalled(configFilePath, 'uninstall').then(function() {
      return unInstallCron(repoPath).then(function() {
        return readConfig(repoPath).then(function(config) {
          return apiRemoveRepo(config.id);
        });
      })
    }).then(function(){
      return removeConfig(repoPath);
    })
}

function fExists(file) {
  return new Promise(function(resolve) {
    try {
      fs.lstat(file, function(err) {
        if (err) return resolve(false);
        resolve(true);
      });
    } catch (err) {
      resolve(false);
    }
  });
}

function getPath(args){
	var repoPath = path.resolve('./');
  if (args.argv._[1]) {
    repoPath = path.resolve(args.argv._[1]);
  }
	return repoPath;
}

function isInstalled(file, iOrUi) {
  return fExists(file).then(function(exists) {
    return new Promise(function(resolve, reject) {
      if (exists) {
        if (iOrUi == 'install') {
          reject('Already installed');
        } else {
          resolve();
        }
      } else {
        if (iOrUi == 'uninstall') {
          reject('Already uninstalled');
        } else {
          resolve();
        }
      }
    });
  });
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
<commit_msg>Fixing an error introduced in the last commit<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced <|endoftext|>


<commit_before>this.mmooc=this.mmooc||{};

this.mmooc.pages = function() {
    function updateButtonText(container, input, label) {
        if (input.is(":checked")) {
            label.html('Marker som ulest');
            container.addClass("is-done");
        } else {
            label.html('Marker som lest');
            container.removeClass("is-done");
        }
    }

    return {
        modifyMarkAsDoneButton: function() {
            $("body").bind("wiki-page-rendered", function() {
                var container = $("#mark-as-done-container");
                container.appendTo("#content .usercontent");

                var input = container.find("input");
                var label = container.find("label");
                input.change(function() {
                    updateButtonText(container, input, label);
                });

                updateButtonText(container, input, label);

                container.show();
            });
        },

        changeTranslations : function() {
            $("a.submit_assignment_link").text('Lever besvarelse');
        },

        showBackLinkIfNecessary: function() {
            if ($('#left-side').is(':hidden')) {
                var linkBack = mmooc.util.renderTemplateWithData("navigateToPreviousPage", {linkText: mmooc.i18n.LinkBack});
                $(linkBack).prependTo($('#content'));
            }
        },

        showBackToAssignmentLink: function(href) {
          if (/\/courses\/\d+\/assignments\/\d+\/submissions\/\d+$/.test(href)) {
            $('#add_comment_form').append('Tilbake til oppgaven');
            return true;
          }

          return false;
        }
    };
}();
<commit_msg>Added function for moving mark as done button to the correct container<commit_after>this.mmooc=this.mmooc||{};

this.mmooc.pages = function() {
    function updateButtonText(container, input, label) {
        if (input.is(":checked")) {
            label.html('Marker som ulest');
            container.addClass("is-done");
        } else {
            label.html('Marker som lest');
            container.removeClass("is-done");
        }
    }

    return {
        modifyMarkAsDoneButton: function() {
            $("body").bind("wiki-page-rendered", function() {
                var container = $("#mark-as-done-container");
                container.appendTo("#content .usercontent");

                var input = container.find("input");
                var label = container.find("label");
                input.change(function() {
                    updateButtonText(container, input, label);
                });

                updateButtonText(container, input, label);

                container.show();
            });
        },

        moveMarkAsDoneButton: function() {
          var button = $("#mark-as-done-checkbox");
          var container = $("#mark-as-done-container");
          button.appendTo(container);
        },

        changeTranslations : function() {
            $("a.submit_assignment_link").text('Lever besvarelse');
        },

        showBackLinkIfNecessary: function() {
            if ($('#left-side').is(':hidden')) {
                var linkBack = mmooc.util.renderTemplateWithData("navigateToPreviousPage", {linkText: mmooc.i18n.LinkBack});
                $(linkBack).prependTo($('#content'));
            }
        },

        showBackToAssignmentLink: function(href) {
          if (/\/courses\/\d+\/assignments\/\d+\/submissions\/\d+$/.test(href)) {
            $('#add_comment_form').append('Tilbake til oppgaven');
            return true;
          }

          return false;
        }
    };
}();
<|endoftext|>


<commit_before>var express = require('express')
var app = express()
var port = process.env.PORT || 5000

//
// Load and launch application.
//
require('./app/datastore.js')(app)
app.listen(port)
console.log('DataStore service running on port: ' + port)
<commit_msg>adding cors<commit_after>var express = require('express')
var cors = require('cors')
var app = express()
var port = process.env.PORT || 5000

//
// Load and launch application.
//
app.use(cors())
require('./app/datastore.js')(app)
app.listen(port)
console.log('DataStore service running on port: ' + port)
<|endoftext|>


<commit_before>/**
 * grunt-angular-translate
 * https://github.com/firehist/grunt-angular-translate
 *
 * Copyright (c) 2013 "firehist" Benjamin Longearet, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function ( grunt ) {

  grunt.registerMultiTask('i18nextract', 'Generate json language file for angular-translate project', function() {

    var _ = grunt.util._;

    // Require lang array with length >= 1
    if (!this.data.lang || !this.data.lang.length) {
      grunt.fail('No lang set for i18nextract');
    }

    var files     = grunt.file.expand( this.data.src ),
         dest      = this.data.dest || '.',
         extraSrc     = grunt.file.expand( this.data.extraSrc || '' ),
         extraSrcName      = grunt.util._.union( this.data.extraSrcName || [], ['label'] ),
         defaultLang      = this.data.defaultLang || '.',
         source    = this.data.source || '',
         prefix    = this.data.prefix || '',
         safeMode  = this.data.safeMode ? true : false,
         suffix    = this.data.suffix || '.json',
         results   = {};

    if (!grunt.file.exists(dest)) {
      grunt.file.mkdir( dest );
    }

    // Parse all files to extract translations
    files.forEach(function(file) {

      grunt.log.debug("Process file: " + file);

      var content = grunt.file.read(file), r;
      while ((r = filterRegexSimple.exec(content)) !== null) {
        if (r.length === 2) {
          results[ grunt.util._(r[1]).strip() ] = '';
        }
      }
      while ((r = filterRegexDouble.exec(content)) !== null) {
        if (r.length === 2) {
          results[ grunt.util._(r[1]).strip() ] = '';
        }
      }
      while ((r = javascriptRegex.exec(content)) !== null) {
        if (r.length === 2) {
          results[ grunt.util._(r[1]).strip() ] = '';
        }
      }
      while ((r = directiveRegex.exec(content)) !== null) {
        if (r.length === 2) {
          results[ grunt.util._(r[1]).strip() ] = '';
        }
      }

      while ((r = javascriptRegex2.exec(content)) !== null) {
        if (r.length === 2) {
          results[ grunt.util._(r[1]).strip() ] = '';
        }
      }

    });

    var _recurseObject = function (data) {
      var currentArray = new Array();
      if (_.isObject(data) || _.isArray(data['attr'])) {
        for (var attr in data) {
          if (_.isString(data[attr]) && _.indexOf(extraSrcName, attr) !== -1) {
            currentArray.push(data[attr]);
          } else if (_.isObject(data[attr]) || _.isArray(data['attr'])) {
              var recurse = _recurseObject(data[attr]);
              currentArray = _.union(currentArray, recurse);
          }
        }
      }
      return currentArray;
    };

    // Parse all extra files to extra
    extraSrc.forEach(function(file) {

      grunt.log.debug("Process extra file: " + file);

      var content = grunt.file.readJSON(file);
      var extractValues = _recurseObject(content);
      for (var i in extractValues) {
          results[ _(extractValues[i]).strip() ] = '';
      }

    });

    this.data.lang.forEach(function(lang) {

      var destFilename  = dest + '/' + prefix + lang + suffix,
          filename   = source,
          translations  = {},
          nbTra         = 0,
          nbEmpty       = 0,
          nbNew         = 0,
          nbDel         = 0,
          json          = {};

      // Test source filename
      if ( filename === '' || !grunt.file.exists( filename ) ) {
        filename = destFilename;
      }

      grunt.log.subhead('Process ' + lang + ' : ' + filename);

      if ( !grunt.file.exists( filename ) ) {
        grunt.log.debug('File doesn\'t exist');
        translations = results;
      } else {
        grunt.log.debug('File exist');
        json = grunt.file.readJSON( filename );

        grunt.util._.extend( (translations = grunt.util._.clone(results) ), json );
      }
      // Make some stats
      for (var key in translations) {
        var translation = translations[ key ],
            isJson      = grunt.util.kindOf( json[key] ) === 'string',
            isResults   = grunt.util.kindOf( results[key] ) === 'string';

        nbTra++;

        if (translation === '') {       // Case empty translation
          if (lang === defaultLang) {
            translations[ key ] = key;
          } else {
            nbEmpty++;
          }
        }
        if ( !isJson && isResults ) {   // Case new translation (exist into src files but not in json file)
          nbNew++;
        }
        if ( isJson && !isResults ) {   // Case deleted translation (exist in json file but not into src files)
          nbDel++;
          if ( !safeMode ) {
            delete translations[ key ];
          }
        }
      }
      // Some information for the output
      if ( !grunt.file.exists( destFilename ) ) {
        grunt.log.subhead('Create file: ' + destFilename);
      }

      grunt.log.writeln('Empty: ' + nbEmpty + ' (' + Math.round( nbEmpty / nbTra * 100 ) + '%) / New: ' + nbNew + ' / Deleted: ' + nbDel);
      // Write JSON file for lang
      grunt.file.write( destFilename, JSON.stringify( translations, null, 4 ) );

    });

    var nbLang = this.data.lang.length || 0;
    grunt.log.ok(nbLang + ' file' + (nbLang ? 's' : '') + ' updated');

  });

  var path            = require('path'),
      // Use to match {{'TRANSLATION' | translate}}
      filterRegexDouble     = /{{\s*"((?:\\.|[^"\\])*)"\s*\|\s*translate(?:[^}]*)}}/gi,
      filterRegexSimple     = /{{\s*'((?:\\.|[^'\\])*)'\s*\|\s*translate(?:[^}]*)}}/gi,
      // Use to match TRANSLATION
      directiveRegex  = /<[^>]*translate[^{>]*>([^<]*)<\/[^>]*>/gi,
      // Use to match $translate('TRANSLATION')
      javascriptRegex = /\$translate\([^'"]['"]([^'"]*)['"][^'"]*\)/gi,
      // Used to match $filter("translate")("TRANSLATION")
      javascriptRegex2 = /\$filter\(\s*['"]translate['"]\s*\)\s*\(\s*['"](.*[\S].*)['"]\s*\)/gi;
};
<commit_msg>implement angular-plural-extract to manage pluralize<commit_after>/**
 * grunt-angular-translate
 * https://github.com/firehist/grunt-angular-translate
 *
 * Copyright (c) 2013 "firehist" Benjamin Longearet, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

  grunt.registerMultiTask('i18nextract', 'Generate json language file for angular-translate project', function () {

    var _ = grunt.util._;

    // Require lang array with length >= 1
    if (!this.data.lang || !this.data.lang.length) {
      grunt.fail('No lang set for i18nextract');
    }

    var files = grunt.file.expand(this.data.src),
      dest = this.data.dest || '.',
      extraSrc = grunt.file.expand(this.data.extraSrc || ''),
      extraSrcName = grunt.util._.union(this.data.extraSrcName || [], ['label']),
      defaultLang = this.data.defaultLang || '.',
      source = this.data.source || '',
      prefix = this.data.prefix || '',
      safeMode = this.data.safeMode ? true : false,
      suffix = this.data.suffix || '.json',
      results = {};

    if (!grunt.file.exists(dest)) {
      grunt.file.mkdir(dest);
    }

    // Parse all files to extract translations
    files.forEach(function (file) {

      grunt.log.debug("Process file: " + file);

      var content = grunt.file.read(file), r;

      for (var i in regexs) {
        while ((r = regexs[i].exec(content)) !== null) {
          if (r.length === 2) {
            results[ grunt.util._(r[1]).strip() ] = '';
          }
        }
      }

    });

    var _recurseObject = function (data) {
      var currentArray = new Array();
      if (_.isObject(data) || _.isArray(data['attr'])) {
        for (var attr in data) {
          if (_.isString(data[attr]) && _.indexOf(extraSrcName, attr) !== -1) {
            currentArray.push(data[attr]);
          } else if (_.isObject(data[attr]) || _.isArray(data['attr'])) {
            var recurse = _recurseObject(data[attr]);
            currentArray = _.union(currentArray, recurse);
          }
        }
      }
      return currentArray;
    };

    // Parse all extra files to extra
    extraSrc.forEach(function (file) {

      grunt.log.debug("Process extra file: " + file);

      var content = grunt.file.readJSON(file);
      var extractValues = _recurseObject(content);
      for (var i in extractValues) {
        results[ _(extractValues[i]).strip() ] = '';
      }

    });

    this.data.lang.forEach(function (lang) {

      var destFilename = dest + '/' + prefix + lang + suffix,
        filename = source,
        translations = {},
        nbTra = 0,
        nbEmpty = 0,
        nbNew = 0,
        nbDel = 0,
        json = {};

      // Test source filename
      if (filename === '' || !grunt.file.exists(filename)) {
        filename = destFilename;
      }

      grunt.log.subhead('Process ' + lang + ' : ' + filename);

      if (!grunt.file.exists(filename)) {
        grunt.log.debug('File doesn\'t exist');
        translations = results;
      } else {
        grunt.log.debug('File exist');
        json = grunt.file.readJSON(filename);

        grunt.util._.extend((translations = grunt.util._.clone(results) ), json);
      }
      // Make some stats
      for (var key in translations) {
        var translation = translations[ key ],
          isJson = grunt.util.kindOf(json[key]) === 'string',
          isResults = grunt.util.kindOf(results[key]) === 'string';

        nbTra++;

        if (translation === '') {       // Case empty translation
          if (lang === defaultLang) {
            translations[ key ] = key;
          } else {
            nbEmpty++;
          }
        }
        if (!isJson && isResults) {   // Case new translation (exist into src files but not in json file)
          nbNew++;
        }
        if (isJson && !isResults) {   // Case deleted translation (exist in json file but not into src files)
          nbDel++;
          if (!safeMode) {
            delete translations[ key ];
          }
        }
      }
      // Some information for the output
      if (!grunt.file.exists(destFilename)) {
        grunt.log.subhead('Create file: ' + destFilename);
      }

      grunt.log.writeln('Empty: ' + nbEmpty + ' (' + Math.round(nbEmpty / nbTra * 100) + '%) / New: ' + nbNew + ' / Deleted: ' + nbDel);
      // Write JSON file for lang
      grunt.file.write(destFilename, JSON.stringify(translations, null, 4));

    });

    var nbLang = this.data.lang.length || 0;
    grunt.log.ok(nbLang + ' file' + (nbLang ? 's' : '') + ' updated');

  });

  var path = require('path');
  var regexs = {
    // Use to match {{'TRANSLATION' | translate}}
    filterRegexDouble: /{{\s*"((?:\\.|[^"\\])*)"\s*\|\s*translate(?:[^}]*)}}/gi,
    filterRegexSimple: /{{\s*'((?:\\.|[^'\\])*)'\s*\|\s*translate(?:[^}]*)}}/gi,
    filterRegexPlural: /angular-plural-extract=\"((?:\\.|[^"\\])*)\"/gi,
    // Use to match TRANSLATION
    directiveRegex: /<[^>]*translate[^{>]*>([^<]*)<\/[^>]*>/gi,
    // Use to match $translate('TRANSLATION')
    javascriptRegex: /\$translate\([^'"]['"]([^'"]*)['"][^'"]*\)/gi,
    // Used to match $filter("translate")("TRANSLATION")
    javascriptRegex2: /\$filter\(\s*['"]translate['"]\s*\)\s*\(\s*['"](.*[\S].*)['"]\s*\)/gi
  };
};
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter <commit_msg>Cleaned out the intertubes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Contents/Developer/usr/bin/git', args)
    var timeout = randomIntFromInterval(0, max_sleep)
    counter = counter +<|endoftext|>