<commit_before>var models = require('../models');
var _ = require('lodash');
var cache = require('../cache');
var sass = require('node-sass');
var browserify = require('browserify');
var path = require('path');
var uuid = require('node-uuid');
var resumer = require('resumer');
var tasks = require('../../tasks');
var config = require('../../config/config');

exports.index = function (req, res, next) {

    models.VisualizationType.findAll()
        .then(function(types) {
            return res.json(types);
        }).error(next);
};

exports.show = function (req, res, next) {

    models.VisualizationType.findAll({
            order: '"name" ASC'
        })
        .then(function(types) {

            return res.render('viz-types/show', {
                vizTypes: types
            });

        }).error(next);
};

exports.resetDefaults = function(req, res, next) {

    console.log('resetting visualization defaults');

    models.VisualizationType
        .destroy({}, {truncate: true}).success(function() {
            console.log('successfully deleted current visualizations');
            tasks.getDefaultVisualizations(function() {
                return res.redirect(config.baseURL + 'visualization-types');
            });

        }).error(function(err) {
            console.log(err);
            return res.status(500).send();
        });
};

exports.fetchDefaults = function (req, res, next) {

    tasks.getDefaultVisualizations(function() {
        return res.redirect(config.baseURL + 'visualization-types');
    });
};

exports.create = function (req, res, next) {

    models.VisualizationType
        .create(_.pick(req.body, 'name', 'initialDataFields', 'isStreaming', 'javascript', 'styles', 'markup', 'sampleData', 'sampleOptions'))
        .then(function(type) {
            return res.json(type);
        }).error(function(err) {
            return res.status(500).send(err);
        });

};

exports.edit = function (req, res, next) {

    models.VisualizationType
        .find(req.params.vid)
        .success(function(vizType) {
            return vizType.updateAttributes(_.pick(req.body, 'name', 'isStreaming', 'initialDataFields', 'javascript', 'styles', 'markup'));
        })
        .success(function(vizType) {
            setTimeout(function() {
                _.each(cache.keys(), function(key) {

                    console.log(key);
                    if(key.indexOf(vizType.name) > -1) {
                        console.log('deleting ' + key);
                        cache.del(key);
                    }
                });
            }, 0);
            return res.status(200).send();
        }).error(function() {
            return res.status(500).send();
        });
};

exports.delete = function (req, res, next) {

    var vizTypeId = req.params.vid;

    models.VisualizationType
        .find(vizTypeId)
        .then(function(vizType) {
            vizType.deleteAndUninstall().then(function() {
                return res.json(vizType);
            }).error(next);
        }).error(next);
};

exports.getDelete = function(req, res, next) {

    var vizTypeId = req.params.vid;

    models.VisualizationType
        .find(vizTypeId)
        .then(function(vizType) {
            vizType
                .deleteAndUninstall()
                .then(function() {
                    return res.redirect(config.baseURL + 'visualization-types/');
                }).catch(next);
        }).catch(next);
};

exports.preview = function(req, res, next) {

    var tmpPath = path.resolve(__dirname + '/../../tmp/js-build/' + uuid.v4() + '/');
    req.session.lastBundlePath = tmpPath;

    var vizTypePromise, name;

    if(req.query.url) {
        var url = req.query.url;
        name = url;
        if(req.query.path) {
            name += '/' + req.query.path;
        }

        name = req.query.name || /[^/]*$/.exec(name)[0];

        vizTypePromise = models.VisualizationType
            .createFromRepoURL(url, { name: name }, {preview: true, path: req.query.path});
    } else if(req.query.path && process.env.NODE_ENV !== 'production') {
        var p = path.resolve(req.query.path);
        name = req.query.name || /[^/]*$/.exec(p)[0];

        vizTypePromise = models.VisualizationType
            .createFromFolder(p, { name: name}, {preview: true});
    }

    vizTypePromise
        .then(function(vizType) {

            console.log('created viz preview');

            vizType.exportToFS(tmpPath)
                .spread(function() {
                    var b = browserify();
                    if(vizType.isModule) {
                        b.require(vizType.moduleName, {
                            expose: vizType.moduleName
                        });
                    } else {
                        var stream = resumer().queue(vizType.javascript).end();
                        b.require(stream, {
                            basedir: tmpPath,
                            expose: vizType.name
                        });
                    }

                    b.bundle(function(err, buf) {

                        if(err) {
                            return next(err);
                        }

                        var javascript = buf.toString('utf8');
                        var scssData = '#lightning-body {\n';
                        if(vizType.styles) {
                            scssData += vizType.styles + '\n';
                        }
                        scssData += '\n}';
                        sass.render({
                            data: scssData,
                            success: function(sassResults) {
                                if(req.url.indexOf('/preview/full') > -1) {
                                    return res.render('viz-types/full-preview', {
                                        vizType: vizType,
                                        javascript: javascript,
                                        css: sassResults.css,
                                        path: path.resolve(req.query.path || ''),
                                        url: req.query.url,
                                        source: req.query.url ? 'gitRepo' : 'localFolder'
                                    });
                                }
                                return res.render('viz-types/preview-editor', {
                                    vizType: vizType,
                                    javascript: javascript,
                                    css: sassResults.css,
                                    path: path.resolve(req.query.path || ''),
                                    url: req.query.url,
                                    source: req.query.url ? 'gitRepo' : 'localFolder'
                                });
                            }
                        });
                    });
                });

        }).fail(function(err) {
            next(err);
        });

};

exports.previewNPM = function(req, res, next) {

    var location = req.params.location;
    var name = req.query.name;

    console.log('requested to link module: ' + name);

    var linker;
    if(location === 'registry') {
        linker = models.VisualizationType.linkFromNPM.bind(models.VisualizationType);
    } else if(location === 'local') {
        linker = models.VisualizationType.linkFromLocalModule.bind(models.VisualizationType);
    } else {
        return res.status(500).send('Invalid location.').end();
    }

    linker(name)
        .then(function(vizType) {
            var b = browserify();
            b.require(name);

            b.bundle(function(err, buf) {

                if(err) {
                    console.log(err);
                    return res.status(500).end();
                }

                var javascript = buf.toString('utf8');

                return res.render('viz-types/preview-editor', {
                    vizType: vizType,
                    javascript: javascript,
                    css: '',
                    location: location,
                    source: 'npm'
                });
            });
        }).catch(function(err) {
            console.log(err);
            return res.status(500).send('error compiling module').end();
        });
};

exports.importNPM = function(req, res, next) {

    var location = req.params.location;
    var name = req.query.name;

    console.log('requested to link module: ' + name);

    var creator;
    if(location === 'registry') {
        creator = models.VisualizationType.createFromNPM.bind(models.VisualizationType);
    } else if(location === 'local') {
        creator = models.VisualizationType.createFromLocalModule.bind(models.VisualizationType);
    } else {
        return res.status(500).send('Invalid location.').end();
    }

    creator(name)
        .then(function(vizType) {
            return res.redirect('/visualization-types/edit/' + vizType.id);
        }).catch(function(err) {
            console.log(err);
            return res.status(500).send('error compiling module').end();
        });
};

exports.importViz = function(req, res, next) {

    var name = req.body.name  || req.query.name;
    var url = req.body.url || req.query.url;
    var path = req.body.path || req.query.path;

    var createPromise;
    if(url) {
        createPromise = models.VisualizationType.createFromRepoURL(url, {name: name});
    } else if(path) {
        createPromise = models.VisualizationType.createFromFolder(path, {name: name}, {preview: false});
    } else {
        return res.status(500).send('Invalid location.').end();
    }

    createPromise
        .then(function(viz) {
            return res.redirect('/visualization-types/edit/' + viz.id);
        }).fail(function(err) {
            next(err);
        });
};

exports.advanced = function (req, res, next) {
    return res.render('viz-types/advanced', {});
};

exports.editor = function (req, res, next) {

    models.VisualizationType.find(req.params.vid)
        .then(function(type) {
            return res.render('viz-types/editor', {
                vizType: type
            });

        }).error(next);
};

exports.thumbnail = function (req, res, next) {

    models.VisualizationType.find(req.params.vid)
        .then(function(type) {
            if(type.thumbnailLocation) {
                return res.sendFile(type.thumbnailLocation);
            }

            return res.status(404).send('no thumbnail found').end();

        }).error(next);
};

exports.importPreviewHandler = function(req, res, next) {
    var method = req.params.method;
    var importPreview = req.params.importPreview;

    if(method === 'npm') {
        if(importPreview === 'import') {
            return exports.importNPM(req, res, next);
        } else {
            return exports.previewNPM(req, res, next);
        }
    } else if(method === 'git' || method === 'local') {
        if(importPreview === 'import') {
            return exports.importViz(req, res, next);
        } else {
            return exports.preview(req, res, next);
        }
    }

};
<commit_msg>more error handling around importing/previewing visualizations<commit_after>var models = require('../models');
var _ = require('lodash');
var cache = require('../cache');
var sass = require('node-sass');
var browserify = require('browserify');
var path = require('path');
var uuid = require('node-uuid');
var resumer = require('resumer');
var tasks = require('../../tasks');
var config = require('../../config/config');

exports.index = function (req, res, next) {

    models.VisualizationType.findAll()
        .then(function(types) {
            return res.json(types);
        }).error(next);
};

exports.show = function (req, res, next) {

    models.VisualizationType.findAll({
            order: '"name" ASC'
        })
        .then(function(types) {

            return res.render('viz-types/show', {
                vizTypes: types
            });

        }).error(next);
};

exports.resetDefaults = function(req, res, next) {

    console.log('resetting visualization defaults');

    models.VisualizationType
        .destroy({}, {truncate: true}).success(function() {
            console.log('successfully deleted current visualizations');
            tasks.getDefaultVisualizations(function() {
                return res.redirect(config.baseURL + 'visualization-types');
            });

        }).error(function(err) {
            console.log(err);
            return res.status(500).send();
        });
};

