<commit_before>// Karma configuration
// Generated on Sun Jul 06 2014 04:18:28 GMT+0200 (CEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['qunit'],

    // list of files / patterns to load in the browser
    files: [
      'modules/jquery/jquery-2.1.1.js',
      'modules/object.assing/object.assign.js',
      'modules/polyfills/number.isnan.js',
      'modules/polyfills/math.log10.js',
      'modules/polyfills/window.customevent.js',
      'modules/polyfills/window.requestanimationframe.js',
      'modules/collection/js/observe.js',
      'modules/collection/js/mixin.events.js',
      'modules/collection/js/collection.js',
      'js/sparky.js',
      'js/sparky.dom.js',
      'js/sparky.observe.js',
      'js/sparky.throttle.js',
      'js/sparky.parse.js',
      'js/sparky.fn.js',
      'js/sparky.fn.each.js',
      'js/sparky.fn.value.js',
      'js/sparky.filters.js',
      'js/sparky.ready.js',
      'test/module.js',
      'test/test.sparky-observe.js',
      'test/test.filters.js',
      'test/test.sparky.js',
      'test/test.sparky-template.js',
      'test/test.sparky-delay.js',
      'test/test.sparky-fn.js',
      'test/test.sparky-fn-each.js',
      //'test/test.sparky-inputs.js',
      //'test/test.sparky-events.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'js/sparky*.js': ['coverage'],
      'modules/collection/js/mixin*.js': ['coverage'],
      'modules/collection/observe.js': ['coverage'],
      'modules/collection/collection.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter

    // Commented for everyday use - the coverage reporter reduces scripts to one
    // line, meaning that karma gives false line numbers for errors
    reporters: ['progress', 'coverage'],

    // optionally, configure the reporter
    coverageReporter: {
      type : 'lcov',
      dir : 'test-coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    //browsers: ['Chrome', 'Firefox', 'Safari'],
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>index<commit_after>// Karma configuration
// Generated on Sun Jul 06 2014 04:18:28 GMT+0200 (CEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['qunit'],

    // list of files / patterns to load in the browser
    files: [
      'modules/jquery/jquery-2.1.1.js',
      'modules/object.assing/object.assign.js',
      'modules/polyfills/number.isnan.js',
      'modules/polyfills/math.log10.js',
      'modules/polyfills/window.customevent.js',
      'modules/polyfills/window.requestanimationframe.js',
      'modules/collection/js/observe.js',
      'modules/collection/js/mixin.events.js',
      'modules/collection/js/collection.js',
      'js/sparky.js',
      'js/sparky.dom.js',
      'js/sparky.observe.js',
      'js/sparky.throttle.js',
      'js/sparky.parse.js',
      'js/sparky.fn.js',
      'js/sparky.fn.each.js',
      'js/sparky.fn.value.js',
      'js/sparky.filters.js',
      'js/sparky.ready.js',
      'test/module.js',
      'test/test.sparky-observe.js',
      'test/test.filters.js',
      'test/test.sparky.js',
      'test/test.sparky-template.js',
      'test/test.sparky-delay.js',
      'test/test.sparky-fn.js',
      'test/test.sparky-fn-each.js',
      'test/test.sparky-inputs.js',
      //'test/test.sparky-events.js'
    ],

    // list of files to exclude
    exclude: [

    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'js/sparky*.js': ['coverage'],
      'modules/collection/js/mixin*.js': ['coverage'],
      'modules/collection/observe.js': ['coverage'],
      'modules/collection/collection.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter

    // Commented for everyday use - the coverage reporter reduces scripts to one
    // line, meaning that karma gives false line numbers for errors
    reporters: ['progress', 'coverage'],

    // optionally, configure the reporter
    coverageReporter: {
      type : 'lcov',
      dir : 'test-coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    //browsers: ['Chrome', 'Firefox', 'Safari'],
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'kube-admin',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },

    flashMessageDefaults: {
      timeout: 4000,
      types: ['1', '2', '3', '4', '5', '6', 'positive', 'negative', 'info']
    },

    contentSecurityPolicy: {
      'default-src': ["'none'"],
      'script-src':  ["'self'"],
      'font-src':    ["'self'", "https://fonts.gstatic.com", "data:"],
      'connect-src': ["'self'"],
      'img-src':     ["'self'", "data:"],
      'style-src':   ["'self'", "http://fonts.googleapis.com"],
      'media-src':   ["'self'"]
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<commit_msg>gh-46 Added CSP rule for connect-src closes #46<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'kube-admin',
    environment: environment,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },

    flashMessageDefaults: {
      timeout: 4000,
      types: ['1', '2', '3', '4', '5', '6', 'positive', 'negative', 'info']
    },

    contentSecurityPolicy: {
      'default-src': ["'none'"],
      'script-src':  ["'self'"],
      'font-src':    ["'self'", "https://fonts.gstatic.com", "data:"],
      'connect-src': ["'self'" , "*"],
      'img-src':     ["'self'", "data:"],
      'style-src':   ["'self'", "http://fonts.googleapis.com"],
      'media-src':   ["'self'"]
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  return ENV;
};
<|endoftext|>


<commit_before>/**
 * UI-Bootstrap Helpers :: v1.0 :: 12-May-2016
 *
 * Copyright (c) 2015 | Sumanth Sampath
 * License: MIT
 */
(function (angular, window, document, undefined) {
    'use strict-di';
    angular.module('uiBootstrapHelpers', ['ui.bootstrap', 'template/defaultModal.html'])
.factory('modalService', ['$uibModal', function (uibModal) {

    var showModal = function (modalOptions, modalDefaults) {
        if (!modalOptions)
            throw "modalOptions should be provided a non null value";
        modalOptions.showCloseButton = true;
        modalOptions.showMultiActions = null;
        return open(modalOptions, modalDefaults);
    };

    var showMultiActionModal = function (modalOptions, modalDefaults) {
        if (!modalOptions)
            throw "modalOptions should be provided a non null value";
        modalOptions.showCloseButton = true;
        if (!modalOptions.showMultiActions)
            modalOptions.actionButtonText = modalOptions.actionButtonText ? modalOptions.actionButtonText : "Ok";
        else {
            if(!angular.isArray(modalOptions.showMultiActions))
                throw "modalOptions.showMultiActions should be an array";
        }

        return open(modalOptions, modalDefaults);
    };

    var showAlert = function (modalOptions, modalDefaults) {
        if (!modalOptions)
            throw "modalOptions should be provided a non null value";
        modalOptions.showCloseButton = false;
        modalOptions.showMultiActions = null;
        return open(modalOptions, modalDefaults);
    };

    var open = function (modalOptions, modalDefaults) {

        modalOptions.headerText = modalOptions.headerText ? modalOptions.headerText : "";
        modalOptions.bodyText = modalOptions.bodyText ? modalOptions.bodyText : "";
        modalOptions.actionButtonText = modalOptions.actionButtonText ? modalOptions.actionButtonText : "Ok";
        modalOptions.closeButtonText = modalOptions.closeButtonText ? modalOptions.closeButtonText : "Cancel";

        if (!modalDefaults) modalDefaults = {};

        modalDefaults.templateUrl = modalDefaults.templateUrl ? modalDefaults.templateUrl : 'template/defaultModal.html';

        //Create temp objects to work with since we're in a singleton service
        var tempModalOptions = {};
        var tempModalDefaults = {};

        //Map modal.html $scope custom properties to defaults defined in service
        angular.extend(tempModalOptions, modalOptions);

        //Map angular-bootstrap-ui modal custom defaults to modal defaults defined in service
        angular.extend(tempModalDefaults, modalDefaults);
        if (!tempModalDefaults.controllerAs) {
            tempModalDefaults.controllerAs = "vm";
        }

        if (!tempModalDefaults.controller) {

            tempModalDefaults.controller = ['$uibModalInstance', function (uibModalInstance) {
                this.modalOptions = tempModalOptions;
                this.modalOptions.ok = function (result) {
                    uibModalInstance.close(result);
                };
                this.modalOptions.close = function (result) {
                    uibModalInstance.dismiss('cancel');
                };
            }]
        };

        return uibModal.open(tempModalDefaults).result;
    };

    return modalService = {
        showModal: showModal,
        showAlert: showAlert,
        showMultiActionModal: showMultiActionModal
    };
}]);
angular.module("template/defaultModal.html", []).run(["$templateCache", function ($templateCache) {
        $templateCache.put("template/defaultModal.html",
    "
\n" +
    "

\n" +
    "
\n" +
    "

\n" +
    "
\n" +
    "
\n" +
    "   <button ng-show=\"!vm.modalOptions.showMultiActions\" class=\" btn btn-primary\" type=\"button\" ng-click=\"vm.modalOptions.ok();\"></button>\n" +
    "   \n" +
    "       <button ng-show=\"actions.visible\" class=\"btn btn-primary\" type=\"button\" ng-click=\"vm.modalOptions.ok(actions.value);\"></button>\n" +
    "   \n" +
    "   <button ng-show=\"vm.modalOptions.showCloseButton\" class=\"btn btn-warning\" type=\"button\" ng-click=\"vm.modalOptions.close();\"></button>\n" +
    "
\n"
    );
}]);
})(window.angular, window, document);<commit_msg>Delete ModalService.js<commit_after><|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define('ace/mode/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/diff_highlight_rules', 'ace/mode/folding/diff'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var HighlightRules = require("./diff_highlight_rules").DiffHighlightRules;
var FoldMode = require("./folding/diff").FoldMode;

var Mode = function() {
    this.HighlightRules = HighlightRules;
    this.foldingRules = new FoldMode(["diff", "index", "\\+{3}", "@@|\\*{5}"], "i");
};
oop.inherits(Mode, TextMode);

(function() {

    this.$id = "ace/mode/diff";
}).call(Mode.prototype);

exports.Mode = Mode;

});

define('ace/mode/diff_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var DiffHighlightRules = function() {

    this.$rules = {
        "start" : [{
                regex: "^(?:\\*{15}|={67}|-{3}|\\+{3})$",
                token: "punctuation.definition.separator.diff",
                "name": "keyword"
            }, { //diff.range.unified
                regex: "^(@@)(\\s*.+?\\s*)(@@)(.*)$",
                token: [
                    "constant",
                    "constant.numeric",
                    "constant",
                    "comment.doc.tag"
                ]
            }, { //diff.range.normal
                regex: "^(\\d+)([,\\d]+)(a|d|c)(\\d+)([,\\d]+)(.*)$",
                token: [
                    "constant.numeric",
                    "punctuation.definition.range.diff",
                    "constant.function",
                    "constant.numeric",
                    "punctuation.definition.range.diff",
                    "invalid"
                ],
                "name": "meta."
            }, {
                regex: "^(\\-{3}|\\+{3}|\\*{3})( .+)$",
                token: [
                    "constant.numeric",
                    "meta.tag"
                ]
            }, { // added
                regex: "^([!+>])(.*?)(\\s*)$",
                token: [
                    "support.constant",
                    "text",
                    "invalid"
                ]
            }, { // removed
                regex: "^([<\\-])(.*?)(\\s*)$",
                token: [
                    "support.function",
                    "string",
                    "invalid"
                ]
            }, {
                regex: "^(diff)(\\s+--\\w+)?(.+?)( .+)?$",
                token: ["variable", "variable", "keyword", "variable"]
            }, {
                regex: "^Index.+$",
                token: "variable"
            }, {
                regex: "^\\s+$",
                token: "text"
            }, {
                regex: "\\s*$",
                token: "invalid"
            }, {
                defaultToken: "invisible",
                caseInsensitive: true
            }
        ]
    };
};

oop.inherits(DiffHighlightRules, TextHighlightRules);

exports.DiffHighlightRules = DiffHighlightRules;
});