exports.fetchDefaults = function (req, res, next) {

    tasks.getDefaultVisualizations(function() {
        return res.redirect(config.baseURL + 'visualization-types');
    });
};

exports.create = function (req, res, next) {

    models.VisualizationType
        .create(_.pick(req.body, 'name', 'initialDataFields', 'isStreaming', 'javascript', 'styles', 'markup', 'sampleData', 'sampleOptions'))
        .then(function(type) {
            return res.json(type);
        }).catch(function(err) {
            return res.status(500).send(err);
        });

};

exports.edit = function (req, res, next) {

    models.VisualizationType
        .find(req.params.vid)
        .success(function(vizType) {
            return vizType.updateAttributes(_.pick(req.body, 'name', 'isStreaming', 'initialDataFields', 'javascript', 'styles', 'markup'));
        })
        .success(function(vizType) {
            setTimeout(function() {
                _.each(cache.keys(), function(key) {

                    console.log(key);
                    if(key.indexOf(vizType.name) > -1) {
                        console.log('deleting ' + key);
                        cache.del(key);
                    }
                });
            }, 0);
            return res.status(200).send();
        }).error(function() {
            return res.status(500).send();
        });
};

exports.delete = function (req, res, next) {

    var vizTypeId = req.params.vid;

    models.VisualizationType
        .find(vizTypeId)
        .then(function(vizType) {
            vizType.deleteAndUninstall().then(function() {
                return res.json(vizType);
            }).error(next);
        }).error(next);
};

exports.getDelete = function(req, res, next) {

    var vizTypeId = req.params.vid;

    models.VisualizationType
        .find(vizTypeId)
        .then(function(vizType) {
            vizType
                .deleteAndUninstall()
                .then(function() {
                    return res.redirect(config.baseURL + 'visualization-types/');
                }).catch(next);
        }).catch(next);
};

exports.preview = function(req, res, next) {

    var tmpPath = path.resolve(__dirname + '/../../tmp/js-build/' + uuid.v4() + '/');
    req.session.lastBundlePath = tmpPath;

    var vizTypePromise, name;

    if(req.query.url) {
        var url = req.query.url;
        name = url;
        if(req.query.path) {
            name += '/' + req.query.path;
        }

        name = req.query.name || /[^/]*$/.exec(name)[0];

        vizTypePromise = models.VisualizationType
            .createFromRepoURL(url, { name: name }, {preview: true, path: req.query.path});
    } else if(req.query.path && process.env.NODE_ENV !== 'production') {
        var p = path.resolve(req.query.path);
        name = req.query.name || /[^/]*$/.exec(p)[0];

        vizTypePromise = models.VisualizationType
            .createFromFolder(p, { name: name}, {preview: true});
    }

    vizTypePromise
        .then(function(vizType) {

            console.log('created viz preview');

            vizType.exportToFS(tmpPath)
                .spread(function() {
                    var b = browserify();
                    if(vizType.isModule) {
                        b.require(vizType.moduleName, {
                            expose: vizType.moduleName
                        });
                    } else {
                        var stream = resumer().queue(vizType.javascript).end();
                        b.require(stream, {
                            basedir: tmpPath,
                            expose: vizType.name
                        });
                    }

                    b.bundle(function(err, buf) {

                        if(err) {
                            return next(err);
                        }

                        var javascript = buf.toString('utf8');
                        var scssData = '#lightning-body {\n';
                        if(vizType.styles) {
                            scssData += vizType.styles + '\n';
                        }
                        scssData += '\n}';
                        sass.render({
                            data: scssData,
                            success: function(sassResults) {
                                if(req.url.indexOf('/preview/full') > -1) {
                                    return res.render('viz-types/full-preview', {
                                        vizType: vizType,
                                        javascript: javascript,
                                        css: sassResults.css,
                                        path: path.resolve(req.query.path || ''),
                                        url: req.query.url,
                                        source: req.query.url ? 'gitRepo' : 'localFolder'
                                    });
                                }
                                return res.render('viz-types/preview-editor', {
                                    vizType: vizType,
                                    javascript: javascript,
                                    css: sassResults.css,
                                    path: path.resolve(req.query.path || ''),
                                    url: req.query.url,
                                    source: req.query.url ? 'gitRepo' : 'localFolder'
                                });
                            }
                        });
                    });
                });

        }).fail(function(err) {
            next(err);
        });

};

exports.previewNPM = function(req, res, next) {

    var location = req.params.location;
    var name = req.query.name;

    console.log('requested to link module: ' + name);

    models.VisualizationType
        .findAll({
            where: {
                moduleName: name
            }
        }).then(function(visualizations) {
            if(visualizations && visualizations.length) {
                throw new Error('Please delete the installed ' + visualizations[0].name + ' visualization before trying to preview ' + name);
            }

            var linker;
            if(location === 'registry') {
                linker = models.VisualizationType.linkFromNPM.bind(models.VisualizationType);
            } else if(location === 'local') {
                linker = models.VisualizationType.linkFromLocalModule.bind(models.VisualizationType);
            } else {
                return res.status(500).send('Invalid location.').end();
            }

            return linker(name);
        }).then(function(vizType) {
            var b = browserify();
            b.require(name);

            b.bundle(function(err, buf) {

                if(err) {
                    console.log(err);
                    return res.status(500).end();
                }

                var javascript = buf.toString('utf8');

                return res.render('viz-types/preview-editor', {
                    vizType: vizType,
                    javascript: javascript,
                    css: '',
                    location: location,
                    source: 'npm'
                });
            });
        }).catch(function(err) {
            return res.status(500).send(err.message).end();
        });
};

exports.importNPM = function(req, res, next) {

    var location = req.params.location;
    var name = req.query.name;

    console.log('requested to link module: ' + name);

    models.VisualizationType
        .findAll({
            where: {
                moduleName: name
            }
        }).then(function(visualizations) {
            if(visualizations && visualizations.length) {
                throw new Error('Please delete the installed ' + visualizations[0].name + ' visualization before trying to install ' + name);
            }
            var creator;
            if(location === 'registry') {
                creator = models.VisualizationType.createFromNPM.bind(models.VisualizationType);
            } else if(location === 'local') {
                creator = models.VisualizationType.createFromLocalModule.bind(models.VisualizationType);
            } else {
                return res.status(500).send('Invalid location.').end();
            }

            return creator(name);
        }).then(function(vizType) {
            return res.redirect('/visualization-types/edit/' + vizType.id);
        }).catch(function(err) {
            return res.status(500).send(err.message).end();
        });
};

exports.importViz = function(req, res, next) {

    var name = req.body.name  || req.query.name;
    var url = req.body.url || req.query.url;
    var path = req.body.path || req.query.path;

    var createPromise;
    if(url) {
        createPromise = models.VisualizationType.createFromRepoURL(url, {name: name});
    } else if(path) {
        createPromise = models.VisualizationType.createFromFolder(path, {name: name}, {preview: false});
    } else {
        return res.status(500).send('Invalid location.').end();
    }

    createPromise
        .then(function(viz) {
            return res.redirect('/visualization-types/edit/' + viz.id);
        }).fail(function(err) {
            next(err);
        });
};

exports.advanced = function (req, res, next) {
    return res.render('viz-types/advanced', {});
};

exports.editor = function (req, res, next) {

    models.VisualizationType.find(req.params.vid)
        .then(function(type) {
            return res.render('viz-types/editor', {
                vizType: type
            });

        }).error(next);
};

exports.thumbnail = function (req, res, next) {

    models.VisualizationType.find(req.params.vid)
        .then(function(type) {
            if(type.thumbnailLocation) {
                return res.sendFile(type.thumbnailLocation);
            }

            return res.status(404).send('no thumbnail found').end();

        }).error(next);
};

exports.importPreviewHandler = function(req, res, next) {
    var method = req.params.method;
    var importPreview = req.params.importPreview;

    if(method === 'npm') {
        if(importPreview === 'import') {
            return exports.importNPM(req, res, next);
        } else {
            return exports.previewNPM(req, res, next);
        }
    } else if(method === 'git' || method === 'local') {
        if(importPreview === 'import') {
            return exports.importViz(req, res, next);
        } else {
            return exports.preview(req, res, next);
        }
    }

};
<|endoftext|>


<commit_before>"use strict";

angular.module('arethusa.core').service('arethusaGrid', [
  'gridsterConfig',
  '$window',
  function(gridsterConfig, $window) {
    var self = this;

    var win = angular.element($window);

    this.settings = {
      dragging: true,
      resizing: true,
      pushing:  true,
      floating: true,
    };

    this.setDragging = function(val) { self.options.draggable.enabled = val; };
    this.setResizing = function(val) { self.options.resizable.enabled = val; };
    this.setPushing  = function(val) { self.options.pushing  = val; };
    this.setFloating = function(val) { self.options.floating = val; };

    this.options = angular.extend(gridsterConfig, {
      columns: 20,
      rowHeight: 'match',
      resizable: {
        enabled: true,
        handles: ['n', 'e', 's', 'w', 'ne', 'nw', 'se', 'sw'],
        stop: function() { win.trigger('resize'); }
      }
    });

    function Item(size, position, plugin, style) {
      return {
        sizeX: size[0],
        sizeY: size[1],
        row: position[0],
        col: position[1],
        plugin: plugin,
        style: style
      };
    }

    this.items = [
      new Item([14, 1], [0, 0], 'text'),
      new Item([9, 8],  [2, 0], 'depTree', { overflow: 'hidden'} ),
      new Item([5, 8],  [1, 9], 'comments'),
      new Item([6, 2],  [0, 14], 'search'),
      new Item([6, 4],  [2, 14], 'morph'),
      new Item([6, 3],  [7, 14], 'relation')
    ];
  }
]);
<commit_msg>Gather itemList in grid when plugins are loaded<commit_after>"use strict";