define('ace/mode/folding/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) {

var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var Range = require("../../range").Range;

var FoldMode = exports.FoldMode = function(levels, flag) {
	this.regExpList = levels;
	this.flag = flag;
	this.foldingStartMarker = RegExp("^(" + levels.join("|") + ")", this.flag);
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {
    this.getFoldWidgetRange = function(session, foldStyle, row) {
        var line = session.getLine(row);
        var start = {row: row, column: line.length};

        var regList = this.regExpList;
        for (var i = 1; i <= regList.length; i++) {
            var re = RegExp("^(" + regList.slice(0, i).join("|") + ")", this.flag);
            if (re.test(line))
                break;
        }

        for (var l = session.getLength(); ++row < l; ) {
            line = session.getLine(row);
            if (re.test(line))
                break;
        }
        if (row == start.row + 1)
            return;
        return  Range.fromPoints(start, {row: row - 1, column: line.length});
    };

}).call(FoldMode.prototype);

});
<commit_msg>training newline character remoned<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define('ace/mode/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/diff_highlight_rules', 'ace/mode/folding/diff'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var HighlightRules = require("./diff_highlight_rules").DiffHighlightRules;
var FoldMode = require("./folding/diff").FoldMode;

var Mode = function() {
    this.HighlightRules = HighlightRules;
    this.foldingRules = new FoldMode(["diff", "index", "\\+{3}", "@@|\\*{5}"], "i");
};
oop.inherits(Mode, TextMode);

(function() {

    this.$id = "ace/mode/diff";
}).call(Mode.prototype);

exports.Mode = Mode;

});

define('ace/mode/diff_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var DiffHighlightRules = function() {

    this.$rules = {
        "start" : [{
                regex: "^(?:\\*{15}|={67}|-{3}|\\+{3})$",
                token: "punctuation.definition.separator.diff",
                "name": "keyword"
            }, { //diff.range.unified
                regex: "^(@@)(\\s*.+?\\s*)(@@)(.*)$",
                token: [
                    "constant",
                    "constant.numeric",
                    "constant",
                    "comment.doc.tag"
                ]
            }, { //diff.range.normal
                regex: "^(\\d+)([,\\d]+)(a|d|c)(\\d+)([,\\d]+)(.*)$",
                token: [
                    "constant.numeric",
                    "punctuation.definition.range.diff",
                    "constant.function",
                    "constant.numeric",
                    "punctuation.definition.range.diff",
                    "invalid"
                ],
                "name": "meta."
            }, {
                regex: "^(\\-{3}|\\+{3}|\\*{3})( .+)$",
                token: [
                    "constant.numeric",
                    "meta.tag"
                ]
            }, { // added
                regex: "^([!+>])(.*?)(\\s*)$",
                token: [
                    "support.constant",
                    "text",
                    "invalid"
                ]
            }, { // removed
                regex: "^([<\\-])(.*?)(\\s*)$",
                token: [
                    "support.function",
                    "string",
                    "invalid"
                ]
            }, {
                regex: "^(diff)(\\s+--\\w+)?(.+?)( .+)?$",
                token: ["variable", "variable", "keyword", "variable"]
            }, {
                regex: "^Index.+$",
                token: "variable"
            }, {
                regex: "^\\s+$",
                token: "text"
            }, {
                regex: "\\s*$",
                token: "invalid"
            }, {
                defaultToken: "invisible",
                caseInsensitive: true
            }
        ]
    };
};

oop.inherits(DiffHighlightRules, TextHighlightRules);

exports.DiffHighlightRules = DiffHighlightRules;
});

define('ace/mode/folding/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) {

var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var Range = require("../../range").Range;

var FoldMode = exports.FoldMode = function(levels, flag) {
	this.regExpList = levels;
	this.flag = flag;
	this.foldingStartMarker = RegExp("^(" + levels.join("|") + ")", this.flag);
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {
    this.getFoldWidgetRange = function(session, foldStyle, row) {
        var line = session.getLine(row);
        var start = {row: row, column: line.length};

        var regList = this.regExpList;
        for (var i = 1; i <= regList.length; i++) {
            var re = RegExp("^(" + regList.slice(0, i).join("|") + ")", this.flag);
            if (re.test(line))
                break;
        }

        for (var l = session.getLength(); ++row < l; ) {
            line = session.getLine(row);
            if (re.test(line))
                break;
        }
        if (row == start.row + 1)
            return;
        return  Range.fromPoints(start, {row: row - 1, column: line.length});
    };

}).call(FoldMode.prototype);

});
<|endoftext|>


<commit_before>(function($) {
  $(function() {
    $(".date-filter input[type=submit]").hide();
    $(".date-filter .date").keypress(function(e) {
      if(e.which == 13) {
        $(".date-filter form").submit();
      };
    })
  })
})(jQuery);<commit_msg>Fix date filter submission<commit_after>(function($) {
  $(function() {
    $(".date-filter input[type=submit]").hide();
    $(".date-filter .date").keypress(function(e) {
      if(e.which == 13) {
        $("form.date-filter").submit();
      };
    })
  })
})(jQuery);
<|endoftext|>


<commit_before>import React from 'react';

import Component from './Component';
import { Easing, StyleSheet, Text, View, Animated ,TouchableOpacity,FlatList} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import Stack from'../Utils/Stack';

class DropdownModale extends Component {

    onItemSelected = (value) => {
        let callback = this.props.onItemSelected || function() {};
        callback(value);
        Stack.getItem('rootApp').dropdownModale.hide();
    }

    render() {
        return (
            <View style={styles.modaleWrapper}>
                <TouchableOpacity style={styles.closeModale} onPress={()=> {Stack.getItem('rootApp').dropdownModale.hide();}}>
                    <Icon name="times" color='grey' size={15} />
                </TouchableOpacity>
                <Text style={styles.modalTitle}>{this.props.title || 'Select an option'}</Text>
                <FlatList
                        style={styles.list}
                        data={this.props.choices}
                        enableEmptySections={true}
                        renderRow={(rowData) => { return (
                            <TouchableOpacity style={styles.listItem} onPress={() => {this.onItemSelected(rowData)}}>
                                <Text>{ rowData.label}</Text>
                            </TouchableOpacity>
                        );
                }} />
            </View>
        );
    }

}

export default class extends Component {

    constructor(props) {
        super(props);

    }

    onItemSelected = (value) => {
        let callback = this.props.onChange || function() {};
        callback(value);
    }

    selectValue = () => {
        let choices = this.props.choices;
        Stack.getItem('rootApp').dropdownModale.setContent(<DropdownModale title={this.props.title || false} value={this.props.value} choices= {choices} onItemSelected={this.onItemSelected} />);
        Stack.getItem('rootApp').dropdownModale.show();
    }

    render() {
        return (
            <TouchableOpacity onPress={this.selectValue} style={styles.button}>
                {typeof this.props.value !== 'undefined' &&<Text style={{color:(this.props.color || 'black')}} >{this.props.value.label}</Text>}
                {typeof this.props.value === 'undefined' &&<Text style={styles.placeholder}>{this.props.placeholder || 'Select a value'}</Text>}
            </TouchableOpacity>
        )
    }
}

const styles = StyleSheet.create({
    modaleWrapper: {
        backgroundColor:'white',
        //padding:10,
    },
    button : {
        padding:5,
    },
    placeholder: {
        color:'grey',
    },
    closeModale : {
        position:'absolute',
        right:10,
        top:10,
        zIndex:10,
    },
    list : {
        marginTop:40,
        borderTopWidth:1,
        borderTopColor:'#eeeeee'
    },
    listItem: {
        padding:10,
        borderBottomWidth:1,
        borderBottomColor:'#eeeeee'
    },
    modalTitle: {
        position:'absolute',
        left:10,
        top:10,
        right:30,
        color:'grey',

    }
});

<commit_msg>Dropdown: replace ListView by FlatList<commit_after>import React from 'react';

import Component from './Component';
import { Easing, StyleSheet, Text, View, Animated ,TouchableOpacity,FlatList} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import Stack from'../Utils/Stack';

class DropdownModale extends Component {

    onItemSelected = (value) => {
        let callback = this.props.onItemSelected || function() {};
        callback(value);
        Stack.getItem('rootApp').dropdownModale.hide();
    }

    render() {
        return (
            <View style={styles.modaleWrapper}>
                <TouchableOpacity style={styles.closeModale} onPress={()=> {Stack.getItem('rootApp').dropdownModale.hide();}}>
                    <Icon name="times" color='grey' size={15} />
                </TouchableOpacity>
                <Text style={styles.modalTitle}>{this.props.title || 'Select an option'}</Text>

                <FlatList
                    data={this.props.choices}
                    renderItem={({ item, index }) => (
                        <TouchableOpacity style={styles.listItem} onPress={() => {this.onItemSelected(item)}}>
                            <Text>{ item.label}</Text>
                        </TouchableOpacity>
                    )}
                  />
            </View>
        );
    }

}

export default class extends Component {

    constructor(props) {
        super(props);

    }

    onItemSelected = (value) => {
        let callback = this.props.onChange || function() {};
        callback(value);
    }

    selectValue = () => {
        let choices = this.props.choices;
        Stack.getItem('rootApp').dropdownModale.setContent(<DropdownModale title={this.props.title || false} value={this.props.value} choices= {choices} onItemSelected={this.onItemSelected} />);
        Stack.getItem('rootApp').dropdownModale.show();
    }

    render() {
        return (
            <TouchableOpacity onPress={this.selectValue} style={styles.button}>
                {typeof this.props.value !== 'undefined' &&<Text style={{color:(this.props.color || 'black')}} >{this.props.value.label}</Text>}
                {typeof this.props.value === 'undefined' &&<Text style={styles.placeholder}>{this.props.placeholder || 'Select a value'}</Text>}
            </TouchableOpacity>
        )
    }
}

const styles = StyleSheet.create({
    modaleWrapper: {
        backgroundColor:'white',
        //padding:10,
    },
    button : {
        padding:5,
    },
    placeholder: {
        color:'grey',
    },
    closeModale : {
        position:'absolute',
        right:10,
        top:10,
        zIndex:10,
    },
    list : {
        marginTop:40,
        borderTopWidth:1,
        borderTopColor:'#eeeeee'
    },
    listItem: {
        padding:10,
        borderBottomWidth:1,
        borderBottomColor:'#eeeeee'
    },
    modalTitle: {
        position:'absolute',
        left:10,
        top:10,
        right:30,
        color:'grey',

    }
});<|endoftext|>


<commit_before>process.env.CHROME_BIN = require('puppeteer').executablePath()

const webpack = require('./webpack.config');

delete webpack['entry'];
delete webpack['output'];
delete webpack['plugins'];
webpack['mode'] = 'development';

module.exports = (config) => {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            // 'legacy/spec/lib/jasmine-species/jasmine-grammar.js',
            'legacy/spec/lib/jasmine-matchers.js',
            // 'legacy/spec/lib/jasmine-ajax/mock-ajax.js',
            'node_modules/jasmine-ajax/lib/mock-ajax.js',
            'node_modules/jasmine-species/jasmine-grammar.js',
            'legacy/spec/lib/i18n/i18n.js',
            // 'legacy/spec/lib/matchers.js',
            'legacy/spec/lib/analytics.js',
            'node_modules/mithril/mithril.js',
            'node_modules/underscore/underscore.js',
            'node_modules/liquidjs/dist/liquid.js',
            'node_modules/mithril-postgrest/mithril-postgrest.umd.js',
            'node_modules/chart.js/Chart.js',
            'node_modules/moment/moment.js',
            'node_modules/select/dist/select.js',
            'node_modules/jquery/dist/jquery.min.js',
            'legacy/vendor/replaceDiacritics.js',
            'legacy/spec/lib/mocks/*mock.js',
            'legacy/spec/index.spec.js',
        ],
        preprocessors: {
            'legacy/spec/lib/mithril-query/mithril-query.js' : ['webpack'],
            'legacy/spec/**/*.spec.js': ['webpack'],
            'legacy/spec/index.spec.js': ['webpack']
        },
        webpack,
        exclude: [],
        reporters: ['spec'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        browsers: ['MyHeadlessChrome'],
        customLaunchers: {
            MyHeadlessChrome: {
                base: 'ChromeHeadless',
                flags: ['--headless', '--no-sandbox']
            }
        },
        singleRun: true
    });
};
<commit_msg>remove webackmode to auto discover<commit_after>process.env.CHROME_BIN = require('puppeteer').executablePath()

const webpack = require('./webpack.config');

delete webpack['entry'];
delete webpack['output'];
delete webpack['plugins'];