angular.module('arethusa.core').service('arethusaGrid', [
  'gridsterConfig',
  '$window',
  'plugins',
  '$rootScope',
  function(gridsterConfig, $window, plugins, $rootScope) {
    var self = this;

    var win = angular.element($window);

    this.settings = {
      dragging: true,
      resizing: true,
      pushing:  true,
      floating: true,
    };

    this.setDragging = function(val) { self.options.draggable.enabled = val; };
    this.setResizing = function(val) { self.options.resizable.enabled = val; };
    this.setPushing  = function(val) { self.options.pushing  = val; };
    this.setFloating = function(val) { self.options.floating = val; };

    this.options = angular.extend(gridsterConfig, {
      columns: 20,
      rowHeight: 'match',
      resizable: {
        enabled: true,
        handles: ['n', 'e', 's', 'w', 'ne', 'nw', 'se', 'sw'],
        stop: function() { win.trigger('resize'); }
      }
    });

    function Item(size, position, plugin, style) {
      return {
        sizeX: size[0],
        sizeY: size[1],
        row: position[0],
        col: position[1],
        plugin: plugin,
        style: style
      };
    }

    this.items = [
      new Item([14, 1], [0, 0], 'text'),
      new Item([9, 8],  [2, 0], 'depTree', { overflow: 'hidden'} ),
      new Item([5, 8],  [1, 9], 'comments'),
      new Item([6, 2],  [0, 14], 'search'),
      new Item([6, 4],  [2, 14], 'morph'),
      new Item([6, 3],  [7, 14], 'relation')
    ];

    this.init = function() {
      self.itemList = arethusaUtil.inject({}, plugins.all, function(memo, name, pl) {
        memo[name] = false;
      });

      angular.forEach(self.items, function(el, i) {
        self.itemList[el.plugin] = true;
      });
    };

    $rootScope.$on('pluginsLoaded', self.init);
  }
]);
<|endoftext|>


<commit_before>'use strict';
/*
 *
 */
angular.module('arethusa').factory('TreebankPersister', [
  'documentStore',
  'configurator',
  'navigator',
  function (documentStore, configurator, navigator) {
    return function(conf) {
      var resource = configurator.provideResource(conf.resource);

      function updateXml() {
        var doc = documentStore.store[conf.docIdentifier];
        doc.xml = arethusaUtil.json2xml(doc.json);
      }

      function updateWord(word, stateWord) {
            word._head = arethusaUtil.formatNumber(stateWord.head.id, 0);
            word._relation = stateWord.relation.label;
            word._lemma = stateWord.morphology.lemma;
            word._postag = stateWord.morphology.postag;
            word._form = stateWord.string;
      }

      function updateDocument() {
        var doc = documentStore.store[conf.docIdentifier];
        var stored = arethusaUtil.toAry(doc.json.treebank.sentence);
        // navigator has to provide means to retrieve sentences by id
        // and not only through a flat array!
        var sentences = navigator.sentencesById;

        angular.forEach(stored, function(sentence, i) {
          var updated = sentences[sentence._id];
          angular.forEach(sentence.word, function(word, i) {
            var stateWord = updated.tokens[arethusaUtil.formatNumber(word._id, 4)];
            updateWord(word, stateWord);
          });
        });
      }

      this.saveData = function(callback) {
        updateDocument();
        updateXml();

        callback();
      };
    };
  }
]);

<commit_msg>Minor formatting<commit_after>'use strict';
/*
 *
 */
angular.module('arethusa').factory('TreebankPersister', [
  'documentStore',
  'configurator',
  'navigator',
  function (documentStore, configurator, navigator) {
    return function(conf) {
      var resource = configurator.provideResource(conf.resource);

      function updateXml() {
        var doc = documentStore.store[conf.docIdentifier];
        doc.xml = arethusaUtil.json2xml(doc.json);
      }

      function updateWord(word, stateWord) {
        word._head = arethusaUtil.formatNumber(stateWord.head.id, 0);
        word._relation = stateWord.relation.label;
        word._lemma = stateWord.morphology.lemma;
        word._postag = stateWord.morphology.postag;
        word._form = stateWord.string;
      }

      function updateDocument() {
        var doc = documentStore.store[conf.docIdentifier];
        var stored = arethusaUtil.toAry(doc.json.treebank.sentence);
        // navigator has to provide means to retrieve sentences by id
        // and not only through a flat array!
        var sentences = navigator.sentencesById;

        angular.forEach(stored, function(sentence, i) {
          var updated = sentences[sentence._id];
          angular.forEach(sentence.word, function(word, i) {
            var stateWord = updated.tokens[arethusaUtil.formatNumber(word._id, 4)];
            updateWord(word, stateWord);
          });
        });
      }

      this.saveData = function(callback) {
        updateDocument();
        updateXml();

        callback();
      };
    };
  }
]);

<|endoftext|>


<commit_before>import { app } from 'electron'

/**
 * Show or hide main window
 * @return {BrowserWindow} appWindow
 */
export default (appWindow) => {
  if (appWindow.isVisible()) {
    appWindow.hide()
    app.hide()
  } else {
    appWindow.show()
    appWindow.focus()
  }
}
<commit_msg>Fix no method error for `app.hide()` on Linux and Windows<commit_after>import { app } from 'electron'

/**
 * Show or hide main window
 * @return {BrowserWindow} appWindow
 */