module.exports = (config) => {
    config.set({
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            // 'legacy/spec/lib/jasmine-species/jasmine-grammar.js',
            'legacy/spec/lib/jasmine-matchers.js',
            // 'legacy/spec/lib/jasmine-ajax/mock-ajax.js',
            'node_modules/jasmine-ajax/lib/mock-ajax.js',
            'node_modules/jasmine-species/jasmine-grammar.js',
            'legacy/spec/lib/i18n/i18n.js',
            // 'legacy/spec/lib/matchers.js',
            'legacy/spec/lib/analytics.js',
            'node_modules/mithril/mithril.js',
            'node_modules/underscore/underscore.js',
            'node_modules/liquidjs/dist/liquid.js',
            'node_modules/mithril-postgrest/mithril-postgrest.umd.js',
            'node_modules/chart.js/Chart.js',
            'node_modules/moment/moment.js',
            'node_modules/select/dist/select.js',
            'node_modules/jquery/dist/jquery.min.js',
            'legacy/vendor/replaceDiacritics.js',
            'legacy/spec/lib/mocks/*mock.js',
            'legacy/spec/index.spec.js',
        ],
        preprocessors: {
            'legacy/spec/lib/mithril-query/mithril-query.js' : ['webpack'],
            'legacy/spec/**/*.spec.js': ['webpack'],
            'legacy/spec/index.spec.js': ['webpack']
        },
        webpack,
        exclude: [],
        reporters: ['spec'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        browsers: ['MyHeadlessChrome'],
        customLaunchers: {
            MyHeadlessChrome: {
                base: 'ChromeHeadless',
                flags: ['--headless', '--no-sandbox']
            }
        },
        singleRun: true
    });
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'dw-collections-manager',
    environment: environment,
    baseURL: '/',
    locationType: 'hash',
    i18n: {
        defaultLocale: 'sv'
    },
    EmberENV: {
    FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
    }
    },

    APP: {
    // Here you can pass flags/options to your application instance
    // when it is created
    },
    moment: {
        // To cherry-pick specific locale support into your application.
        // Full list of locales: https://github.com/moment/moment/tree/2.10.3/locale
        includeLocales: ['sv', 'en']
    },
    metricsAdapters: [{
            name: 'Piwik',
            environments: ['production'],
            config: {
                piwikUrl: 'http://monitor.dina-web.net',
                siteId: 4
            }
        }, {
            name: 'Piwik',
            environments: ['development'],
            config: {
                piwikUrl: 'http://monitor.dina-web.net',
                siteId: 2
            }
    }]
  };

  if (environment === 'development') {

    // Basic logging, e.g. "Transitioned into 'post'"
    ENV.LOG_TRANSITIONS = true,

    // Extremely detailed logging, highlighting every internal
    // step made while transitioning into a route, including
    // `beforeModel`, `model`, and `afterModel` hooks, and
    // information about redirects and aborted transitions
    ENV.LOG_TRANSITIONS_INTERNAL = true

    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;

    // api.dina-web is specified in the backend reposity.
    ENV.HOST = 'http://api.dina-web';
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
      ENV.SENTRY_LOGGING = true;

      // String to be replaced when running in production.
      ENV.HOST = 'REPLACEWITHHOST';
  }

  return ENV;
};
<commit_msg>Use Piwik over SSL<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'dw-collections-manager',
    environment: environment,
    baseURL: '/',
    locationType: 'hash',
    i18n: {
        defaultLocale: 'sv'
    },
    EmberENV: {
    FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
    }
    },

    APP: {
    // Here you can pass flags/options to your application instance
    // when it is created
    },
    moment: {
        // To cherry-pick specific locale support into your application.
        // Full list of locales: https://github.com/moment/moment/tree/2.10.3/locale
        includeLocales: ['sv', 'en']
    },
    metricsAdapters: [{
            name: 'Piwik',
            environments: ['production'],
            config: {
                piwikUrl: 'https://monitor.dina-web.net',
                siteId: 4
            }
        }, {
            name: 'Piwik',
            environments: ['development'],
            config: {
                piwikUrl: 'https://monitor.dina-web.net',
                siteId: 2
            }
    }]
  };

  if (environment === 'development') {

    // Basic logging, e.g. "Transitioned into 'post'"
    ENV.LOG_TRANSITIONS = true,

    // Extremely detailed logging, highlighting every internal
    // step made while transitioning into a route, including
    // `beforeModel`, `model`, and `afterModel` hooks, and
    // information about redirects and aborted transitions
    ENV.LOG_TRANSITIONS_INTERNAL = true

    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;

    // api.dina-web is specified in the backend reposity.
    ENV.HOST = 'http://api.dina-web';
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
      ENV.SENTRY_LOGGING = true;

      // String to be replaced when running in production.
      ENV.HOST = 'REPLACEWITHHOST';
  }

  return ENV;
};
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import { _ } from 'meteor/underscore';
import Tabular from '../common/Tabular';

/*
 * These are the two publications used by TabularTable.
 *
 * The genericPub one can be overridden by supplying a `pub`
 * property with a different publication name. This publication
 * is given only the list of ids and requested fields. You may
 * want to override it if you need to publish documents from
 * related collections along with the table collection documents.
 *
 * The getInfo one runs first and handles all the complex logic
 * required by this package, so that you don't have to duplicate
 * this logic when overriding the genericPub function.
 *
 * Having two publications also allows fine-grained control of
 * reactivity on the client.
 */

Meteor.publish('tabular_genericPub', function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  const table = Tabular.tablesByName[tableName];
  if (!table) {
    // We throw an error in the other pub, so no need to throw one here
    this.ready();
    return;
  }

  // Check security. We call this in both publications.
  if (typeof table.allow === 'function' && !table.allow(this.userId, fields)) {
    this.ready();
    return;
  }

  // Check security for fields. We call this only in this publication
  if (typeof table.allowFields === 'function' && !table.allowFields(this.userId, fields)) {
    this.ready();
    return;
  }

  return table.collection.find({_id: {$in: ids}}, {fields: fields});
});

Meteor.publish('tabular_getInfo', function (tableName, selector, sort, skip, limit) {
  check(tableName, String);
  check(selector, Match.Optional(Match.OneOf(Object, null)));
  check(sort, Match.Optional(Match.OneOf(Array, null)));
  check(skip, Number);
  check(limit, Match.Optional(Match.OneOf(Number, null)));

  const table = Tabular.tablesByName[tableName];
  if (!table) {
    throw new Error(`No TabularTable defined with the name "${tableName}". Make sure you are defining your TabularTable in common code.`);
  }

  // Check security. We call this in both publications.
  // Even though we're only publishing _ids and counts
  // from this function, with sensitive data, there is
  // a chance someone could do a query and learn something
  // just based on whether a result is found or not.
  if (typeof table.allow === 'function' && !table.allow(this.userId)) {
    this.ready();
    return;
  }

  selector = selector || {};

  // Allow the user to modify the selector before we use it
  if (typeof table.changeSelector === 'function') {
    selector = table.changeSelector(selector, this.userId);
  }

  // Apply the server side selector specified in the tabular
  // table constructor. Both must be met, so we join
  // them using $and, allowing both selectors to have
  // the same keys.
  if (typeof table.selector === 'function') {
    const tableSelector = table.selector(this.userId);
    if (_.isEmpty(selector)) {
      selector = tableSelector;
    } else {
      selector = {$and: [tableSelector, selector]};
    }
  }

  const findOptions = {
    skip: skip,
    fields: {_id: 1}
  };

  // `limit` may be `null`
  if (limit > 0) {
    findOptions.limit = limit;
  }

  // `sort` may be `null`
  if (_.isArray(sort)) {
    findOptions.sort = sort;
  }

  const filteredCursor = table.collection.find(selector, findOptions);

  let filteredRecordIds = filteredCursor.map(doc => doc._id);

  const countCursor = table.collection.find(selector, {fields: {_id: 1}});

  let recordReady = false;
  let updateRecords = () => {
    const currentCount = countCursor.count();

    // From https://datatables.net/manual/server-side
    // recordsTotal: Total records, before filtering (i.e. the total number of records in the database)
    // recordsFiltered: Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned for this page of data).

    const record = {
      ids: filteredRecordIds,
      // count() will give us the updated total count
      // every time. It does not take the find options
      // limit into account.
      recordsTotal: currentCount,
      recordsFiltered: currentCount
    };

    if (recordReady) {
      //console.log('changed', tableName, record);
      this.changed('tabular_records', tableName, record);
    } else {
      //console.log('added', tableName, record);
      this.added('tabular_records', tableName, record);
      recordReady = true;
    }
  }

  if (table.throttleRefresh) {
    updateRecords = _.throttle(updateRecords, table.throttleRefresh);
  }

  updateRecords();

  this.ready();

  // Handle docs being added or removed from the result set.
  let initializing = true;
  const handle = filteredCursor.observeChanges({
    added: function (id) {
      if (initializing) return;

      //console.log('ADDED');
      filteredRecordIds.push(id);
      updateRecords();
    },
    removed: function (id) {
      //console.log('REMOVED');
      // _.findWhere is used to support Mongo ObjectIDs
      filteredRecordIds = _.without(filteredRecordIds, _.findWhere(filteredRecordIds, id));
      updateRecords();
    }
  });
  initializing = false;

  // It is too inefficient to use an observe without any limits to track count perfectly
  // accurately when, for example, the selector is {} and there are a million documents.
  // Instead we will update the count every 10 seconds, in addition to whenever the limited
  // result set changes.
  const interval = Meteor.setInterval(updateRecords, 10000);

  // Stop observing the cursors when client unsubs.
  // Stopping a subscription automatically takes
  // care of sending the client any removed messages.
  this.onStop(() => {
    Meteor.clearInterval(interval);
    handle.stop();
  });
});

export default Tabular;
<commit_msg>Wrap updateRecords in bindEnvironment<commit_after>import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import { _ } from 'meteor/underscore';
import Tabular from '../common/Tabular';

/*
 * These are the two publications used by TabularTable.
 *
 * The genericPub one can be overridden by supplying a `pub`
 * property with a different publication name. This publication
 * is given only the list of ids and requested fields. You may
 * want to override it if you need to publish documents from
 * related collections along with the table collection documents.
 *
 * The getInfo one runs first and handles all the complex logic
 * required by this package, so that you don't have to duplicate
 * this logic when overriding the genericPub function.
 *
 * Having two publications also allows fine-grained control of
 * reactivity on the client.
 */

Meteor.publish('tabular_genericPub', function (tableName, ids, fields) {
  check(tableName, String);
  check(ids, Array);
  check(fields, Match.Optional(Object));

  const table = Tabular.tablesByName[tableName];
  if (!table) {
    // We throw an error in the other pub, so no need to throw one here
    this.ready();
    return;
  }

  // Check security. We call this in both publications.
  if (typeof table.allow === 'function' && !table.allow(this.userId, fields)) {
    this.ready();
    return;
  }

  // Check security for fields. We call this only in this publication
  if (typeof table.allowFields === 'function' && !table.allowFields(this.userId, fields)) {
    this.ready();
    return;
  }

  return table.collection.find({_id: {$in: ids}}, {fields: fields});
});

Meteor.publish('tabular_getInfo', function (tableName, selector, sort, skip, limit) {
  check(tableName, String);
  check(selector, Match.Optional(Match.OneOf(Object, null)));
  check(sort, Match.Optional(Match.OneOf(Array, null)));
  check(skip, Number);
  check(limit, Match.Optional(Match.OneOf(Number, null)));

  const table = Tabular.tablesByName[tableName];
  if (!table) {
    throw new Error(`No TabularTable defined with the name "${tableName}". Make sure you are defining your TabularTable in common code.`);
  }

  // Check security. We call this in both publications.
  // Even though we're only publishing _ids and counts
  // from this function, with sensitive data, there is
  // a chance someone could do a query and learn something
  // just based on whether a result is found or not.
  if (typeof table.allow === 'function' && !table.allow(this.userId)) {
    this.ready();
    return;
  }

  selector = selector || {};

  // Allow the user to modify the selector before we use it
  if (typeof table.changeSelector === 'function') {
    selector = table.changeSelector(selector, this.userId);
  }

  // Apply the server side selector specified in the tabular
  // table constructor. Both must be met, so we join
  // them using $and, allowing both selectors to have
  // the same keys.
  if (typeof table.selector === 'function') {
    const tableSelector = table.selector(this.userId);
    if (_.isEmpty(selector)) {
      selector = tableSelector;
    } else {
      selector = {$and: [tableSelector, selector]};
    }
  }

  const findOptions = {
    skip: skip,
    fields: {_id: 1}
  };

  // `limit` may be `null`
  if (limit > 0) {
    findOptions.limit = limit;
  }

  // `sort` may be `null`
  if (_.isArray(sort)) {
    findOptions.sort = sort;
  }

  const filteredCursor = table.collection.find(selector, findOptions);

  let filteredRecordIds = filteredCursor.map(doc => doc._id);

  const countCursor = table.collection.find(selector, {fields: {_id: 1}});

  let recordReady = false;
  let updateRecords = () => {
    const currentCount = countCursor.count();

    // From https://datatables.net/manual/server-side
    // recordsTotal: Total records, before filtering (i.e. the total number of records in the database)
    // recordsFiltered: Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned for this page of data).

    const record = {
      ids: filteredRecordIds,
      // count() will give us the updated total count
      // every time. It does not take the find options
      // limit into account.
      recordsTotal: currentCount,
      recordsFiltered: currentCount
    };

    if (recordReady) {
      //console.log('changed', tableName, record);
      this.changed('tabular_records', tableName, record);
    } else {
      //console.log('added', tableName, record);
      this.added('tabular_records', tableName, record);
      recordReady = true;
    }
  }

  if (table.throttleRefresh) {
    // Why Meteor.bindEnvironment? See https://github.com/aldeed/meteor-tabular/issues/278#issuecomment-217318112
    updateRecords = _.throttle(Meteor.bindEnvironment(updateRecords), table.throttleRefresh);
  }

  updateRecords();

  this.ready();

  // Handle docs being added or removed from the result set.
  let initializing = true;
  const handle = filteredCursor.observeChanges({
    added: function (id) {
      if (initializing) return;

      //console.log('ADDED');
      filteredRecordIds.push(id);
      updateRecords();
    },
    removed: function (id) {
      //console.log('REMOVED');
      // _.findWhere is used to support Mongo ObjectIDs
      filteredRecordIds = _.without(filteredRecordIds, _.findWhere(filteredRecordIds, id));
      updateRecords();
    }
  });
  initializing = false;

  // It is too inefficient to use an observe without any limits to track count perfectly
  // accurately when, for example, the selector is {} and there are a million documents.
  // Instead we will update the count every 10 seconds, in addition to whenever the limited
  // result set changes.
  const interval = Meteor.setInterval(updateRecords, 10000);

  // Stop observing the cursors when client unsubs.
  // Stopping a subscription automatically takes
  // care of sending the client any removed messages.
  this.onStop(() => {
    Meteor.clearInterval(interval);
    handle.stop();
  });
});

export default Tabular;
<|endoftext|>


<commit_before>angular.module('citizen-engagement.cameraCtrl',[])
<commit_msg>cameractrl<commit_after>angular.module('citizen-engagement.cameraCtrl',[])

.factory("CameraService", function($q) {
  return {
  getPicture: function(options) {
    var deferred = $q.defer();
    navigator.camera.getPicture(function(result) {
      // do any magic you need
      deferred.resolve(result);
      }, function(err) {
      deferred.reject(err);
      }, options);
        return deferred.promise;
    }
  }
});

.controller("cameraController", function(CameraService, $http, qimgUrl, qimgToken) {
  // take the picture
  CameraService.getPicture({
    quality: 75,
    targetWidth: 400,
    targetHeight: 300,
    // return base64-encoded data instead of a file
    destinationType: Camera.DestinationType.DATA_URL
    }).then(function(imageData) {
      // upload the image
      $http({
      method: "POST",
      url: qimgUrl + "/images",
      headers: {
      Authorization: "Bearer " + qimgToken
      },
      data: {
      data: imageData
    }
    }).success(function(data) {
      var imageUrl = data.url;
      // do something with imageUrl
    });
  });
})
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Slider, Modal } from 'react-native'
import {
  Container, Content, Body, View,
  Card, CardItem,
  Form,
  Item, InputGroup, Input, Label, Text,
  Picker, Button, Icon,
  Spinner
} from 'native-base'
import { Grid, Col, Row } from 'react-native-easy-grid'

const ROLE_FETCHER = 'Fetcher'
const fakeFetcher =   { userID: 2, userAlias: 'Epan',  role: ROLE_FETCHER,   objective: 'Pencil' }

export default class TaskForm extends Component {
  static navigationOptions = {
    header: {
      title: 'New Task',
    }
  }
  state = {
    requestModalVisible: false,
    bidStatus: 'PENDING',
    cost: 0,
    tip: 0
  }