export default (appWindow) => {
  if (appWindow.isVisible()) {
    appWindow.hide()
    if (process.platform === 'darwin') {
      // Restore focus in previous application
      // MacOS only: https://github.com/electron/electron/blob/master/docs/api/app.md#apphide-macos
      app.hide()
    }
  } else {
    appWindow.show()
    appWindow.focus()
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function(sequelize, DataTypes){

    var USER = sequelize.define('user', {
          NAME  : DataTypes.STRING
        , EMAIL : {
              type: DataTypes.STRING
            , allowNull : false
            , unique    : true
            , validate  : {
                isEmail : {
                    msg : 'Email is not valid'
                }
            }
        }
        , PASSWORD : {
              type: DataTypes.STRING
            , allowNull : false
        }
        , TOKEN        : DataTypes.STRING
        , RESETTOKEN   : DataTypes.STRING
        , RESETEXPIRES : DataTypes.DATE
    }, {
        classMethods  : {
            associate : function(models){
                USER.hasMany(models.job_request, {
                    foreignKey    : {
                        name      : 'JOB_ID'
                      , allowNull : true
                      }
                });
                USER.hasMany(models.job, {
                    onDelete    : 'cascade'
                  , foreignKey  : {
                      name      : 'USER_ID'
                    , allowNull : false
                    }
                });
                USER.belongsTo(models.user_status, { foreignKey : 'USER_STATUS' });
            }
      }
    });

    return USER;
}
<commit_msg>added foreign key user id to organization<commit_after>'use strict';

module.exports = function(sequelize, DataTypes){

    var USER = sequelize.define('user', {
          NAME  : DataTypes.STRING
        , EMAIL : {
              type: DataTypes.STRING
            , allowNull : false
            , unique    : true
            , validate  : {
                isEmail : {
                    msg : 'Email is not valid'
                }
            }
        }
        , PASSWORD : {
              type: DataTypes.STRING
            , allowNull : false
        }
        , TOKEN        : DataTypes.STRING
        , RESETTOKEN   : DataTypes.STRING
        , RESETEXPIRES : DataTypes.DATE
    }, {
        classMethods  : {
            associate : function(models){
                USER.hasMany(models.job_request, {
                    foreignKey    : {
                        name      : 'JOB_ID'
                      , allowNull : true
                      }
                });
                USER.hasMany(models.org, {
                    foreignKey    : {
                        name      : 'USER_ID'
                      , allowNull : false
                    }
                });
                USER.hasMany(models.job, {
                    onDelete    : 'cascade'
                  , foreignKey  : {
                      name      : 'USER_ID'
                    , allowNull : false
                    }
                });
                USER.belongsTo(models.user_status, { foreignKey : 'USER_STATUS' });
            }
      }
    });

    return USER;
}
<|endoftext|>


<commit_before>// vi:si:et:sw=2:sts=2:ts=2
/**
 * @ngdoc     controller
 * @name      mushin.controller:NumberListController
 * @requires  $scope
 *
 * @description
The number list controller controls the number list
 *              directive for importance and urgency,
 *            allowing the user to choose any (or all) numbers.

 *
 *
The controller should be initialized with the following
 *               tags:
 *

 *
type

'project' or 'context'

 *
all

 *
true or false;
 *                     whether to allow selecting all tags

 *
data

the parent scope's variable that contains the hash of tags

 *
active

the parent scope's variable that contains the hash of tag selection; the controller will manipulate .active

 *

 *

 *
 *
A parent scope should provide the following members:
 *

 *
'projects' or 'contexts'

 *
depending on the type

 *

 *

 *
 * @author    Thomas Vander Stichele <thomas (at) apestaart (dot) org>
 */
angular.module('mushin').controller(
  'NumberListController',
  function($scope, $attrs) {

    var debug = new window.$debug('mushin:controllers/numberlist');

    /* projects or contexts */
    if ($attrs.type === undefined) {
      throw new Error("No type attribute for NumberListController");
    }
    $scope.type = $attrs.type;
    $scope.typeletter = $scope.type.toUpperCase().charAt(0);

    /* whether to show the All ... header */
    if ($attrs.all === undefined) {
      throw new Error("No all attribute " + JSON.stringify($attrs) + " for NumberListController");
    } else {
      /* convert string to boolean */
      $scope.showAll = ($attrs.all == 'true');
    }

    if ($attrs.data === undefined) {
      throw new Error("No data attribute for NumberListController for " +
        $scope.type);
    }
    $scope.tags = $scope[$attrs.data];

    if ($attrs.active === undefined) {
      throw new Error("No active attribute for NumberListController for " +
        $scope.type);
    }
    $scope.active = $scope[$attrs.active];

    if ($attrs.multiple === undefined) {
      throw new Error("No multiple attribute for NumberListController for " +
        $scope.type);
    }
    $scope.multiple = ($attrs.multiple == 'true');

    $scope.open = false;

    debug('new NumberListController of type ' + $scope.type +
      ' with attrs ' + JSON.stringify($attrs));

    $scope.selectedAll = true;

    $scope.isType = function(type) {
      return type == $scope.type;
    }

    /**
     * @ngdoc    method
     * @name     mushin.controller:NumberListController#toggle
     * @methodOf mushin.controller:NumberListController
     * @param    {string} name the one-character 'name' of the
     *                         number to toggle.
     *
     * @description
     *
     * Toggle the selection state of the number.
     * Will emit NUMBER_TOGGLED with urgency/importance and a string
     * representation of the number toggled.
     */
    $scope.toggle = function(name) {
      var all = true;

      if (!(name in $scope.active)) {
          $scope.active[name] = {
              'active': false
          };
      }
      // activating one resets the others if not multiple
      if (!$scope.multiple && !$scope.active[name].active) {
        $scope.clear();
      }
      $scope.active[name].active = !$scope.active[name].active;
      $scope.$emit('NUMBER_TOGGLED', $scope.type, name);

      for (var key in $scope.active) {
        if ($scope.active[key].active) { all = false; }
      }
      if ($scope.selectedAll != all) {
        $scope.selectedAll = all;
      }
//      debug('active: ' + JSON.stringify($scope.active));
    }

    /**
     * @ngdoc    method
     * @name     mushin.controller:NumberListController#clear
     * @methodOf mushin.controller:NumberListController
     *
     * @description
     *
     * Clear the selection state of all numbers, and set selectedAll.
     */
    $scope.clear = function() {
      for (var key in $scope.active) {
        $scope.active[key].active = false;
      }
      $scope.selectedAll = true;
    }

    /* FIXME: this looks unused anywhere; remove? */
    /**
     * @ngdoc    method
     * @name     mushin.controller:NumberListController#filterByTag
     * @methodOf mushin.controller:NumberListController
     *
     * @description
     *
     * Filter the given thing by the current selection state.
     *
     * @param {object} thing the thing to filter
     */
    $scope.filterByNumber = function(thing) {
      debug('filterByNumber ' + thing);

      if ($scope.selectedAll) {
        return true;
      }

      for (var key in $scope.tags) {
        if ($scope.active[key].active) {
          return true;
        }
      }

      return false;
    }

  }
);
<commit_msg>fix debug that was breaking filter<commit_after>// vi:si:et:sw=2:sts=2:ts=2
/**
 * @ngdoc     controller
 * @name      mushin.controller:NumberListController
 * @requires  $scope
 *
 * @description
The number list controller controls the number list
 *              directive for importance and urgency,
 *            allowing the user to choose any (or all) numbers.

 *
 *
The controller should be initialized with the following
 *               tags:
 *

 *
type

'project' or 'context'

 *
all

 *
true or false;
 *                     whether to allow selecting all tags

 *
data

the parent scope's variable that contains the hash of tags

 *
active

the parent scope's variable that contains the hash of tag selection; the controller will manipulate .active

 *

 *

 *
 *
A parent scope should provide the following members:
 *

 *
'projects' or 'contexts'

 *
depending on the type

 *

 *

 *
 * @author    Thomas Vander Stichele <thomas (at) apestaart (dot) org>
 */
angular.module('mushin').controller(
  'NumberListController',
  function($scope, $attrs) {

    var debug = new window.$debug('mushin:controllers/numberlist');

    /* projects or contexts */
    if ($attrs.type === undefined) {
      throw new Error("No type attribute for NumberListController");
    }
    $scope.type = $attrs.type;
    $scope.typeletter = $scope.type.toUpperCase().charAt(0);

    /* whether to show the All ... header */
    if ($attrs.all === undefined) {
      throw new Error("No all attribute " + JSON.stringify($attrs) + " for NumberListController");
    } else {
      /* convert string to boolean */
      $scope.showAll = ($attrs.all == 'true');
    }

    if ($attrs.data === undefined) {
      throw new Error("No data attribute for NumberListController for " +
        $scope.type);
    }
    $scope.tags = $scope[$attrs.data];

    if ($attrs.active === undefined) {
      throw new Error("No active attribute for NumberListController for " +
        $scope.type);
    }
    $scope.active = $scope[$attrs.active];

    if ($attrs.multiple === undefined) {
      throw new Error("No multiple attribute for NumberListController for " +
        $scope.type);
    }
    $scope.multiple = ($attrs.multiple == 'true');

    $scope.open = false;

    debug('new NumberListController of type ' + $scope.type);
    // FIXME: can't do this; circular attrs
    // ' with attrs ' + JSON.stringify($attrs));

    $scope.selectedAll = true;

    $scope.isType = function(type) {
      return type == $scope.type;
    }

    /**
     * @ngdoc    method
     * @name     mushin.controller:NumberListController#toggle
     * @methodOf mushin.controller:NumberListController
     * @param    {string} name the one-character 'name' of the
     *                         number to toggle.
     *
     * @description
     *
     * Toggle the selection state of the number.
     * Will emit NUMBER_TOGGLED with urgency/importance and a string
     * representation of the number toggled.
     */
    $scope.toggle = function(name) {
      var all = true;

      if (!(name in $scope.active)) {
          $scope.active[name] = {
              'active': false
          };
      }
      // activating one resets the others if not multiple
      if (!$scope.multiple && !$scope.active[name].active) {
        $scope.clear();
      }
      $scope.active[name].active = !$scope.active[name].active;
      $scope.$emit('NUMBER_TOGGLED', $scope.type, name);

      for (var key in $scope.active) {
        if ($scope.active[key].active) { all = false; }
      }
      if ($scope.selectedAll != all) {
        $scope.selectedAll = all;
      }
//      debug('active: ' + JSON.stringify($scope.active));
    }

    /**
     * @ngdoc    method
     * @name     mushin.controller:NumberListController#clear
     * @methodOf mushin.controller:NumberListController
     *
     * @description
     *
     * Clear the selection state of all numbers, and set selectedAll.
     */
    $scope.clear = function() {
      for (var key in $scope.active) {
        $scope.active[key].active = false;
      }
      $scope.selectedAll = true;
    }

    /* FIXME: this looks unused anywhere; remove? */
    /**
     * @ngdoc    method
     * @name     mushin.controller:NumberListController#filterByTag
     * @methodOf mushin.controller:NumberListController
     *
     * @description
     *
     * Filter the given thing by the current selection state.
     *
     * @param {object} thing the thing to filter
     */
    $scope.filterByNumber = function(thing) {
      debug('filterByNumber ' + thing);

      if ($scope.selectedAll) {
        return true;
      }

      for (var key in $scope.tags) {
        if ($scope.active[key].active) {
          return true;
        }
      }

      return false;
    }

  }
);
<|endoftext|>


<commit_before>'use strict';

var angular = require('angular');

angular.module('deckApp')
  .controller('SortToggleCtrl', function($scope) {
    var ctrl = this;

    if (angular.isObject($scope.$parent.sortModel)) {
      $scope.model = $scope.$parent.sortModel;
    } else {
      $scope.model = {
        reverse: false,
      };
      $scope.$parent.sortModel = $scope.model;
    }

    if ($scope.default === 'true') {
      $scope.model.sortKey = $scope.key;
    }

    ctrl.setSortKey = function (key) {
      $scope.model.sortKey = key;
      $scope.model.reverse = ctrl.isSortKey(key) ? !$scope.model.reverse : false;
      console.log(key, $scope.model, $scope.$parent.sortModel);
    };

    ctrl.isSortKey = function (key) {
      return $scope.$parent.sortModel.sortKey === key;
    };

  });
<commit_msg>remove errant log<commit_after>'use strict';

var angular = require('angular');

angular.module('deckApp')
  .controller('SortToggleCtrl', function($scope) {
    var ctrl = this;

    if (angular.isObject($scope.$parent.sortModel)) {
      $scope.model = $scope.$parent.sortModel;
    } else {
      $scope.model = {
        reverse: false,
      };
      $scope.$parent.sortModel = $scope.model;
    }

    if ($scope.default === 'true') {
      $scope.model.sortKey = $scope.key;
    }

    ctrl.setSortKey = function (key) {
      $scope.model.sortKey = key;
      $scope.model.reverse = ctrl.isSortKey(key) ? !$scope.model.reverse : false;
    };

    ctrl.isSortKey = function (key) {
      return $scope.$parent.sortModel.sortKey === key;
    };

  });
<|endoftext|>


<commit_before>var BasemapFormModel = require('../../../../../../javascripts/cartodb3/editor/layers/basemap-content-views/basemap-form-model');
var BasemapsCollection = require('../../../../../../javascripts/cartodb3/editor/layers/basemap-content-views/basemaps-collection');
var LayerDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/layer-definitions-collection');
var AnalysisDefinitionNodesCollection = require('../../../../../../javascripts/cartodb3/data/analysis-definition-nodes-collection');
var ConfigModel = require('../../../../../../javascripts/cartodb3/data/config-model');
var _ = require('underscore');

describe('editor/layers/basemap-content-views/basemap-form-model', function () {
  beforeEach(function () {
    spyOn(_, 'debounce').and.callFake(function (func) {
      return function () {
        func.apply(this, arguments);
      };
    });

    var configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.analysisDefinitionNodesCollection = new AnalysisDefinitionNodesCollection(null, {
      configModel: configModel
    });

    this.layerDefinitionsCollection = new LayerDefinitionsCollection(null, {
      configModel: configModel,
      analysisDefinitionNodesCollection: this.analysisDefinitionNodesCollection,
      mapId: 'm-123'
    });
    this.layerDefinitionsCollection.add({
      id: 'l-1',
      kind: 'carto',
      options: {
        table_name: 'foo'
      }
    });
    this.basemapsCollection = new BasemapsCollection();
    this.basemapsCollection.add({
      default: false,
      color: '#35AAE5',
      image: '',
      maxZoom: 32,
      className: 'plain',
      category: 'Color',
      type: 'Plain',
      selected: true,
      val: 'plain',
      label: 'plain',
      template: 'plain'
    });

    this.formModel = new BasemapFormModel({
      color: {
        color: {
          fixed: '#35AAE5',
          opacity: 1
        }
      },
      image: ''
    }, {
      basemapsCollection: this.basemapsCollection,
      layerDefinitionsCollection: this.layerDefinitionsCollection
    });

    spyOn(this.formModel._basemapsCollection, 'updateSelected');
    spyOn(this.formModel._layerDefinitionsCollection, 'setBaseLayer');
  });

  describe('when form data changes', function () {
    beforeEach(function () {
      this.formModel.set('color', {
        color: {
          fixed: '#FABADA',
          opacity: 1
        }
      });
    });

    it('should save changes', function () {
      expect(this.formModel._basemapsCollection.updateSelected).toHaveBeenCalledWith('plain');
      expect(this.formModel._layerDefinitionsCollection.setBaseLayer).toHaveBeenCalledWith({
        default: false,
        color: '#FABADA',
        image: '',
        maxZoom: 32,
        className: 'plain',
        category: 'Color',
        type: 'Plain',
        selected: true,
        val: 'plain',
        label: 'plain',
        template: 'plain',
        id: null,
        urlTemplate: '',
        subdomains: '',
        minZoom: 0,
        name: '',
        attribution: null,
        labels: null
      });
    });
  });
});
<commit_msg>Fixing test<commit_after>var BasemapFormModel = require('../../../../../../javascripts/cartodb3/editor/layers/basemap-content-views/basemap-form-model');
var BasemapsCollection = require('../../../../../../javascripts/cartodb3/editor/layers/basemap-content-views/basemaps-collection');
var LayerDefinitionsCollection = require('../../../../../../javascripts/cartodb3/data/layer-definitions-collection');
var AnalysisDefinitionNodesCollection = require('../../../../../../javascripts/cartodb3/data/analysis-definition-nodes-collection');
var ConfigModel = require('../../../../../../javascripts/cartodb3/data/config-model');
var _ = require('underscore');

describe('editor/layers/basemap-content-views/basemap-form-model', function () {
  beforeEach(function () {
    spyOn(_, 'debounce').and.callFake(function (func) {
      return function () {
        func.apply(this, arguments);
      };
    });

    var configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.analysisDefinitionNodesCollection = new AnalysisDefinitionNodesCollection(null, {
      configModel: configModel
    });

    this.layerDefinitionsCollection = new LayerDefinitionsCollection(null, {
      configModel: configModel,
      analysisDefinitionNodesCollection: this.analysisDefinitionNodesCollection,
      mapId: 'm-123'
    });
    this.layerDefinitionsCollection.add({
      id: 'l-1',
      kind: 'carto',
      options: {
        table_name: 'foo'
      }
    });
    this.basemapsCollection = new BasemapsCollection();
    this.basemapsCollection.add({
      default: false,
      color: '#35AAE5',
      image: '',
      maxZoom: 32,
      className: 'plain',
      category: 'Color',
      type: 'Plain',
      selected: true,
      val: 'plain',
      label: 'plain',
      template: 'plain'
    });

    this.formModel = new BasemapFormModel({
      color: {
        color: {
          fixed: '#35AAE5',
          opacity: 1
        }
      },
      image: ''
    }, {
      basemapsCollection: this.basemapsCollection,
      layerDefinitionsCollection: this.layerDefinitionsCollection
    });

    spyOn(this.formModel._basemapsCollection, 'updateSelected');
    spyOn(this.formModel._layerDefinitionsCollection, 'setBaseLayer');
  });

  describe('when form data changes', function () {
    beforeEach(function () {
      this.formModel.set('color', {
        color: {
          fixed: '#FABADA',
          opacity: 1
        }
      });
    });

    it('should save changes', function () {
      expect(this.formModel._basemapsCollection.updateSelected).toHaveBeenCalledWith('plain');
      expect(this.formModel._layerDefinitionsCollection.setBaseLayer).toHaveBeenCalledWith({
        default: false,
        color: '#FABADA',
        image: '',
        maxZoom: 32,
        className: 'plain',
        category: 'Color',
        type: 'Plain',
        selected: true,
        val: 'plain',
        label: 'plain',
        template: 'plain',
        id: null,
        urlTemplate: '',
        subdomains: '',
        minZoom: 0,
        name: '',
        attribution: null,
        labels: null,
        tms: false
      });
    });
  });
});
<|endoftext|>


<commit_before>import {Form} from 'widget/form/form'
import {Layout} from 'widget/layout'
import {Panel} from 'widget/panel/panel'
import {RecipeActions} from '../../timeSeriesRecipe'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {compose} from 'compose'
import {msg} from 'translate'
import {selectFrom} from 'stateUtils'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import styles from './retrieve.module.css'

const fields = {
    indicator: new Form.Field()
        .notEmpty('process.timeSeries.panel.retrieve.form.indicator.required'),
    scale: new Form.Field(),
}

const mapRecipeToProps = recipe => ({
    sources: selectFrom(recipe, 'model.sources')
})

class Retrieve extends React.Component {
    constructor(props) {
        super(props)
        const {recipeId, inputs: {scale}} = this.props
        this.recipeActions = RecipeActions(recipeId)
        if (!scale.value)
            scale.set(30)
    }

    renderContent() {
        const {sources, inputs: {indicator, scale}} = this.props
        const indicatorOptions = _.isEmpty(sources['SENTINEL_1'])
            ? [
                {value: 'ndvi', label: 'NDVI', tooltip: '(nir - red) / (nir + red)'},
                {value: 'ndmi', label: 'NDMI', tooltip: '(nir - swir1) / (nir + swir1)'},
                {value: 'ndwi', label: 'NDWI', tooltip: '(green - nir) / (green + nir)'},
                {value: 'ndfi', label: 'NDFI', tooltip: 'Normalized Difference Fraction Index'},
                {value: 'nbr', label: 'NBR', tooltip: '(nir - swir2) / (nir + swir2)'},
                {value: 'evi', label: 'EVI', tooltip: '2.5 * (nir - red) / (nir + 6 * red - 7.5 * blue + 1)'},
                {value: 'evi2', label: 'EVI2', tooltip: '2.5 * (nir - red) / (nir + 2.4 * red + 1)'},
                {value: 'savi', label: 'SAVI', tooltip: '(1.5 * (nir - red) / (nir + red + 0.5)'}
            ]
            : [
                {value: 'VV', label: 'VV'},
                {value: 'VH', label: 'VH'},
                {value: 'VV/VH', label: 'VV/VH'}
            ]

        return (
            <Layout>
                <Form.Buttons
                    label={msg('process.timeSeries.panel.retrieve.form.indicator.label')}
                    input={indicator}
                    multiple={false}
                    options={indicatorOptions}/>
                <Form.Slider
                    label={msg('process.radarMosaic.panel.retrieve.form.scale.label')}
                    info={scale => msg('process.timeSeries.panel.retrieve.form.scale.info', {scale})}
                    input={scale}
                    minValue={10}
                    maxValue={100}
                    scale={'log'}
                    ticks={[10, 15, 20, 30, 60, 100]}
                    snap
                    range='none'
                />
            </Layout>
        )
    }

    render() {
        return (
            <RecipeFormPanel
                className={styles.panel}
                isActionForm
                placement='top-right'
                onApply={values => this.recipeActions.retrieve(values).dispatch()}>
                <Panel.Header
                    icon='cloud-download-alt'
                    title={msg('process.timeSeries.panel.retrieve.title')}/>
                <Panel.Content>
                    {this.renderContent()}
                </Panel.Content>
                <Form.PanelButtons
                    applyLabel={msg('process.timeSeries.panel.retrieve.apply')}/>
            </RecipeFormPanel>
        )
    }
}

Retrieve.propTypes = {
    recipeId: PropTypes.string
}

export default compose(
    Retrieve,
    recipeFormPanel({id: 'retrieve', fields, mapRecipeToProps})
)
<commit_msg>Corrected S1 band ratio band name.<commit_after>import {Form} from 'widget/form/form'
import {Layout} from 'widget/layout'
import {Panel} from 'widget/panel/panel'
import {RecipeActions} from '../../timeSeriesRecipe'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {compose} from 'compose'
import {msg} from 'translate'
import {selectFrom} from 'stateUtils'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import styles from './retrieve.module.css'

const fields = {
    indicator: new Form.Field()
        .notEmpty('process.timeSeries.panel.retrieve.form.indicator.required'),
    scale: new Form.Field(),
}

const mapRecipeToProps = recipe => ({
    sources: selectFrom(recipe, 'model.sources')
})

class Retrieve extends React.Component {
    constructor(props) {
        super(props)
        const {recipeId, inputs: {scale}} = this.props
        this.recipeActions = RecipeActions(recipeId)
        if (!scale.value)
            scale.set(30)
    }

    renderContent() {
        const {sources, inputs: {indicator, scale}} = this.props
        const indicatorOptions = _.isEmpty(sources['SENTINEL_1'])
            ? [
                {value: 'ndvi', label: 'NDVI', tooltip: '(nir - red) / (nir + red)'},
                {value: 'ndmi', label: 'NDMI', tooltip: '(nir - swir1) / (nir + swir1)'},
                {value: 'ndwi', label: 'NDWI', tooltip: '(green - nir) / (green + nir)'},
                {value: 'ndfi', label: 'NDFI', tooltip: 'Normalized Difference Fraction Index'},
                {value: 'nbr', label: 'NBR', tooltip: '(nir - swir2) / (nir + swir2)'},
                {value: 'evi', label: 'EVI', tooltip: '2.5 * (nir - red) / (nir + 6 * red - 7.5 * blue + 1)'},
                {value: 'evi2', label: 'EVI2', tooltip: '2.5 * (nir - red) / (nir + 2.4 * red + 1)'},
                {value: 'savi', label: 'SAVI', tooltip: '(1.5 * (nir - red) / (nir + red + 0.5)'}
            ]
            : [
                {value: 'VV', label: 'VV'},
                {value: 'VH', label: 'VH'},
                {value: 'ratio_VV_VH', label: 'VV/VH'}
            ]

        return (
            <Layout>
                <Form.Buttons
                    label={msg('process.timeSeries.panel.retrieve.form.indicator.label')}
                    input={indicator}
                    multiple={false}
                    options={indicatorOptions}/>
                <Form.Slider
                    label={msg('process.radarMosaic.panel.retrieve.form.scale.label')}
                    info={scale => msg('process.timeSeries.panel.retrieve.form.scale.info', {scale})}
                    input={scale}
                    minValue={10}
                    maxValue={100}
                    scale={'log'}
                    ticks={[10, 15, 20, 30, 60, 100]}
                    snap
                    range='none'
                />
            </Layout>
        )
    }

    render() {
        return (
            <RecipeFormPanel
                className={styles.panel}
                isActionForm
                placement='top-right'
                onApply={values => this.recipeActions.retrieve(values).dispatch()}>
                <Panel.Header
                    icon='cloud-download-alt'
                    title={msg('process.timeSeries.panel.retrieve.title')}/>
                <Panel.Content>
                    {this.renderContent()}
                </Panel.Content>
                <Form.PanelButtons
                    applyLabel={msg('process.timeSeries.panel.retrieve.apply')}/>
            </RecipeFormPanel>
        )
    }
}

Retrieve.propTypes = {
    recipeId: PropTypes.string
}

export default compose(
    Retrieve,
    recipeFormPanel({id: 'retrieve', fields, mapRecipeToProps})
)
<|endoftext|>


<commit_before>var ansiHelper = require('./ansiHelper'),
	fire = require('./fire'),

	// Color chart:
	// http://upload.wikimedia.org/wikipedia/commons/9/95/Xterm_color_chart.png
	FIRE_COLORS = [124, 196, 202, 208, 214, 220, 226],
	MAXIMUM_INTENSITY = 10,
	remainingLogs;

fire.init({
	width: 40,
	height: 15,
	maxIntensity: MAXIMUM_INTENSITY,
	iterationInterval: 100,
	consumeInterval: 1000,
	ascii: [' ', '.', ':', '*', 's', 'S', '#', '$'].map(function(char, index) {
		if (!index) return char;
		return ansiHelper.bgColor(FIRE_COLORS[index-1], char);
	})
});

var consumeLog = function consumeLog() {
	if (remainingLogs > 0) {
		remainingLogs -= 1;
		console.log("consume log");

		if (remainingLogs <= MAXIMUM_INTENSITY) {
			fire.setIntensity(remainingLogs);
		}
	}
}

// Starts the fireplace by placing the logs gently in the
// niche.
//
// Use something that burns well first, like paper,
// to create a good looking flame. You don't want to add
// all the logs at once; this would likely prevent the fire
// to start.
//
// Once this is done, start putting the first log.
// Wait until the fire has taken before adding the next one.
//
// Or more easily, call this function passing it the number of
// logs to consume.
//
// logs			- The number of logs to consume.
//
// renderer - The rendering callback. Called with the ANSI escaped
//						String representing the current fire animation.
//
// Returns nothing.
var burnLogs = function burnLogs(logs, renderer) {
	remainingLogs = logs

	fire.startFire({
		consume:	consumeLog,
		renderer: renderer
	});
};

module.exports = {
	// setRenderer: setRenderer,
	burnLogs:		 burnLogs
}
<commit_msg>Removing the setRenderer method on fireplace, since it's not used anymore.<commit_after>var ansiHelper = require('./ansiHelper'),
	fire = require('./fire'),

	// Color chart:
	// http://upload.wikimedia.org/wikipedia/commons/9/95/Xterm_color_chart.png
	FIRE_COLORS = [124, 196, 202, 208, 214, 220, 226],
	MAXIMUM_INTENSITY = 10,
	remainingLogs;

fire.init({
	width: 40,
	height: 15,
	maxIntensity: MAXIMUM_INTENSITY,
	iterationInterval: 100,
	consumeInterval: 1000,
	ascii: [' ', '.', ':', '*', 's', 'S', '#', '$'].map(function(char, index) {
		if (!index) return char;
		return ansiHelper.bgColor(FIRE_COLORS[index-1], char);
	})
});

var consumeLog = function consumeLog() {
	if (remainingLogs > 0) {
		remainingLogs -= 1;
		console.log("consume log");

		if (remainingLogs <= MAXIMUM_INTENSITY) {
			fire.setIntensity(remainingLogs);
		}
	}
}

// Starts the fireplace by placing the logs gently in the
// niche.
//
// Use something that burns well first, like paper,
// to create a good looking flame. You don't want to add
// all the logs at once; this would likely prevent the fire
// to start.
//
// Once this is done, start putting the first log.
// Wait until the fire has taken before adding the next one.
//
// Or more easily, call this function passing it the number of
// logs to consume.
//
// logs			- The number of logs to consume.
//
// renderer - The rendering callback. Called with the ANSI escaped
//						String representing the current fire animation.
//
// Returns nothing.
var burnLogs = function burnLogs(logs, renderer) {
	remainingLogs = logs

	fire.startFire({
		consume:	consumeLog,
		renderer: renderer
	});
};

module.exports = {
	burnLogs:		 burnLogs
}
<|endoftext|>


<commit_before>/* frequency.js
 * (c) Pranav Ravichandran <me@onloop.net>
 * Released under the MIT license.
 * http://github.com/pranavrc/frequency/
 */

$(document).ready(function () {
    var count = 0;

    $("[data-frequency]").each(function () {
        var frequency = parseFloat(($(this).data('frequency')));
        var fadeDelay = Math.log(frequency) / Math.LN10;
        var fadeTimePercentage = (frequency <= 2) ? 75 : fadeDelay * 100 / frequency;
        var aName = 'fade' + count;

        $('head').append("<style>                         \
            @keyframes " + aName + " {                    \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
            @-webkit-keyframes " + aName + " {            \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
            @-moz-keyframes " + aName + " {               \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
            @-o-keyframes " + aName + " {                 \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
        </style>");

        $(this).css({
            "animation": aName + " " + frequency + "s forwards",
            "-webkit-animation": aName + " " + frequency + "s forwards",
            "-moz-animation": aName + " " + frequency + "s forwards",
            "-o-animation": aName + " " + frequency + "s forwards",
            "animation-iteration-count": "infinite",
            "-webkit-animation-iteration-count": "infinite",
            "-moz-animation-iteration-count": "infinite",
            "-o-animation-iteration-count": "infinite"
        });

        count++;
    });
});
<commit_msg>Add initial delay<commit_after>/* frequency.js
 * (c) Pranav Ravichandran <me@onloop.net>
 * Released under the MIT license.
 * http://github.com/pranavrc/frequency/
 */

$(document).ready(function () {
    var count = 0;

    $("[data-frequency]").each(function () {
        var frequency = parseFloat(($(this).data('frequency')));
        var fadeDelay = Math.log(frequency) / Math.LN10;
        var fadeTimePercentage = (frequency <= 2) ? 75 : fadeDelay * 100 / frequency;
        var aName = 'fade' + count;

        $('head').append("<style>                         \
            @keyframes " + aName + " {                    \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
            @-webkit-keyframes " + aName + " {            \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
            @-moz-keyframes " + aName + " {               \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
            @-o-keyframes " + aName + " {                 \
                0%   {opacity:1;}" + fadeTimePercentage +
                "%   {opacity:0.10;}                      \
                100% {opacity:0.10;}                      \
            }                                             \
        </style>");

        $(this).css({
            "opacity": 0.1,
            "animation": aName + " " + frequency + "s forwards",
            "-webkit-animation": aName + " " + frequency + "s forwards",
            "-moz-animation": aName + " " + frequency + "s forwards",
            "-o-animation": aName + " " + frequency + "s forwards",
            "animation-iteration-count": "infinite",
            "-webkit-animation-iteration-count": "infinite",
            "-moz-animation-iteration-count": "infinite",
            "-o-animation-iteration-count": "infinite",
            "animation-delay": frequency + "s",
            "-webkit-animation-delay": frequency + "s",
            "-moz-animation-delay": frequency + "s",
            "-o-animation-delay": frequency + "s"
        });

        count++;
    });
});
<|endoftext|>


<commit_before>define(module, function(exports, require) {

  var slice = Array.prototype.slice;
  var fs = require('fs');
  var os = require('os');
  var util = require('util');
  var path = require('path');

  function make_directory(directory, mode) {
    directory = path.resolve(directory);
    if (typeof mode === 'undefined') {
      mode = 0777 & (~process.umask());
    }
    try {
      if (!fs.statSync(directory).isDirectory()) {
        throw new Error(directory + ' exists and is not a directory');
      }
    } catch (e) {
      if (e.code === 'ENOENT') {
        make_directory(path.dirname(directory), mode);
        fs.mkdirSync(directory, mode);
      } else {
        throw e;
      }
    }
  }

  function delete_directory(directory, options) {
    options = options || {};
    if (fs.existsSync(directory)) {
      fs.readdirSync(directory).forEach(function(node) {
        var item = path.join(directory, node);
        if (fs.lstatSync(item).isDirectory()) {
          delete_directory(item);
        } else {
          fs.unlinkSync(item);
        }
      });
      if (!options.children) {
        fs.rmdirSync(directory);
      }
    }
  }

  function delete_files(directory) {
    if (fs.existsSync(directory)) {
      fs.readdirSync(directory).forEach(function(node) {
        var item = path.join(directory, node);
        if (fs.lstatSync(item).isFile()) {
          fs.unlinkSync(item);
        }
      });
    }
  }

  function delete_file(file) {
    if (fs.lstatSync(file).isFile()) {
      fs.unlinkSync(file);
    }
  }

  exports({

    ns: 'qp-library/fss',

    stat: function() {
      return fs.statSync(path.join.apply(null, arguments));
    },

    exists: function() {
      return fs.existsSync(path.join.apply(null, arguments));
    },

    make_directory: make_directory,
    delete_directory: delete_directory,
    delete_file: delete_file,
    delete_files: delete_files,

    read: function() {
      var data = null;
      try {
        data = fs.readFileSync(path.join.apply(null, arguments), 'utf8');
      } catch(e) { throw e; }
      return data;
    },

    write: function() {
      var args = slice.call(arguments);
      var data = args.pop();
      var file = path.join.apply(null, args);
      var filepath = path.dirname(file);
      try {
        if (!fs.existsSync(filepath)) {
          make_directory(filepath);
        }
        fs.writeFileSync(file, data);
      } catch (e) { throw e; }
      return file;
    },

    clear: function() {
      var args = slice.call(arguments);
      args.push('');
      return this.write.apply(this, args);
    },

    copy: function(source, target) {
      try {
        var data = fs.readFileSync(source);
        var target_dir = path.dirname(target);
        if (!fs.existsSync(target_dir)) {
          make_directory(target_dir);
        }
        fs.writeFileSync(target, data);
        return data.length;
      } catch (e) {
        return null;
      }
    },

    rename: function(file, name) {
      try {
        fs.renameSync(file, path.join(path.dirname(file), name));
      } catch (e) {
        return null;
      }
    },

    append: function() {
      var args = slice.call(arguments);
      var data = args.pop();
      var file = path.join.apply(null, args);
      var filepath = path.dirname(file);
      try {
        if (!fs.existsSync(filepath)) {
          make_directory(filepath);
        }
        fs.appendFileSync(file, data);
      } catch (e) { throw e; }
      return file;
    },

    read_json: function() {
      var json = null;
      try {
        json = JSON.parse(fs.readFileSync(path.join.apply(null, arguments), 'utf8'));
      } catch(e) { json = {}; }
      return json;
    },

    write_json: function() {
      var args = slice.call(arguments);
      var o = args.pop();
      this.clear.apply(this, args);
      args.push(JSON.stringify(o, null, '  '));
      this.write.apply(this, args);
    },

    get_directories: function(dir, options) {
      options = options || {};
      var exclude = options.exclude;
      var directories = [];
      try {
        fs.readdirSync(dir).forEach(function(node) {
          if (node[0] !== '.' && (!exclude || exclude.indexOf(node) === -1)) {
            var name = path.join(dir, node);
            var stat = fs.statSync(name);
            if (stat.isDirectory()) {
              directories.push(name);
            }
          }
        }, this);
      } catch(e) { directories = null; }
      return directories;
    },

    get_files: function(dir, options, files) {
      options = options || {};
      files = files || [];
      var exts = options.ext;
      var search = options.file;
      try {
        var dirs = [];
        fs.readdirSync(dir).forEach(function(node) {
          if (node[0] !== '.') {
            var ext = path.extname(node);
            var name = path.join(dir, node);
            var stat = fs.statSync(name);
            if (stat.isFile()) {
              if (
                (!exts && !search) ||
                (exts && ext.length && exts.indexOf(ext) >= 0) ||
                (search && node === search)
              ) {
                files.push(name);
              }
            } else if (stat.isDirectory()) {
              if (options.deep) {
                dirs.push(name);
              }
            }
          }
        }, this);
        if (options.deep && dirs.length) {
          dirs.forEach(function(dir) {
            this.get_files(dir, options, files);
          }, this);
        }
      } catch(e) { if (options.debug) console.log(e); files = null; }
      return files;
    },

    read_files: function(files, options) {
      options = options || {};
      var data = '';
      var new_line = os.EOL + os.EOL;
      files.forEach(function(file) {
        if (fs.lstatSync(file).isFile()) {
          data += os.EOL + '/* ' + file + ' */' + new_line + fs.readFileSync(file, 'utf8');
        }
      });
      return data;
    },

    merge_files: function(files, options) {
      if (options && options.out_file) {
        delete_file(options.out_file);
        var new_line = os.EOL + os.EOL;
        files.forEach(function(file) {
          if (fs.lstatSync(file).isFile()) {
            var data = os.EOL + '/* ' + file + ' */' + new_line + fs.readFileSync(file, 'utf8');
            fs.appendFileSync(options.out_file, data);
          }
        });
      }
    },

    base64_image: function(image, mime) {
      var data = fs.readFileSync(image).toString('base64');
      return util.format('data:%s;base64,%s', mime, data);
    }

  });

});
<commit_msg>fss - delete_file - check file exists first<commit_after>define(module, function(exports, require) {

  var slice = Array.prototype.slice;
  var fs = require('fs');
  var os = require('os');
  var util = require('util');
  var path = require('path');

  function make_directory(directory, mode) {
    directory = path.resolve(directory);
    if (typeof mode === 'undefined') {
      mode = 0777 & (~process.umask());
    }
    try {
      if (!fs.statSync(directory).isDirectory()) {
        throw new Error(directory + ' exists and is not a directory');
      }
    } catch (e) {
      if (e.code === 'ENOENT') {
        make_directory(path.dirname(directory), mode);
        fs.mkdirSync(directory, mode);
      } else {
        throw e;
      }
    }
  }

  function delete_directory(directory, options) {
    options = options || {};
    if (fs.existsSync(directory)) {
      fs.readdirSync(directory).forEach(function(node) {
        var item = path.join(directory, node);
        if (fs.lstatSync(item).isDirectory()) {
          delete_directory(item);
        } else {
          fs.unlinkSync(item);
        }
      });
      if (!options.children) {
        fs.rmdirSync(directory);
      }
    }
  }

  function delete_files(directory) {
    if (fs.existsSync(directory)) {
      fs.readdirSync(directory).forEach(function(node) {
        var item = path.join(directory, node);
        if (fs.lstatSync(item).isFile()) {
          fs.unlinkSync(item);
        }
      });
    }
  }

  function delete_file(file) {
    if (fs.existsSync(file) && fs.lstatSync(file).isFile()) {
      fs.unlinkSync(file);
    }
  }

  exports({

    ns: 'qp-library/fss',

    stat: function() {
      return fs.statSync(path.join.apply(null, arguments));
    },

    exists: function() {
      return fs.existsSync(path.join.apply(null, arguments));
    },

    make_directory: make_directory,
    delete_directory: delete_directory,
    delete_file: delete_file,
    delete_files: delete_files,

    read: function() {
      var data = null;
      try {
        data = fs.readFileSync(path.join.apply(null, arguments), 'utf8');
      } catch(e) { throw e; }
      return data;
    },

    write: function() {
      var args = slice.call(arguments);
      var data = args.pop();
      var file = path.join.apply(null, args);
      var filepath = path.dirname(file);
      try {
        if (!fs.existsSync(filepath)) {
          make_directory(filepath);
        }
        fs.writeFileSync(file, data);
      } catch (e) { throw e; }
      return file;
    },

    clear: function() {
      var args = slice.call(arguments);
      args.push('');
      return this.write.apply(this, args);
    },

    copy: function(source, target) {
      try {
        var data = fs.readFileSync(source);
        var target_dir = path.dirname(target);
        if (!fs.existsSync(target_dir)) {
          make_directory(target_dir);
        }
        fs.writeFileSync(target, data);
        return data.length;
      } catch (e) {
        return null;
      }
    },

    rename: function(file, name) {
      try {
        fs.renameSync(file, path.join(path.dirname(file), name));
      } catch (e) {
        return null;
      }
    },

    append: function() {
      var args = slice.call(arguments);
      var data = args.pop();
      var file = path.join.apply(null, args);
      var filepath = path.dirname(file);
      try {
        if (!fs.existsSync(filepath)) {
          make_directory(filepath);
        }
        fs.appendFileSync(file, data);
      } catch (e) { throw e; }
      return file;
    },

    read_json: function() {
      var json = null;
      try {
        json = JSON.parse(fs.readFileSync(path.join.apply(null, arguments), 'utf8'));
      } catch(e) { json = {}; }
      return json;
    },

    write_json: function() {
      var args = slice.call(arguments);
      var o = args.pop();
      this.clear.apply(this, args);
      args.push(JSON.stringify(o, null, '  '));
      this.write.apply(this, args);
    },

    get_directories: function(dir, options) {
      options = options || {};
      var exclude = options.exclude;
      var directories = [];
      try {
        fs.readdirSync(dir).forEach(function(node) {
          if (node[0] !== '.' && (!exclude || exclude.indexOf(node) === -1)) {
            var name = path.join(dir, node);
            var stat = fs.statSync(name);
            if (stat.isDirectory()) {
              directories.push(name);
            }
          }
        }, this);
      } catch(e) { directories = null; }
      return directories;
    },

    get_files: function(dir, options, files) {
      options = options || {};
      files = files || [];
      var exts = options.ext;
      var search = options.file;
      try {
        var dirs = [];
        fs.readdirSync(dir).forEach(function(node) {
          if (node[0] !== '.') {
            var ext = path.extname(node);
            var name = path.join(dir, node);
            var stat = fs.statSync(name);
            if (stat.isFile()) {
              if (
                (!exts && !search) ||
                (exts && ext.length && exts.indexOf(ext) >= 0) ||
                (search && node === search)
              ) {
                files.push(name);
              }
            } else if (stat.isDirectory()) {
              if (options.deep) {
                dirs.push(name);
              }
            }
          }
        }, this);
        if (options.deep && dirs.length) {
          dirs.forEach(function(dir) {
            this.get_files(dir, options, files);
          }, this);
        }
      } catch(e) { if (options.debug) console.log(e); files = null; }
      return files;
    },

    read_files: function(files, options) {
      options = options || {};
      var data = '';
      var new_line = os.EOL + os.EOL;
      files.forEach(function(file) {
        if (fs.lstatSync(file).isFile()) {
          data += os.EOL + '/* ' + file + ' */' + new_line + fs.readFileSync(file, 'utf8');
        }
      });
      return data;
    },

    merge_files: function(files, options) {
      if (options && options.out_file) {
        delete_file(options.out_file);
        var new_line = os.EOL + os.EOL;
        files.forEach(function(file) {
          if (fs.lstatSync(file).isFile()) {
            var data = os.EOL + '/* ' + file + ' */' + new_line + fs.readFileSync(file, 'utf8');
            fs.appendFileSync(options.out_file, data);
          }
        });
      }
    },

    base64_image: function(image, mime) {
      var data = fs.readFileSync(image).toString('base64');
      return util.format('data:%s;base64,%s', mime, data);
    }

  });

});
<|endoftext|>


<commit_before>/*Global Phaser*/
//First we define our Basic game container variable. This is basic boilerplate.
//Args: width, height, renderer, and div in the hosting page.
var game = new Phaser.Game(480,640, Phaser.AUTO, 'game_div', {preload: preload, create: create, update: update});

//Load our assets
function preload(){
  game.load.image('bat', 'assets/img/paddleBlu.png');
  game.load.image('ball', 'assets/img/ballBlue.png');
  game.load.image('greenBlock','assets/img/element_green_rectangle.png')
}

var blocks;

function create(){
  game.physics.startSystem(Phaser.Physics.ARCADE);
  blocks = game.add.group();
  blocks.enableBody = true;
  player = game.add.sprite(game.world.width / 2 - 52, game.world.height - 132, 'bat');

}
function update(){

}<commit_msg>some more code cleanup<commit_after>/*global Phaser*/
//First we define our basic game container variable. This is basic boilerplate.
//Args: width, height, renderer, and div in the hosting page.
var game = new Phaser.Game(480,640, Phaser.AUTO, 'game_div', {preload: preload, create: create, update: update});

//Load our assets
function preload(){
  game.load.image('bat', 'assets/img/paddleBlu.png');
  game.load.image('ball', 'assets/img/ballBlue.png');
  game.load.image('greenBlock','assets/img/element_green_rectangle.png');
}

var blocks;
var player;

function create(){
  game.physics.startSystem(Phaser.Physics.ARCADE);

  //Initialize the Player's paddle
  player = game.add.sprite(0, 0, 'bat');
  player.x = (game.world.width / 2) - (player.width / 2);
  player.y = (game.world.height - 128);

  //Initialize the blocks
  blocks = game.add.group();
  blocks.enableBody = true;
}

function update(){

}<|endoftext|>


<commit_before>var Game = function(player1, player2) {
  this.player1 = player1;
  this.player2 = player2;
  this.onSubmit(this.player1, this.player2);
  this.onSubmit(this.player2, this.player1);
  this.sendCountdown(player1, 3);
  this.sendCountdown(player2, 3);
};

Game.prototype.sendCountdown = function(player, count) {
  player.emit('countdown', {count: count});
};

Game.prototype.onSubmit = function(player, opponent){
  var self = this;
  player.on('submit', function(data){
    player.move = data.move;
    self.getResults(player, opponent);
  });
};

Game.prototype.getResults = function(player, opponent){
  if(opponent.move){
    if (player.move == 'rock') {
      if (opponent.move == 'scissors') {
        // player wins
      } else if (opponent.move == 'paper') {
        // opponent wins
      } else {
        // tie
      }
    } else if (player.move == 'scissors') {
      if (opponent.move == 'rock') {
        // opponent wins
      } else if (opponent.move == 'paper') {
        // player wins
      } else {
        // tie
      }
    }
    else {  // player threw paper
      if (opponent.move == 'scissors') {
        // opponent wins
      } else if (opponent.move == 'rock') {
        // player wins
      } else {
        // tie
      }
    }
  }
};

module.exports = Game;
<commit_msg>Added sendResult logic<commit_after>var Game = function(player1, player2) {
  this.player1 = player1;
  this.player2 = player2;
  this.onSubmit(this.player1, this.player2);
  this.onSubmit(this.player2, this.player1);
  this.sendCountdown(player1, 3);
  this.sendCountdown(player2, 3);
};

Game.prototype.sendCountdown = function(player, count) {
  player.emit('countdown', {count: count});
};

Game.prototype.onSubmit = function(player, opponent){
  var self = this;
  player.on('submit', function(data) {
    player.move = data.move;
    self.getResults(player, opponent);
  });
};

Game.prototype.getResults = function(player, opponent){
  if(opponent.move){
    if (player.move == 'rock') {
      if (opponent.move == 'scissors') {
        // player wins
      } else if (opponent.move == 'paper') {
        // opponent wins
      } else {
        // tie
      }
    } else if (player.move == 'scissors') {
      if (opponent.move == 'rock') {
        // opponent wins
      } else if (opponent.move == 'paper') {
        // player wins
      } else {
        // tie
      }
    }
    else {  // player threw paper
      if (opponent.move == 'scissors') {
        // opponent wins
      } else if (opponent.move == 'rock') {
        // player wins
      } else {
        // tie
      }
    }
  }
};

Game.prototype.sendResults = function(player, opponent, result) {
  if (result == 0) {
    player.emit('result', {result: 'winner'} );
    opponent.emit('result', {result: 'loser'} );
  } else if (result == 1) {
    player.emit('result', { result: 'loser' } );
    opponent.emit('result', { result: 'winner' } );
  } else {
    player.emit('result', { result: 'tie' } );
    opponent.emit('result', { result: 'tie' } );
  }
}

module.exports = Game;
<|endoftext|>


<commit_before>const gulp = require('gulp');
const mocha = require('gulp-mocha');
const tests = require('../test/unit.test');

gulp.task('test', function() {
    return gulp
        .src(tests.all)
        .pipe(mocha({
            bail: true,
            timeout: 6000,
            exit: true,
        }))
        .once('end', function() {
            process.exit();
        });
});

gulp.task('profile', function() {
    return gulp
        .src(tests.all)
        .pipe(mocha({
            bail: false,
            timeout: 6000,
            exit: true,
            prof: true
        }))
        .once('end', function() {
            process.exit();
        });
});

gulp.task('test:typings', function() {
    return gulp
        .src(tests.typings)
        .pipe(mocha({
            bail: true,
            timeout: 6000,
            exit: true
        }))
        .once('end', function() {
            process.exit();
        });
});
<commit_msg>FIX(typings) increase test-timeout because of parallel<commit_after>const gulp = require('gulp');
const mocha = require('gulp-mocha');
const tests = require('../test/unit.test');

gulp.task('test', function() {
    return gulp
        .src(tests.all)
        .pipe(mocha({
            bail: true,
            timeout: 6000,
            exit: true,
        }))
        .once('end', function() {
            process.exit();
        });
});

gulp.task('profile', function() {
    return gulp
        .src(tests.all)
        .pipe(mocha({
            bail: false,
            timeout: 6000,
            exit: true,
            prof: true
        }))
        .once('end', function() {
            process.exit();
        });
});

gulp.task('test:typings', function() {
    return gulp
        .src(tests.typings)
        .pipe(mocha({
            bail: true,
            timeout: 12000,
            exit: true
        }))
        .once('end', function() {
            process.exit();
        });
});
<|endoftext|>


<commit_before>var cluster = require("cluster");
var os      = require("os");

const CPUS = os.cpus();
if (cluster.isMaster)
{
    CPUS.forEach(function() {
        cluster.fork()
    });

    cluster.on("listening", function(worker) {
        console.log("Cluster %d connected", worker.process.pid);
    });

    cluster.on("disconnect", function(worker) {
        console.log("Cluster %d disconnected", worker.process.pid);
    });

    cluster.on("exit", function(worker) {
        console.log("Cluster %d is dead", worker.process.pid);
        cluster.fork();
    });
}
else
{
    // Load server
    require(__dirname + "/server");
}<commit_msg>~ New script Cluster, ZeroDown added<commit_after>// Zerodown time Cluster
var recluster = require('recluster');
var path      = require('path');

var cluster   = recluster(path.join(__dirname, 'server.js'));
cluster.run();

// if process is killed, reload the cluster
process.on('SIGUSR2', function() {
    console.log('Got SIGUSR2, reloading cluster...');
    cluster.reload();
});

console.log("Spawned cluster, PID", process.pid);<|endoftext|>