  submitRequest = () => {
    // this.setState({
    //   requestModalVisible: true
    // })

    // setTimeout(() => {
    //   this.setState({
    //     bidStatus: 'ACCEPTED'
    //   })
    // }, 2000)

    this.props.navigation.navigate('ChatRoom', { receiver: fakeFetcher })
  }

  render = () => (
    <Content>
      <Modal
        animationType="fade"
        transparent={true}
        visible={this.state.requestModalVisible}
      >
        <Container style={{ backgroundColor: 'rgba(52, 52, 52, 0.4)', paddingHorizontal: 50, paddingVertical: 200 }}>
          <Card>
            <CardItem>
              <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>{
                this.state.bidStatus === 'PENDING' ?
                  <View style={{ justifyContent: 'center', alignItems: 'center', marginVertical: 70, marginHorizontal: 30 }}>
                    <Text>Waiting for Fetcher response</Text>
                    <Spinner />
                  </View> :
                  <View style={{ justifyContent: 'center', alignItems: 'center', marginVertical: 70, marginHorizontal: 30 }}>
                    <View><Text>Task {this.state.bidStatus} !</Text></View>
                    <Button primary block onPress={() => {
                      this.setState({
                        requestModalVisible: false
                      })
                      this.props.navigation.navigate('ChatRoom', { receiver: fakeFetcher })
                      }}>
                      <Icon name="arrow-forward" />
                    </Button>
                  </View>
              }</View>
            </CardItem>
          </Card>
        </Container>
      </Modal>
        <Card>
          <CardItem>

            <View style={{ alignSelf: 'stretch' }}>
              <Item stackedLabel>
                I need:<Input />
              </Item>
              <Item stackedLabel>
                From:<Input />
              </Item>
              <View style={{ flexDirection: 'row', flex: 1 }}>
                <Item stackedLabel style={{ width: 200 }}>
                  Within:<Input keyboardType="numeric" />
                </Item>
                <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                <Picker
                  iosHeader="Select one"
                  mode="dropdown"
                  selectedValue="key0"
                  onValueChange={() => {}}
                  style={{width: 100}}
                  mode="dropdown"
                >
                  <Picker.Item label="Hour" value="key0" />
                  <Picker.Item label="Day" value="key1" />
                </Picker>
                </View>
              </View>
              <View style={{ marginVertical: 10 }}>
                Cost: {this.state.cost}
                <Slider minimumValue={0} maximumValue={1000} step={5} onSlidingComplete={cost => this.setState({ cost })} />
              </View>
              <View style={{ marginVertical: 10 }}>
                Tip: {this.state.tip}
                <Slider minimumValue={0} maximumValue={100} step={2} onSlidingComplete={tip => this.setState({ tip })} />
              </View>
              <Item stackedLabel>
                Additional information
                <Input />
              </Item>
              <Button primary block style={{ marginTop: 30 }} onPress={() => this.submitRequest()}>
                <Text>Request!</Text>
              </Button>
            </View>

          </CardItem>
        </Card>
      </Content>
  )
}
<commit_msg>use numeric for cost+tip, add checkbox for prefer female fetcher<commit_after>import React, { Component } from 'react'
import { Slider, Modal } from 'react-native'
import {
  Container, Content, Body, View,
  Card, CardItem,
  Form,
  Item, InputGroup, Input, Label, Text,
  Picker, Button, Icon, CheckBox,
  Spinner
} from 'native-base'
import { Grid, Col, Row } from 'react-native-easy-grid'

const ROLE_FETCHER = 'Fetcher'
const fakeFetcher =   { userID: 2, userAlias: 'Epan',  role: ROLE_FETCHER,   objective: 'Pencil' }

export default class TaskForm extends Component {
  static navigationOptions = {
    header: {
      title: 'New Task',
    }
  }
  state = {
    requestModalVisible: false,
    bidStatus: 'PENDING',
    cost: 0,
    tip: 0,
    preferFemale: false
  }

  submitRequest = () => {
    this.props.navigation.navigate('ChatRoom', { receiver: fakeFetcher })
  }

  render = () => (
    <Content>
      <Modal
        animationType="fade"
        transparent={true}
        visible={this.state.requestModalVisible}
      >
        <Container style={{ backgroundColor: 'rgba(52, 52, 52, 0.4)', paddingHorizontal: 50, paddingVertical: 200 }}>
          <Card>
            <CardItem>
              <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>{
                this.state.bidStatus === 'PENDING' ?
                  <View style={{ justifyContent: 'center', alignItems: 'center', marginVertical: 70, marginHorizontal: 30 }}>
                    <Text>Waiting for Fetcher response</Text>
                    <Spinner />
                  </View> :
                  <View style={{ justifyContent: 'center', alignItems: 'center', marginVertical: 70, marginHorizontal: 30 }}>
                    <View><Text>Task {this.state.bidStatus} !</Text></View>
                    <Button primary block onPress={() => {
                      this.setState({
                        requestModalVisible: false
                      })
                      this.props.navigation.navigate('ChatRoom', { receiver: fakeFetcher })
                      }}>
                      <Icon name="arrow-forward" />
                    </Button>
                  </View>
              }</View>
            </CardItem>
          </Card>
        </Container>
      </Modal>
        <Card>
          <CardItem>

            <View style={{ alignSelf: 'stretch' }}>
              <Item stackedLabel>
                I need:<Input />
              </Item>
              <Item stackedLabel>
                From:<Input />
              </Item>
              <View style={{ flexDirection: 'row', flex: 1 }}>
                <Item stackedLabel style={{ width: 200 }}>
                  Within:<Input keyboardType="numeric" />
                </Item>
                <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                <Picker
                  iosHeader="Select one"
                  mode="dropdown"
                  selectedValue="key0"
                  onValueChange={() => {}}
                  style={{width: 100}}
                  mode="dropdown"
                >
                  <Picker.Item label="Hour" value="key0" />
                  <Picker.Item label="Day" value="key1" />
                </Picker>
                </View>
              </View>
              <View style={{ marginVertical: 10 }}>
                Cost:
                <Input keyboardType="numeric" defaultValue={this.state.cost} onChange={({nativeEvent}) => this.setState({ cost: nativeEvent.text })} />
              </View>
              <View style={{ marginVertical: 10 }}>
                Tip: {this.state.tip}
                <Input keyboardType="numeric" defaultValue={this.state.tip} onChange={({nativeEvent}) => this.setState({ tip: nativeEvent.text })} />
              </View>
              <View style={{ marginVertical: 10 }}>
                 {this.state.tip}
                <CheckBox checked={this.state.preferFemale} onPress={() => this.setState({ preferFemale: !this.state.preferFemale })} />
              </View>
              <Item stackedLabel>
                Additional information
                <Input />
              </Item>
              <Button primary block style={{ marginTop: 30 }} onPress={() => this.submitRequest()}>
                <Text>Request!</Text>
              </Button>
            </View>

          </CardItem>
        </Card>
      </Content>
  )
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Nov 19 2016 00:50:37 GMT+0100 (CET)

const path = require('path');

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'chai'],

        // list of files / patterns to load in the browser
        files: [
            'src/test/*.spec.js',
            // {pattern: 'src/js/*.js)', included: false}
        ],

        // list of files to exclude
        exclude: [
            'src/index.js'
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/js/*.js': ['coverage'],
            'src/test/*.spec.js': ['webpack']
        },

        webpack: {
            module: {
                preLoaders: [
                    // instrument only testing sources with Istanbul
                    {
                        test: /\.js$/,
                        include: path.resolve('src/js/'),
                        loader: 'istanbul-instrumenter'
                    }
                ]
            }
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['ChromeNoSandbox'],

		customLaunchers: {
			ChromeNoSandbox: {
				base: 'Chrome',
				flags: ['--no-sandbox']
			}
		},

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    });
};
<commit_msg>reverting changes<commit_after>// Karma configuration
// Generated on Sat Nov 19 2016 00:50:37 GMT+0100 (CET)

const path = require('path');

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['mocha', 'chai'],

        // list of files / patterns to load in the browser
        files: [
            'src/test/*.spec.js',
            // {pattern: 'src/js/*.js)', included: false}
        ],

        // list of files to exclude
        exclude: [
            'src/index.js'
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'src/js/*.js': ['coverage'],
            'src/test/*.spec.js': ['webpack']
        },

        webpack: {
            module: {
                preLoaders: [
                    // instrument only testing sources with Istanbul
                    {
                        test: /\.js$/,
                        include: path.resolve('src/js/'),
                        loader: 'istanbul-instrumenter'
                    }
                ]
            }
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress', 'coverage'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chromium'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    });
};
<|endoftext|>


<commit_before>/* jshint node: true */
var pkg  = require('../package.json');
var fs   = require('fs');
var YAML = require('yamljs');

// host can be an ip "1.2.3.4" -> http://1.2.3.4:8080
// or a URL+port
function normalizeHost(host,defaultPort) {
  if ( host.indexOf('http') !== 0 )
  {
    if ( host.indexOf(':') === -1 )
    {
      host = 'http://' + host + (defaultPort ? ':'+defaultPort : '');
    }
    else
    {
      host = 'http://' + host;
    }
  }

  return host;
}

function readLocales(environment) {
  /* Parse the translations from the translations folder*/
  /* ember intl getLocalesByTranslations does not work if intl is not managing them (bundled) */
  /* This needs a little work to read the yaml files for the langugae name prop*/
  var files = fs.readdirSync('./translations');
  var translationsOut = {};
  files.forEach(function(filename) {
    if ( environment === 'production' && filename === 'none.yaml' ) {
      // Don't show the "None" language in prod
      return;
    }
    var ymlFile = YAML.load('./translations/' + filename);
    var label  = ymlFile.languageName;
    var locale = filename.split('.')[0];
    translationsOut[locale] = label;
  });
  return translationsOut;
}

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'ui',
    environment: environment,
    exportApplicationGlobal: true,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    minifyCSS: {
        enabled: false
    },
    minifyJS: {
        enabled: false
    },

    contentSecurityPolicy: {
      // Allow the occasional <elem style="blah">...
      'style-src':  "'self' releases.rancher.com localhost:3000 'unsafe-inline'",
      'font-src':   "'self' releases.rancher.com",
      'script-src': "'self' releases.rancher.com localhost:3000",
      'object-src': "'self' releases.rancher.com",
      'img-src':    "'self' releases.rancher.com avatars.githubusercontent.com gravatar.com localhost:3000 data:",
      'frame-src':  "'self' releases.rancher.com",

      // Allow connect to anywhere, for console and event stream socket
      'connect-src': '*'
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
      version: pkg.version,
      appName: 'Rancher',
      apiServer: 'http://localhost:8080',
      apiEndpoint: '/v1',
      catalogServer: '',
      catalogEndpoint: '/v1-catalog',
      projectToken: '%PROJECTID%',
      kubernetesEndpoint: '/r/projects/%PROJECTID%/kubernetes',
      kubectlEndpoint: '/r/projects/%PROJECTID%/kubectld:8091/v1-kubectl',
      mesosEndpoint: '/r/projects/%PROJECTID%/mesos-master:5050',
      proxyEndpoint: '/v1/proxy',
      wsEndpoint: '/v1/projects/%PROJECTID%/subscribe' +
                    '?eventNames=resource.change' +
                    '&eventNames=service.kubernetes.change' +
                    '&include=hosts' +
                    '&include=services' +
                    '&include=instances' +
                    '&include=instance' +
                    '&include=instanceLinks' +
                    '&include=ipAddresses',
      baseAssets: '/',
      locales: readLocales(environment)
    },
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    ENV.APP.LOG_ACTIVE_GENERATION = true;
    ENV.APP.LOG_TRANSITIONS = true;
    ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (process.env.BASE_URL) {
    ENV.baseURL = process.env.BASE_URL;
  }

  ENV.APP.baseURL = ENV.baseURL;

  if (process.env.FINGERPRINT) {
    ENV.APP.fingerprint = process.env.FINGERPRINT;
  }

  if (process.env.BASE_ASSETS) {
    ENV.APP.baseAssets = process.env.BASE_ASSETS;
  }

  // Override the Rancher server/endpoint with environment var
  var server = process.env.RANCHER;
  if ( server )
  {
    ENV.APP.apiServer = normalizeHost(server,8080);
  }
  else if (environment === 'production')
  {
    ENV.APP.apiServer = '';
  }

  // Override the Catalog server/endpoint with environment var
  server = process.env.CATALOG;
  if ( server )
  {
    ENV.APP.catalogServer = normalizeHost(server,8088);
  }
  else if (environment === 'production')
  {
    ENV.APP.catalogServer = '';
  }

  var pl = process.env.PL;
  if ( pl )
  {
    ENV.APP.pl = pl;
  }
  else
  {
    ENV.APP.pl = 'rancher';
  }

  return ENV;
};
<commit_msg>Disable pagination on subscribe socket<commit_after>/* jshint node: true */
var pkg  = require('../package.json');
var fs   = require('fs');
var YAML = require('yamljs');

// host can be an ip "1.2.3.4" -> http://1.2.3.4:8080
// or a URL+port
function normalizeHost(host,defaultPort) {
  if ( host.indexOf('http') !== 0 )
  {
    if ( host.indexOf(':') === -1 )
    {
      host = 'http://' + host + (defaultPort ? ':'+defaultPort : '');
    }
    else
    {
      host = 'http://' + host;
    }
  }

  return host;
}

function readLocales(environment) {
  /* Parse the translations from the translations folder*/
  /* ember intl getLocalesByTranslations does not work if intl is not managing them (bundled) */
  /* This needs a little work to read the yaml files for the langugae name prop*/
  var files = fs.readdirSync('./translations');
  var translationsOut = {};
  files.forEach(function(filename) {
    if ( environment === 'production' && filename === 'none.yaml' ) {
      // Don't show the "None" language in prod
      return;
    }
    var ymlFile = YAML.load('./translations/' + filename);
    var label  = ymlFile.languageName;
    var locale = filename.split('.')[0];
    translationsOut[locale] = label;
  });
  return translationsOut;
}

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'ui',
    environment: environment,
    exportApplicationGlobal: true,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    minifyCSS: {
        enabled: false
    },
    minifyJS: {
        enabled: false
    },

    contentSecurityPolicy: {
      // Allow the occasional <elem style="blah">...
      'style-src':  "'self' releases.rancher.com localhost:3000 'unsafe-inline'",
      'font-src':   "'self' releases.rancher.com",
      'script-src': "'self' releases.rancher.com localhost:3000",
      'object-src': "'self' releases.rancher.com",
      'img-src':    "'self' releases.rancher.com avatars.githubusercontent.com gravatar.com localhost:3000 data:",
      'frame-src':  "'self' releases.rancher.com",

      // Allow connect to anywhere, for console and event stream socket
      'connect-src': '*'
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
      version: pkg.version,
      appName: 'Rancher',
      apiServer: 'http://localhost:8080',
      apiEndpoint: '/v1',
      catalogServer: '',
      catalogEndpoint: '/v1-catalog',
      projectToken: '%PROJECTID%',
      kubernetesEndpoint: '/r/projects/%PROJECTID%/kubernetes',
      kubectlEndpoint: '/r/projects/%PROJECTID%/kubectld:8091/v1-kubectl',
      mesosEndpoint: '/r/projects/%PROJECTID%/mesos-master:5050',
      proxyEndpoint: '/v1/proxy',
      wsEndpoint: '/v1/projects/%PROJECTID%/subscribe' +
                    '?eventNames=resource.change' +
                    '&eventNames=service.kubernetes.change' +
                    '&limit=-1' +
                    '&include=hosts' +
                    '&include=services' +
                    '&include=instances' +
                    '&include=instance' +
                    '&include=instanceLinks' +
                    '&include=ipAddresses',
      baseAssets: '/',
      locales: readLocales(environment)
    },
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    ENV.APP.LOG_ACTIVE_GENERATION = true;
    ENV.APP.LOG_TRANSITIONS = true;
    ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (process.env.BASE_URL) {
    ENV.baseURL = process.env.BASE_URL;
  }

  ENV.APP.baseURL = ENV.baseURL;

  if (process.env.FINGERPRINT) {
    ENV.APP.fingerprint = process.env.FINGERPRINT;
  }

  if (process.env.BASE_ASSETS) {
    ENV.APP.baseAssets = process.env.BASE_ASSETS;
  }

  // Override the Rancher server/endpoint with environment var
  var server = process.env.RANCHER;
  if ( server )
  {
    ENV.APP.apiServer = normalizeHost(server,8080);
  }
  else if (environment === 'production')
  {
    ENV.APP.apiServer = '';
  }

  // Override the Catalog server/endpoint with environment var
  server = process.env.CATALOG;
  if ( server )
  {
    ENV.APP.catalogServer = normalizeHost(server,8088);
  }
  else if (environment === 'production')
  {
    ENV.APP.catalogServer = '';
  }

  var pl = process.env.PL;
  if ( pl )
  {
    ENV.APP.pl = pl;
  }
  else
  {
    ENV.APP.pl = 'rancher';
  }

  return ENV;
};
<|endoftext|>


<commit_before>var mongo = require('mongodb'),
	Server = mongo.Server,
    Db = mongo.Db,
    BSON = require('bson').BSONPure;

	var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = require('bson').BSONPure;

// This is the IP of the mongoDB database. It can easily be changed to point to your server.
var server = new Server('localhost', 27017, {
    auto_reconnect: true
});

//Create a new database called exampleDB (or get the existing one).
db = new Db('exampleDB', server);

db.open(function(err, db) {
    if (!err) {
        console.log("Connected to 'exampleDB' database");
        db.collection('example', {
            strict: true
        }, function(err, collection) {
            if (err) {
                console.log("The 'example' collection doesn't exist. Creating it with sample data...");
                // populateDB(); //uncomment that if you want some sample data to prepopulate your DB
            }
        });
    }
});

exports.getStuff = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving stuff: ' + id);
    db.collection('example', function(err, collection) {
        if (err) {
            throw err; //If something goes wrong just throw an error
        } else {
            collection.findOne({
                '_id': new BSON.ObjectID(id)
            }, function(err, item) {
                if (err !== null) {
                    res.status(500).send(err); // If an error occured send a status 500 to the front-end
                }

                if (item === null) {
                    res.status(404).send('Not Found!'); //Let the user know when the recipe isn't found
                } else {
                    res.send(item); //If everything went well then send back the response.
                }
            });
        }
    });
};

exports.postStuff = function(req, res) {
    var sample = req.body;
    console.log('Adding example: ' + JSON.stringify(sample));
    db.collection('example', function(err, collection) {
        if (err) {
            throw err;
        } else {
            collection.insert(sample, {
                safe: true
            }, function(err, result) {
                if (err) {
                    res.send({
                        'error': 'An error has occurred'
                    });
                } else {
                    console.log('Success: ' + JSON.stringify(result[0]));
                    res.send(result[0]);
                }
            });
        }
    });
}

exports.updateStuff = function(req, res) {
    var id = req.params.id;
    var sample = req.body;
    console.log('Updating sample: ' + id);
    console.log(JSON.stringify(sample));
    db.collection('example', function(err, collection) {
        collection.update({
            '_id': new BSON.ObjectID(id)
        }, sample, {
            safe: true
        }, function(err, result) {
            if (err) {
                console.log('Error updating sample: ' + err);
                res.send({
                    'error': 'An error has occurred'
                });
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(sample);
            }
        });
    });
}

exports.deleteStuff = function(req, res) {
    var id = req.params.id;
    console.log('Deleting sample: ' + id);
    db.collection('example', function(err, collection) {
        collection.remove({
            '_id': new BSON.ObjectID(id)
        }, {
            safe: true
        }, function(err, result) {
            if (err) {
                res.send({
                    'error': 'An error has occurred - ' + err
                });
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(result);
            }
        });
    });
}

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
var populateDB = function() {

    var sampleData = [{
        name: "Lemon Chicken",
        cookingTime: "30 minutes",
        ingredients: [{
            'ingredient': 'Chicken',
            'quantity': '2'
        }, {
            'ingredient': 'Lemon',
            'quantity': '1'
        }, {
            'ingredient': 'Thyme',
            'quantity': '1 tbsp'
        }],
        picture: "lemonChicken.jpg"
    }, {
        name: "Beef Stroganoff",
        cookingTime: "30 minutes",
        ingredients: [{
            'ingredient': 'Beef',
            'quantity': '0.5 kg'
        }, {
            'ingredient': 'Mustard',
            'quantity': '2 tbsp'
        }, {
            'ingredient': 'Mushrooms',
            'quantity': '10'
        }],
        picture: "beefStroganoff.jpg"
    }];

    db.collection('example', function(err, collection) {
        collection.insert(sampleData, {
            safe: true
        }, function(err, result) {});
    });

};<commit_msg>removing some duplicate variables in the main server file<commit_after>var mongo = require('mongodb'),
	Server = mongo.Server,
    Db = mongo.Db,
    BSON = require('bson').BSONPure;

// This is the IP of the mongoDB database. It can easily be changed to point to your server.
var server = new Server('localhost', 27017, {
    auto_reconnect: true
});

//Create a new database called exampleDB (or get the existing one).
db = new Db('exampleDB', server);

db.open(function(err, db) {
    if (!err) {
        console.log("Connected to 'exampleDB' database");
        db.collection('example', {
            strict: true
        }, function(err, collection) {
            if (err) {
                console.log("The 'example' collection doesn't exist. Creating it with sample data...");
                // populateDB(); //uncomment that if you want some sample data to prepopulate your DB
            }
        });
    }
});

exports.getStuff = function(req, res) {
    var id = req.params.id;
    console.log('Retrieving stuff: ' + id);
    db.collection('example', function(err, collection) {
        if (err) {
            throw err; //If something goes wrong just throw an error
        } else {
            collection.findOne({
                '_id': new BSON.ObjectID(id)
            }, function(err, item) {
                if (err !== null) {
                    res.status(500).send(err); // If an error occured send a status 500 to the front-end
                }

                if (item === null) {
                    res.status(404).send('Not Found!'); //Let the user know when the recipe isn't found
                } else {
                    res.send(item); //If everything went well then send back the response.
                }
            });
        }
    });
};

exports.postStuff = function(req, res) {
    var sample = req.body;
    console.log('Adding example: ' + JSON.stringify(sample));
    db.collection('example', function(err, collection) {
        if (err) {
            throw err;
        } else {
            collection.insert(sample, {
                safe: true
            }, function(err, result) {
                if (err) {
                    res.send({
                        'error': 'An error has occurred'
                    });
                } else {
                    console.log('Success: ' + JSON.stringify(result[0]));
                    res.send(result[0]);
                }
            });
        }
    });
}

exports.updateStuff = function(req, res) {
    var id = req.params.id;
    var sample = req.body;
    console.log('Updating sample: ' + id);
    console.log(JSON.stringify(sample));
    db.collection('example', function(err, collection) {
        collection.update({
            '_id': new BSON.ObjectID(id)
        }, sample, {
            safe: true
        }, function(err, result) {
            if (err) {
                console.log('Error updating sample: ' + err);
                res.send({
                    'error': 'An error has occurred'
                });
            } else {
                console.log('' + result + ' document(s) updated');
                res.send(sample);
            }
        });
    });
}

exports.deleteStuff = function(req, res) {
    var id = req.params.id;
    console.log('Deleting sample: ' + id);
    db.collection('example', function(err, collection) {
        collection.remove({
            '_id': new BSON.ObjectID(id)
        }, {
            safe: true
        }, function(err, result) {
            if (err) {
                res.send({
                    'error': 'An error has occurred - ' + err
                });
            } else {
                console.log('' + result + ' document(s) deleted');
                res.send(result);
            }
        });
    });
}

/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
var populateDB = function() {

    var sampleData = [{
        name: "Lemon Chicken",
        cookingTime: "30 minutes",
        ingredients: [{
            'ingredient': 'Chicken',
            'quantity': '2'
        }, {
            'ingredient': 'Lemon',
            'quantity': '1'
        }, {
            'ingredient': 'Thyme',
            'quantity': '1 tbsp'
        }],
        picture: "lemonChicken.jpg"
    }, {
        name: "Beef Stroganoff",
        cookingTime: "30 minutes",
        ingredients: [{
            'ingredient': 'Beef',
            'quantity': '0.5 kg'
        }, {
            'ingredient': 'Mustard',
            'quantity': '2 tbsp'
        }, {
            'ingredient': 'Mushrooms',
            'quantity': '10'
        }],
        picture: "beefStroganoff.jpg"
    }];

    db.collection('example', function(err, collection) {
        collection.insert(sampleData, {
            safe: true
        }, function(err, result) {});
    });

};<|endoftext|>