<commit_before>/**
 * Module dependencies
 */

var util = require('util');
var assert = require('assert');
var _ = require('@sailshq/lodash');
var getModel = require('./get-model');
var getAttribute = require('./get-attribute');

/**
 * isCapableOfOptimizedPopulate()
 *
 * Determine whether this association fully supports optimized populate.
 *
 * > Note that, if this is a plural association (a `collection` assoc. that is pointed at
 * > by `via` on the other side, or for which there IS no "other side"), then there will be
 * > a junction model in play.  For this utility to return `true`, that junction model must
 * > also be on the same datastore!
 *
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 * @param {String} attrName        [the name of the association in question]
 * @param {String} modelIdentity   [the identity of the model this association belongs to]
 * @param {Ref} orm                [the Waterline ORM instance]
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 * @returns {Boolean}
 */

module.exports = function isCapableOfOptimizedPopulate(attrName, modelIdentity, orm) {

  assert(_.isString(attrName), 'Must specify `attrName` as a string.  But instead, got: '+util.inspect(attrName, {depth:5})+'');
  assert(_.isString(modelIdentity), 'Must specify `modelIdentity` as a string.  But instead, got: '+util.inspect(modelIdentity, {depth:5})+'');
  assert(!_.isUndefined(orm), 'Must pass in `orm` (a reference to the Waterline ORM instance).  But instead, got: '+util.inspect(orm, {depth:5})+'');

  //  ╦  ╔═╗╔═╗╦╔═  ╦ ╦╔═╗  ┌─┐┌─┐┌─┐┌─┐┌─┐┬┌─┐┌┬┐┬┌─┐┌┐┌   ┬   ┌┬┐┌─┐┌┬┐┌─┐┬  ┌─┐
  //  ║  ║ ║║ ║╠╩╗  ║ ║╠═╝  ├─┤└─┐└─┐│ ││  │├─┤ │ ││ ││││  ┌┼─  ││││ │ ││├┤ │  └─┐
  //  ╩═╝╚═╝╚═╝╩ ╩  ╚═╝╩    ┴ ┴└─┘└─┘└─┘└─┘┴┴ ┴ ┴ ┴└─┘┘└┘  └┘   ┴ ┴└─┘─┴┘└─┘┴─┘└─┘

  // Look up the containing model for this association, and the attribute definition itself.
  var PrimaryWLModel = getModel(modelIdentity, orm);
  var attrDef = getAttribute(attrName, modelIdentity, orm);

  assert(attrDef.model || attrDef.collection, 'Attempting to check whether attribute `'+attrName+'` of model `'+modelIdentity+'` is capable of optimized populate, but it\'s not even an association!');

  // Look up the other, associated model.
  var otherModelIdentity = attrDef.model ? attrDef.model : attrDef.collection;
  var OtherWLModel = getModel(otherModelIdentity, orm);

  //  ┌─┐┬ ┬┌─┐┌─┐┬┌─  ┬ ┬┬ ┬┌─┐┌┬┐┬ ┬┌─┐┬─┐  ╔═╗╦  ╦    ┌┬┐┌─┐┌┬┐┌─┐┬  ┌─┐
  //  │  ├─┤├┤ │  ├┴┐  │││├─┤├┤  │ ├─┤├┤ ├┬┘  ╠═╣║  ║    ││││ │ ││├┤ │  └─┐
  //  └─┘┴ ┴└─┘└─┘┴ ┴  └┴┘┴ ┴└─┘ ┴ ┴ ┴└─┘┴└─  ╩ ╩╩═╝╩═╝  ┴ ┴└─┘─┴┘└─┘┴─┘└─┘
  //  ┌─┐┬─┐┌─┐  ┬ ┬┌─┐┬┌┐┌┌─┐  ┌┬┐┬ ┬┌─┐  ╔═╗╔═╗╔╦╗╔═╗  ╔╦╗╔═╗╔╦╗╔═╗╔═╗╔╦╗╔═╗╦═╗╔═╗
  //  ├─┤├┬┘├┤   │ │└─┐│││││ ┬   │ ├─┤├┤   ╚═╗╠═╣║║║║╣    ║║╠═╣ ║ ╠═╣╚═╗ ║ ║ ║╠╦╝║╣
  //  ┴ ┴┴└─└─┘  └─┘└─┘┴┘└┘└─┘   ┴ ┴ ┴└─┘  ╚═╝╩ ╩╩ ╩╚═╝  ═╩╝╩ ╩ ╩ ╩ ╩╚═╝ ╩ ╚═╝╩╚═╚═╝

  // Determine if the two models are using the same datastore.
  var isUsingSameDatastore = (PrimaryWLModel.datastore === OtherWLModel.datastore);

  // Now figure out if this association is using a junction
  // (i.e. is a bidirectional collection association, aka "many to many")
  // > If it is not, we'll leave `JunctionWLModel` as undefined.
  var JunctionWLModel;

  // Grab the mapped schema for the relationship
  var primarySchemaDef = PrimaryWLModel.schema[attrName];

  // Check if the primary schema def is pointing to a junction table
  var childWLModel = getModel(primarySchemaDef.referenceIdentity, orm);

  // If the child model has a junction or through table flag then the JunctionWLModel
  // gets set to childWLModel.
  if (_.has(Object.getPrototypeOf(childWLModel), 'junctionTable') && _.isBoolean(Object.getPrototypeOf(childWLModel).junctionTable)) {
    JunctionWLModel = childWLModel;
  }

  if (_.has(Object.getPrototypeOf(childWLModel), 'throughTable') && _.isPlainObject(Object.getPrototypeOf(childWLModel).throughTable)) {
    JunctionWLModel = childWLModel;
  }

  // If there is a junction, make sure to factor that in too.
  // (It has to be using the same datastore as the other two for it to count.)
  if (JunctionWLModel) {
    isUsingSameDatastore = isUsingSameDatastore && (JunctionWLModel.datastore === PrimaryWLModel.datastore);
  }//>-

  // Now, if any of the models involved is using a different datastore, then bail.
  if (!isUsingSameDatastore) {
    return false;
  }//-•

  // --•
  // IWMIH, we know that this association is using exactly ONE datastore.
  var relevantDatastoreName = PrimaryWLModel.datastore;

  // Finally, check to see if our datastore's configured adapter supports
  // optimized populates.
  var doesAdapterSupportOptimizedPopulates = false;
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // TODO: set `doesAdapterSupportOptimizedPopulates` to either `true` or `false`,
  // depending on whether this datastore's (`relevantDatastoreName`'s) adapter supports
  // optimized populates.
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  assert(_.isBoolean(doesAdapterSupportOptimizedPopulates), 'Internal bug in Waterline: The variable `doesAdapterSupportOptimizedPopulates` should be either true or false.  But instead, it is: '+util.inspect(doesAdapterSupportOptimizedPopulates, {depth:5})+'');

  return doesAdapterSupportOptimizedPopulates;

};

// Quick test:
/*```
require('./lib/waterline/utils/ontology/is-capable-of-optimized-populate')('pets', 'user', { collections: { user: { attributes: { id: { type: 'string', required: true, unique: true }, age: { type: 'number', required: false }, foo: { type: 'string', required: true }, pets: { collection: 'pet' } }, primaryKey: 'id', hasSchema: true}, pet: { attributes: { id: { type:'number', required: true, unique: true } }, primaryKey: 'id', hasSchema: true } } });
```*/
<commit_msg>handle the fact that the datastore is stored in an array from the old operation builder<commit_after>/**
 * Module dependencies
 */

var util = require('util');
var assert = require('assert');
var _ = require('@sailshq/lodash');
var getModel = require('./get-model');
var getAttribute = require('./get-attribute');

/**
 * isCapableOfOptimizedPopulate()
 *
 * Determine whether this association fully supports optimized populate.
 *
 * > Note that, if this is a plural association (a `collection` assoc. that is pointed at
 * > by `via` on the other side, or for which there IS no "other side"), then there will be
 * > a junction model in play.  For this utility to return `true`, that junction model must
 * > also be on the same datastore!
 *
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 * @param {String} attrName        [the name of the association in question]
 * @param {String} modelIdentity   [the identity of the model this association belongs to]
 * @param {Ref} orm                [the Waterline ORM instance]
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 * @returns {Boolean}
 */

module.exports = function isCapableOfOptimizedPopulate(attrName, modelIdentity, orm) {

  assert(_.isString(attrName), 'Must specify `attrName` as a string.  But instead, got: '+util.inspect(attrName, {depth:5})+'');
  assert(_.isString(modelIdentity), 'Must specify `modelIdentity` as a string.  But instead, got: '+util.inspect(modelIdentity, {depth:5})+'');
  assert(!_.isUndefined(orm), 'Must pass in `orm` (a reference to the Waterline ORM instance).  But instead, got: '+util.inspect(orm, {depth:5})+'');

  //  ╦  ╔═╗╔═╗╦╔═  ╦ ╦╔═╗  ┌─┐┌─┐┌─┐┌─┐┌─┐┬┌─┐┌┬┐┬┌─┐┌┐┌   ┬   ┌┬┐┌─┐┌┬┐┌─┐┬  ┌─┐
  //  ║  ║ ║║ ║╠╩╗  ║ ║╠═╝  ├─┤└─┐└─┐│ ││  │├─┤ │ ││ ││││  ┌┼─  ││││ │ ││├┤ │  └─┐
  //  ╩═╝╚═╝╚═╝╩ ╩  ╚═╝╩    ┴ ┴└─┘└─┘└─┘└─┘┴┴ ┴ ┴ ┴└─┘┘└┘  └┘   ┴ ┴└─┘─┴┘└─┘┴─┘└─┘

  // Look up the containing model for this association, and the attribute definition itself.
  var PrimaryWLModel = getModel(modelIdentity, orm);
  var attrDef = getAttribute(attrName, modelIdentity, orm);

  assert(attrDef.model || attrDef.collection, 'Attempting to check whether attribute `'+attrName+'` of model `'+modelIdentity+'` is capable of optimized populate, but it\'s not even an association!');

  // Look up the other, associated model.
  var otherModelIdentity = attrDef.model ? attrDef.model : attrDef.collection;
  var OtherWLModel = getModel(otherModelIdentity, orm);

  //  ┌─┐┬ ┬┌─┐┌─┐┬┌─  ┬ ┬┬ ┬┌─┐┌┬┐┬ ┬┌─┐┬─┐  ╔═╗╦  ╦    ┌┬┐┌─┐┌┬┐┌─┐┬  ┌─┐
  //  │  ├─┤├┤ │  ├┴┐  │││├─┤├┤  │ ├─┤├┤ ├┬┘  ╠═╣║  ║    ││││ │ ││├┤ │  └─┐
  //  └─┘┴ ┴└─┘└─┘┴ ┴  └┴┘┴ ┴└─┘ ┴ ┴ ┴└─┘┴└─  ╩ ╩╩═╝╩═╝  ┴ ┴└─┘─┴┘└─┘┴─┘└─┘
  //  ┌─┐┬─┐┌─┐  ┬ ┬┌─┐┬┌┐┌┌─┐  ┌┬┐┬ ┬┌─┐  ╔═╗╔═╗╔╦╗╔═╗  ╔╦╗╔═╗╔╦╗╔═╗╔═╗╔╦╗╔═╗╦═╗╔═╗
  //  ├─┤├┬┘├┤   │ │└─┐│││││ ┬   │ ├─┤├┤   ╚═╗╠═╣║║║║╣    ║║╠═╣ ║ ╠═╣╚═╗ ║ ║ ║╠╦╝║╣
  //  ┴ ┴┴└─└─┘  └─┘└─┘┴┘└┘└─┘   ┴ ┴ ┴└─┘  ╚═╝╩ ╩╩ ╩╚═╝  ═╩╝╩ ╩ ╩ ╩ ╩╚═╝ ╩ ╚═╝╩╚═╚═╝

  // Determine if the two models are using the same datastore.
  var isUsingSameDatastore = (_.first(PrimaryWLModel.datastore) === _.first(OtherWLModel.datastore));

  // Now figure out if this association is using a junction
  // (i.e. is a bidirectional collection association, aka "many to many")
  // > If it is not, we'll leave `JunctionWLModel` as undefined.
  var JunctionWLModel;

  // Grab the mapped schema for the relationship
  var primarySchemaDef = PrimaryWLModel.schema[attrName];

  // Check if the primary schema def is pointing to a junction table
  var childWLModel = getModel(primarySchemaDef.referenceIdentity, orm);

  // If the child model has a junction or through table flag then the JunctionWLModel
  // gets set to childWLModel.
  if (_.has(Object.getPrototypeOf(childWLModel), 'junctionTable') && _.isBoolean(Object.getPrototypeOf(childWLModel).junctionTable)) {
    JunctionWLModel = childWLModel;
  }

  if (_.has(Object.getPrototypeOf(childWLModel), 'throughTable') && _.isPlainObject(Object.getPrototypeOf(childWLModel).throughTable)) {
    JunctionWLModel = childWLModel;
  }

  // If there is a junction, make sure to factor that in too.
  // (It has to be using the same datastore as the other two for it to count.)
  if (JunctionWLModel) {
    isUsingSameDatastore = isUsingSameDatastore && (_.first(JunctionWLModel.datastore) === _.first(PrimaryWLModel.datastore));
  }//>-

  // Now, if any of the models involved is using a different datastore, then bail.
  if (!isUsingSameDatastore) {
    return false;
  }//-•

  // --•
  // IWMIH, we know that this association is using exactly ONE datastore.
  var relevantDatastoreName = PrimaryWLModel.datastore;

  // Finally, check to see if our datastore's configured adapter supports
  // optimized populates.
  var doesAdapterSupportOptimizedPopulates = false;
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // TODO: set `doesAdapterSupportOptimizedPopulates` to either `true` or `false`,
  // depending on whether this datastore's (`relevantDatastoreName`'s) adapter supports
  // optimized populates.
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  assert(_.isBoolean(doesAdapterSupportOptimizedPopulates), 'Internal bug in Waterline: The variable `doesAdapterSupportOptimizedPopulates` should be either true or false.  But instead, it is: '+util.inspect(doesAdapterSupportOptimizedPopulates, {depth:5})+'');

  return doesAdapterSupportOptimizedPopulates;

};

// Quick test:
/*```
require('./lib/waterline/utils/ontology/is-capable-of-optimized-populate')('pets', 'user', { collections: { user: { attributes: { id: { type: 'string', required: true, unique: true }, age: { type: 'number', required: false }, foo: { type: 'string', required: true }, pets: { collection: 'pet' } }, primaryKey: 'id', hasSchema: true}, pet: { attributes: { id: { type:'number', required: true, unique: true } }, primaryKey: 'id', hasSchema: true } } });
```*/
<|endoftext|>


<commit_before>define(['text!./results-list.html', 'app', 'lodash'], function(template, app, _) { 'use strict';

app.directive('resultsList',[ function () {
    return {
        restrict: 'EAC',
        template: template,
        replace: true,
        require : '^reportingDisplay',
        scope: {

        },
          link : function ($scope, $element, $attr, reportingDisplayCtrl)
        {
            $scope.expanded = false;

            $(function () {
                $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this country');
                $('.tree li.parent_li > span').on('click', function (e) {
                    var children = $(this).parent('li.parent_li').find(' > ul > li');
                    if (children.is(":visible")) {
                        children.hide('fast');
                        $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
                    } else {
                        children.show('fast');
                        $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
                    }
                    e.stopPropagation();
                });
            });

        }//link
    }; // return
  }]);  //app.directive('searchFilterCountries
});// define
<commit_msg>Created toggle function and dropped jQuery<commit_after>define(['text!./results-list.html', 'app', 'lodash'], function(template, app, _) { 'use strict';

app.directive('resultsList',['$timeout', function ($timeout) {
    return {
        restrict: 'EAC',
        template: template,
        replace: true,
        require : '^reportingDisplay',
        scope: {
          title: '@title',
          items: '=ngModel',
          facet: '@facet',
          numRecords: '=count' // total count of all children subquires needed for 0 result combinations
        },
          link : function ($scope, $element, $attr, reportingDisplayCtrl)
        {
            $scope.expanded = false;
            $scope.schemaNameMap={

                'nationalAssessment':'National Assesment'

            };
            $scope.$watch('items',function(){init();});

            //=======================================================================
    				//
    				//=======================================================================
    				function init() {
                  $scope.numCountries=_.size($scope.items);
                  if(!$scope.numRecords)$scope.numRecords=0;
                  console.log('result list items',$scope.items);
                  //initJQ();
    				}//

            //=======================================================================
    				//
    				//=======================================================================
    				$scope.toggleHide =function (show) {

                  if(show)
                        show=false;
                  else
                        show=true;
                  return show;

    				}//
            // //=======================================================================
    				// //
    				// //=======================================================================
    				// function initJQ() {
            //     $(function () {
            //
            //         $('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this country');
            //         $('.tree li.parent_li > span').on('click', function (e) {
            //             var children = $(this).parent('li.parent_li').find(' > ul > li');
            //             if (children.is(":visible")) {
            //
            //                 children.hide('fast');
            //                 $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
            //             } else {
            //                 children.show('fast');
            //                 $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
            //             }
            //             e.stopPropagation();
            //         });
            //     });
            // }//initJQ()

        }//link
    }; // return
  }]);  //app.directive('searchFilterCountries
});// define
<|endoftext|>


<commit_before>"use strict";

const {strict: assert} = require("assert");

const {mock_module, set_global, zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

const channel = mock_module("channel");
const ui = mock_module("ui");

mock_module("starred_messages", {
    add: () => {},

    remove: () => {},
});

const message_flags = zrequire("message_flags");

run_test("starred", () => {
    const message = {
        id: 50,
    };
    set_global("current_msg_list", {
        all_messages: () => [message],
        is_search: () => false,
    });
    let ui_updated;

    ui.update_starred_view = () => {
        ui_updated = true;
    };

    let posted_data;

    channel.post = (opts) => {
        assert.equal(opts.url, "/json/messages/flags");
        posted_data = opts.data;
    };

    message_flags.toggle_starred_and_update_server(message);

    assert(ui_updated);

    assert.deepEqual(posted_data, {
        messages: "[50]",
        flag: "starred",
        op: "add",
    });

    assert.deepEqual(message, {
        id: 50,
        starred: true,
    });

    ui_updated = false;

    message_flags.toggle_starred_and_update_server(message);

    assert(ui_updated);

    assert.deepEqual(posted_data, {
        messages: "[50]",
        flag: "starred",
        op: "remove",
    });

    assert.deepEqual(message, {
        id: 50,
        starred: false,
    });
});
run_test("read", () => {
    // Way to capture posted info in every request
    let channel_post_opts;
    channel.post = (opts) => {
        channel_post_opts = opts;
    };

    // For testing purpose limit the batch size value to 5 instead of 1000
    message_flags.__Rewire__("_unread_batch_size", 5);
    let msgs_to_flag_read = [
        {locally_echoed: false, id: 1},
        {locally_echoed: false, id: 2},
        {locally_echoed: false, id: 3},
        {locally_echoed: false, id: 4},
        {locally_echoed: false, id: 5},
        {locally_echoed: false, id: 6},
        {locally_echoed: false, id: 7},
    ];
    message_flags.send_read(msgs_to_flag_read);
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[1,2,3,4,5]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });

    // Mock successful flagging of ids
    let success_response_data = {
        messages: [1, 2, 3, 4, 5],
    };
    channel_post_opts.success(success_response_data);
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[6,7]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });
    success_response_data = {
        messages: [6, 7],
    };
    channel_post_opts.success(success_response_data);

    // Don't flag locally echoed messages as read
    const local_msg_1 = {locally_echoed: true, id: 1};
    const local_msg_2 = {locally_echoed: true, id: 2};
    msgs_to_flag_read = [
        local_msg_1,
        local_msg_2,
        {locally_echoed: false, id: 3},
        {locally_echoed: false, id: 4},
        {locally_echoed: false, id: 5},
        {locally_echoed: false, id: 6},
        {locally_echoed: false, id: 7},
    ];
    message_flags.send_read(msgs_to_flag_read);
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[3,4,5,6,7]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });

    // Mark them non local
    local_msg_1.locally_echoed = false;
    local_msg_2.locally_echoed = false;

    // Mock successful flagging of ids
    success_response_data = {
        messages: [3, 4, 5, 6, 7],
    };
    channel_post_opts.success(success_response_data);

    // Former locally echoed messages flagging retried
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[1,2]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });
});
<commit_msg>node tests: Add overrides for message_flags.<commit_after>"use strict";

const {strict: assert} = require("assert");

const {mock_module, set_global, with_field, zrequire} = require("../zjsunit/namespace");
const {run_test} = require("../zjsunit/test");

const channel = mock_module("channel");
const ui = mock_module("ui");

mock_module("starred_messages", {
    add: () => {},

    remove: () => {},
});

const message_flags = zrequire("message_flags");

run_test("starred", (override) => {
    const message = {
        id: 50,
    };
    set_global("current_msg_list", {
        all_messages: () => [message],
        is_search: () => false,
    });
    let ui_updated;

    ui.update_starred_view = () => {
        ui_updated = true;
    };

    let posted_data;

    override(channel, "post", (opts) => {
        assert.equal(opts.url, "/json/messages/flags");
        posted_data = opts.data;
    });

    message_flags.toggle_starred_and_update_server(message);

    assert(ui_updated);

    assert.deepEqual(posted_data, {
        messages: "[50]",
        flag: "starred",
        op: "add",
    });

    assert.deepEqual(message, {
        id: 50,
        starred: true,
    });

    ui_updated = false;

    message_flags.toggle_starred_and_update_server(message);

    assert(ui_updated);

    assert.deepEqual(posted_data, {
        messages: "[50]",
        flag: "starred",
        op: "remove",
    });

    assert.deepEqual(message, {
        id: 50,
        starred: false,
    });
});
run_test("read", (override) => {
    // Way to capture posted info in every request
    let channel_post_opts;
    override(channel, "post", (opts) => {
        channel_post_opts = opts;
    });

    // For testing purpose limit the batch size value to 5 instead of 1000
    function send_read(messages) {
        with_field(message_flags, "_unread_batch_size", 5, () => {
            message_flags.send_read(messages);
        });
    }

    let msgs_to_flag_read = [
        {locally_echoed: false, id: 1},
        {locally_echoed: false, id: 2},
        {locally_echoed: false, id: 3},
        {locally_echoed: false, id: 4},
        {locally_echoed: false, id: 5},
        {locally_echoed: false, id: 6},
        {locally_echoed: false, id: 7},
    ];
    send_read(msgs_to_flag_read);
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[1,2,3,4,5]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });

    // Mock successful flagging of ids
    let success_response_data = {
        messages: [1, 2, 3, 4, 5],
    };
    channel_post_opts.success(success_response_data);
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[6,7]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });
    success_response_data = {
        messages: [6, 7],
    };
    channel_post_opts.success(success_response_data);

    // Don't flag locally echoed messages as read
    const local_msg_1 = {locally_echoed: true, id: 1};
    const local_msg_2 = {locally_echoed: true, id: 2};
    msgs_to_flag_read = [
        local_msg_1,
        local_msg_2,
        {locally_echoed: false, id: 3},
        {locally_echoed: false, id: 4},
        {locally_echoed: false, id: 5},
        {locally_echoed: false, id: 6},
        {locally_echoed: false, id: 7},
    ];
    send_read(msgs_to_flag_read);
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[3,4,5,6,7]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });

    // Mark them non local
    local_msg_1.locally_echoed = false;
    local_msg_2.locally_echoed = false;

    // Mock successful flagging of ids
    success_response_data = {
        messages: [3, 4, 5, 6, 7],
    };
    channel_post_opts.success(success_response_data);

    // Former locally echoed messages flagging retried
    assert.deepEqual(channel_post_opts, {
        url: "/json/messages/flags",
        idempotent: true,
        data: {
            messages: "[1,2]",
            op: "add",
            flag: "read",
        },
        success: channel_post_opts.success,
    });
});
<|endoftext|>


<commit_before>/*
primecolor.js
Copyright 2014-2015 Edward L. Platt <ed@elplatt.com>
Distributed under BSD 3-clause license
*/
PrimeColor = {
    seed: { "red": 0, "green": 0, "blue": 0 },
    setSeed: function (r, g, b) {
        this.seed = {
            "red": r,
            "green": g,
            "blue": b
        }
    },
    getColorHex: function (i) {
        var r = (i * 63) % 256;
        var g = (i * 101) % 256;
        var b = (i * 167) % 256;
        r = (r + this.seed.red) % 256;
        r = 8;
        g = (g + this.seed.green) % 256;
        b = (b + this.seed.blue) % 256;
        rh = r.toString(16);
        if (rh.length == 1) { rh = "0" + rh; }
        gh = g.toString(16);
        if (gh.length == 1) { gh = "0" + gh; }
        bh = b.toString(16);
        if (bh.length == 1) { bh = "0" + bh; }
        return "#" + rh + gh + bh;
    }
}<commit_msg>Remove debugging from primecolor.<commit_after>/*
primecolor.js
Copyright 2014-2015 Edward L. Platt <ed@elplatt.com>
Distributed under BSD 3-clause license
*/
PrimeColor = {
    seed: { "red": 0, "green": 0, "blue": 0 },
    setSeed: function (r, g, b) {
        this.seed = {
            "red": r,
            "green": g,
            "blue": b
        }
    },
    getColorHex: function (i) {
        var r = (i * 63) % 256;
        var g = (i * 101) % 256;
        var b = (i * 167) % 256;
        r = (r + this.seed.red) % 256;
        g = (g + this.seed.green) % 256;
        b = (b + this.seed.blue) % 256;
        rh = r.toString(16);
        if (rh.length == 1) { rh = "0" + rh; }
        gh = g.toString(16);
        if (gh.length == 1) { gh = "0" + gh; }
        bh = b.toString(16);
        if (bh.length == 1) { bh = "0" + bh; }
        return "#" + rh + gh + bh;
    }
}<|endoftext|>


<commit_before>module.exports = function(optimist) {
	optimist
		.boolean("help").alias("help", "h").alias("help", "?").describe("help")
		.string("config").describe("config")
		.string("env").describe("env", "Enviroment passed to the config, when it is a function")
		.string("context").describe("context")
		.string("entry").describe("entry")
		.string("module-bind").describe("module-bind")
		.string("module-bind-post").describe("module-bind-post")
		.string("module-bind-pre").describe("module-bind-pre")
		.string("output-path").describe("output-path")
		.string("output-file").describe("output-file")
		.string("output-chunk-file").describe("output-chunk-file")
		.string("output-source-map-file").describe("output-source-map-file")
		.string("output-public-path").describe("output-public-path")
		.string("output-jsonp-function").describe("output-jsonp-function")
		.boolean("output-pathinfo").describe("output-pathinfo")
		.string("output-library").describe("output-library")
		.string("output-library-target").describe("output-library-target")
		.string("records-input-path").describe("records-input-path")
		.string("records-output-path").describe("records-output-path")
		.string("records-path").describe("records-path")
		.string("define").describe("define")
		.string("target").describe("target")
		.boolean("cache").describe("cache").default("cache", true)
		.boolean("watch").alias("watch", "w").describe("watch")
		.boolean("watch-stdin").alias("watch-stdin", "stdin").describe("watch which closes when stdin ends")
		.describe("watch-aggregate-timeout")
		.describe("watch-poll")
		.boolean("hot").describe("hot")
		.boolean("debug").describe("debug")
		.string("devtool").describe("devtool")
		.boolean("progress").describe("progress")
		.string("resolve-alias").describe("resolve-alias")
		.string("resolve-loader-alias").describe("resolve-loader-alias")
		.describe("optimize-max-chunks")
		.describe("optimize-min-chunk-size")
		.boolean("optimize-minimize").describe("optimize-minimize")
		.boolean("optimize-dedupe").describe("optimize-dedupe")
		.string("prefetch").describe("prefetch")
		.string("provide").describe("provide")
		.boolean("labeled-modules").describe("labeled-modules")
		.string("plugin").describe("plugin")
		.boolean("bail").describe("bail")
		.boolean("profile").describe("profile")
		.boolean("d").describe("d", "shortcut for --debug --devtool sourcemap --output-pathinfo")
		.boolean("p").describe("p", "shortcut for --optimize-minimize");
};
<commit_msg>comments for the CLI<commit_after>module.exports = function(optimist) {
	optimist
		.boolean("help").alias("help", "h").alias("help", "?").describe("help")
		.string("config").describe("config", "Path to the config file")
		.string("env").describe("env", "Enviroment passed to the config, when it is a function")
		.string("context").describe("context", "The root directory for resolving entry point and stats")
		.string("entry").describe("entry", "The entry point")
		.string("module-bind").describe("module-bind", "Bind an extension to a loader")
		.string("module-bind-post").describe("module-bind-post")
		.string("module-bind-pre").describe("module-bind-pre")
		.string("output-path").describe("output-path", "The output path for compilation assets")
		.string("output-file").describe("output-file", "The output filename of the bundle")
		.string("output-chunk-file").describe("output-chunk-file", "The output filename for additional chunks")
		.string("output-source-map-file").describe("output-source-map-file", "The output filename for the SourceMap")
		.string("output-public-path").describe("output-public-path", "The public path for the assets")
		.string("output-jsonp-function").describe("output-jsonp-function", "The name of the jsonp function used for chunk loading")
		.boolean("output-pathinfo").describe("output-pathinfo", "Include a comment with the request for every dependency")
		.string("output-library").describe("output-library", "Expose the exports of the entry point as library")
		.string("output-library-target").describe("output-library-target", "The type for exposing the exports of the entry point as library")
		.string("records-input-path").describe("records-input-path", "Path to the records file (reading)")
		.string("records-output-path").describe("records-output-path", "Path to the records file (writing)")
		.string("records-path").describe("records-path", "Path to the records file")
		.string("define").describe("define", "Define any free var in the bundle")
		.string("target").describe("target", "The targeted execution enviroment")
		.boolean("cache").describe("cache", "Enable in memory caching").default("cache", true)
		.boolean("watch").alias("watch", "w").describe("watch", "Watch the filesystem for changes")
		.boolean("watch-stdin").alias("watch-stdin", "stdin").describe("Exit the process when stdin is closed")
		.describe("watch-aggregate-timeout", "Timeout for gathering changes while watching")
		.describe("watch-poll", "The polling intervall for watching (also enable polling)")
		.boolean("hot").describe("hot", "Enables Hot Module Replacement")
		.boolean("debug").describe("debug", "Switch loaders to debug mode")
		.string("devtool").describe("devtool", "Enable devtool for better debugging experience")
		.boolean("progress").describe("progress", "Print compilation progress in percentage")
		.string("resolve-alias").describe("resolve-alias", "Setup a module alias for resolving")
		.string("resolve-loader-alias").describe("resolve-loader-alias", "Setup a loader alias for resolving")
		.describe("optimize-max-chunks", "Try to keep the chunk count below a limit")
		.describe("optimize-min-chunk-size", "Try to keep the chunk size above a limit")
		.boolean("optimize-minimize").describe("optimize-minimize", "Minimize javascript and switches loaders to minimizing")
		.boolean("optimize-dedupe").describe("optimize-dedupe", "Optimize duplicate module sources in the bundle")
		.string("prefetch").describe("prefetch", "Prefetch this request")
		.string("provide").describe("provide", "Provide these modules as free vars in all modules")
		.boolean("labeled-modules").describe("labeled-modules", "Enables labeled modules")
		.string("plugin").describe("plugin", "Load this plugin")
		.boolean("bail").describe("bail", "Abort the compilation on first error")
		.boolean("profile").describe("profile", "Profile the compilation and include information in stats")
		.boolean("d").describe("d", "shortcut for --debug --devtool eval-check-module-source-map --output-pathinfo")
		.boolean("p").describe("p", "shortcut for --optimize-minimize --define process.env.NODE_ENV=\"production\"");
};
<|endoftext|>


<commit_before>export function initialize() {
  let application = arguments[1] || arguments[0];
  application.deferReadiness();
  setTimeout(() => {
    application.advanceReadiness();
  }, 1500);
}

export default {
  name: 'wait',
  initialize
};
<commit_msg>chore: setTimeout -> run.later for Ember 2.x compatibility<commit_after>import { later } from '@ember/runloop';

export function initialize() {
  let application = arguments[1] || arguments[0];
  application.deferReadiness();
  later(() => {
    application.advanceReadiness();
  }, 1500);
}

export default {
  name: 'wait',
  initialize
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { injectIntl, intlShape, defineMessages, FormattedMessage } from 'react-intl'

class Publication extends React.Component {
  constructor (props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
    this.handleReservationClick = this.handleReservationClick.bind(this)
  }

  renderTitle (publication) {
    let title = publication.mainTitle
    if (publication.partTitle) {
      title += ` — ${publication.partTitle}`
    }
    return title
  }

  handleClick () {
    this.props.expandSubResource(this.props.publication.id, true)
  }

  handleReservationClick (event) {
    event.preventDefault()
    event.stopPropagation()
    this.props.startReservation(this.props.publication.recordId)
  }

  render () {
    const publication = this.props.publication
    const languages = [ ...new Set(publication.languages.map(language => this.props.intl.formatMessage({ id: language }))) ]
    const formats = [ ...new Set(publication.formats.map(format => this.props.intl.formatMessage({ id: format }))) ]
    return (
      <article onClick={this.handleClick} className={this.props.open ? 'single-publication open' : 'single-publication'}
               data-automation-id={`publication_${publication.uri}`} data-formats={formats}>

<FormattedMessage {...(publication.available ? messages.available : messages.unavailable)} />

                {this.renderTitle(publication)}

                {publication.publicationYear}
              ,

                {languages.join(', ')}

          {publication.items.length > 0
            ? (<button className='grey-btn' type='button'>

                <FormattedMessage {...messages.reserve} />

          </button>) : null}

          Vis status
          <button className='show-status-arrow' type='button'>

          </button>

    )
  }
}

Publication.propTypes = {
  publication: PropTypes.object.isRequired,
  expandSubResource: PropTypes.func.isRequired,
  startReservation: PropTypes.func.isRequired,
  open: PropTypes.bool,
  intl: intlShape.isRequired
}

const messages = defineMessages({
  available: {
    id: 'Publication.available',
    description: 'The text displayed when the publication is available',
    defaultMessage: 'Available'
  },
  unavailable: {
    id: 'Publication.unavailable',
    description: 'The text displayed when the publication unavailable',
    defaultMessage: 'Unavailable'
  },
  reserve: {
    id: 'Publication.reserve',
    description: 'The button that allows users to reserve a publication',
    defaultMessage: 'Reserve'
  }
})

export default injectIntl(Publication)
<commit_msg>patron-client: Remove comma when not needed<commit_after>import React, { PropTypes } from 'react'
import { injectIntl, intlShape, defineMessages, FormattedMessage } from 'react-intl'

class Publication extends React.Component {
  constructor (props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
    this.handleReservationClick = this.handleReservationClick.bind(this)
  }

  renderTitle (publication) {
    let title = publication.mainTitle
    if (publication.partTitle) {
      title += ` — ${publication.partTitle}`
    }
    return title
  }

  handleClick () {
    this.props.expandSubResource(this.props.publication.id, true)
  }

  handleReservationClick (event) {
    event.preventDefault()
    event.stopPropagation()
    this.props.startReservation(this.props.publication.recordId)
  }

  render () {
    const publication = this.props.publication
    const languages = [ ...new Set(publication.languages.map(language => this.props.intl.formatMessage({ id: language }))) ]
    const formats = [ ...new Set(publication.formats.map(format => this.props.intl.formatMessage({ id: format }))) ]
    return (
      <article onClick={this.handleClick} className={this.props.open ? 'single-publication open' : 'single-publication'}
               data-automation-id={`publication_${publication.uri}`} data-formats={formats}>

<FormattedMessage {...(publication.available ? messages.available : messages.unavailable)} />

                {this.renderTitle(publication)}

                {publication.publicationYear}
              {publication.publicationYear && languages.length > 0 ? ',' : null}

                {languages.join(', ')}

          {publication.items.length > 0
            ? (<button className='grey-btn' type='button'>

                <FormattedMessage {...messages.reserve} />

          </button>) : null}

          Vis status
          <button className='show-status-arrow' type='button'>

          </button>

    )
  }
}

Publication.propTypes = {
  publication: PropTypes.object.isRequired,
  expandSubResource: PropTypes.func.isRequired,
  startReservation: PropTypes.func.isRequired,
  open: PropTypes.bool,
  intl: intlShape.isRequired
}

const messages = defineMessages({
  available: {
    id: 'Publication.available',
    description: 'The text displayed when the publication is available',
    defaultMessage: 'Available'
  },
  unavailable: {
    id: 'Publication.unavailable',
    description: 'The text displayed when the publication unavailable',
    defaultMessage: 'Unavailable'
  },
  reserve: {
    id: 'Publication.reserve',
    description: 'The button that allows users to reserve a publication',
    defaultMessage: 'Reserve'
  }
})

export default injectIntl(Publication)
<|endoftext|>


<commit_before>var creep_baseOp = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (!creep.memory.initialSetup) {
            setupCreepMemory(creep);
        }
        //Resource generation
        var totalOps = creep.carry[RESOURCE_OPS];
        if (totalOps < 600 && creep.memory.cooldowns.GENERATE_OPS <= Game.time) {
            if (creep.usePower(PWR_GENERATE_OPS) == OK) {
                creep.memory.cooldowns.GENERATE_OPS = Game.time + 50;
                totalOps = totalOps + 6;
            }
        }

        //Note - Empowered sources generate 7,000 per 300 ticks (lvl 4)

        //LIMITED ACTIONS (Due to Ops expenses)
        //When under attack - OPERATE_TOWER/OPERATE_SPAWN
        //When RunningAssault flag exists - OPERATE_SPAWN
        //if creep.memory.cooldowns.OPERATE_SPAWN <= Game.time && totalOps >= 100 && checkForSpawnNeed(creep)

        if (!creep.memory.jobFocus) {
            //Try to find work that needs doing
            creep.memory.jobFocus = findNeededWork(creep);
        }

        //Main work loop
        //Should change to focus on a job until it's done (Exception : Keeping creep alive)
        if (creep.ticksToLive <= 100 && Memory.powerSpawnList[creep.room.name]) {
            var powerSpawnTarget = Game.getObjectById(Memory.powerSpawnList[creep.room.name][0]);
            if (powerSpawnTarget) {
                var renewResult = creep.renew(powerSpawnTarget);
                if (renewResult == ERR_NOT_IN_RANGE) {
                    creep.travelTo(powerSpawnTarget);
                }
            }
        } else if (creep.memory.jobFocus == 'OPERATE_EXTENSION') {
            var useResult = creep.usePower(PWR_OPERATE_EXTENSION, creep.room.storage);
            if (useResult == ERR_NOT_IN_RANGE) {
                creep.travelTo(creep.room.storage, {
                    range: 3
                });
            } else if (useResult == OK) {
                creep.memory.cooldowns.OPERATE_EXTENSION = Game.time + 50;
                totalOps = totalOps - 2;
                creep.memory.jobFocus = undefined;
            }
        } else if (creep.memory.jobFocus == 'REGEN_SOURCE') {
            var targetSource;
            if (creep.memory.empoweredSources[0] <= Game.time) {
                targetSource = Game.getObjectById(creep.memory.sources[0]);
            } else {
                targetSource = Game.getObjectById(creep.memory.sources[1]);
            }

            var useResult = creep.usePower(PWR_REGEN_SOURCE, targetSource);
            if (useResult == ERR_NOT_IN_RANGE) {
                creep.travelTo(targetSource, {
                    range: 3
                });
            } else if (useResult == OK) {
                creep.memory.cooldowns.REGEN_SOURCE = Game.time + 100;
                if (targetSource.id == creep.memory.sources[0]) {
                    creep.memory.empoweredSources[0] = Game.time + 300;
                } else {
                    creep.memory.empoweredSources[1] = Game.time + 300;
                }
                creep.memory.jobFocus = undefined;
            }
        } else if (creep.memory.jobFocus == 'OPERATE_LAB') {
            var targetLab = getNeededLab(creep);
            //Creep will do nothing if lab is undefined, add handling?
            if (targetLab) {
                var useResult = creep.usePower(PWR_OPERATE_LAB, targetLab);
                if (useResult == ERR_NOT_IN_RANGE) {
                    creep.travelTo(targetLab, {
                        range: 3
                    });
                } else if (useResult == OK) {
                    creep.memory.cooldowns.OPERATE_LAB = Game.time + 50;
                    updateLabBoost(creep);
                    creep.memory.jobFocus = undefined;
                }
            }
        } else if (creep.memory.jobFocus == 'FILL_SPAWNS') {
            //Power only fills extentions, fill spawns.
            if (creep.carry[RESOURCE_ENERGY] <= 900) {
                let neededAmount = 2000 - creep.carry[RESOURCE_ENERGY];
                creep.memory.structureTarget = undefined;
                //Get from storage
                //Check overflow link first
                var linkTarget = undefined;
                if (creep.memory.linkSource) {
                    linkTarget = Game.getObjectById(creep.memory.linkSource)
                }
                if (linkTarget && linkTarget.energy >= 400) {
                    if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(linkTarget, {
                            ignoreRoads: true
                        });
                    }
                } else {
                    var storageTarget = creep.room.storage;
                    if (creep.room.terminal && storageTarget.store[RESOURCE_ENERGY] < 250000 && creep.room.terminal.store[RESOURCE_ENERGY] > 31000) {
                        storageTarget = creep.room.terminal;
                    }
                    if (storageTarget) {
                        let withdrawResult = creep.withdraw(storageTarget, RESOURCE_ENERGY, neededAmount)
                        if (withdrawResult == ERR_NOT_IN_RANGE) {
                            creep.travelTo(storageTarget, {
                                ignoreRoads: true
                            });
                        } else if (withdrawResult == ERR_NOT_ENOUGH_RESOURCES) {
                            creep.withdraw(storageTarget, RESOURCE_ENERGY)
                        }
                    }
                }
            } else {
                let savedTarget = Game.getObjectById(creep.memory.structureTarget);
                var getNewStructure = false;
                if (savedTarget && savedTarget.energy < savedTarget.energyCapacity) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(savedTarget);
                    } else {
                        creep.memory.jobFocus = undefined;
                        creep.memory.structureTarget = undefined;
                    }
                }
                if (!creep.memory.structureTarget) {
                    var target = undefined;
                    target = creep.pos.findClosestByPath(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });

                    if (!target) {
                        //Find closest by path will not return anything if path is blocked
                        target = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                            }
                        });
                    }

                    if (target) {
                        if (creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.travelTo(target);
                            creep.memory.structureTarget = target.id;
                        } else {
                            //OK
                            creep.memory.jobFocus = undefined;
                            creep.memory.structureTarget = undefined;
                        }
                    }
                }
            }
        } else {
            //Busywork - dump overflow link
            if (creep.carry[RESOURCE_ENERGY] <= 1200) {
                var linkTarget = undefined;
                creep.memory.structureTarget = undefined;
                if (creep.memory.linkSource) {
                    linkTarget = Game.getObjectById(creep.memory.linkSource)
                }
                if (linkTarget && linkTarget.energy >= 400) {
                    if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(linkTarget, {
                            ignoreRoads: true
                        });
                    }
                }
            } else {
                //Saved Target
                if (creep.memory.structureTarget) {
                    var thisTarget = Game.getObjectById(creep.memory.structureTarget);
                    if (thisTarget) {
                        let tResult = creep.transfer(thisTarget, RESOURCE_ENERGY)
                        if (tResult == ERR_NOT_IN_RANGE) {
                            creep.travelTo(thisTarget);
                        } else if (tResult == OK) {
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        creep.memory.structureTarget = undefined;
                    }
                } else {
                    //Terminal
                    let foundWork = false;
                    if (creep.room.terminal) {
                        let targetEnergy = 0;
                        if (creep.room.storage) {
                            if (creep.room.storage.store[RESOURCE_ENERGY] >= 275000) {
                                targetEnergy = 60000;
                            } else if (creep.room.storage.store[RESOURCE_ENERGY] >= 50000) {
                                targetEnergy = 30000;
                            }
                        }
                        if (creep.room.terminal.store[RESOURCE_ENERGY] < targetEnergy && (creep.room.terminal.storeCapacity - 5000) > _.sum(creep.room.terminal.store)) {
                            foundWork = true;
                            creep.memory.structureTarget = creep.room.terminal.id;
                            if (creep.transfer(creep.room.terminal, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.travelTo(creep.room.terminal);
                            }
                        }
                    }
                    //PowerSpawn/Nuker
                    if (!foundWork && creep.room.controller.level == 8) {
                        var target = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_POWER_SPAWN ||
                                    structure.structureType == STRUCTURE_NUKER) && structure.energy < structure.energyCapacity;
                            }
                        });
                        if (target) {
                            foundWork = true;
                            creep.memory.structureTarget = target.id;
                            if (creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.travelTo(target);
                            } else {
                                creep.memory.structureTarget = undefined;
                            }
                        }
                    }

                    if (!foundWork && creep.room.storage && creep.transfer(creep.room.storage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.memory.structureTarget = creep.room.storage.id;
                        creep.travelTo(creep.room.storage);
                    }
                }

            }
        }

        let talkingCreeps = creep.pos.findInRange(FIND_MY_CREEPS, 1, {
            filter: (thisCreep) => (creep.id != thisCreep.id && thisCreep.saying && thisCreep.saying != "\u261D\uD83D\uDE3C" && thisCreep.saying != "\uD83D\uDC4C\uD83D\uDE39")
        })
        if (talkingCreeps.length) {
            let coords = talkingCreeps[0].saying.split(";");
            if (coords.length == 2 && creep.pos.x == parseInt(coords[0]) && creep.pos.y == parseInt(coords[1])) {
                //Standing in the way of a creep
                let thisDirection = creep.pos.getDirectionTo(talkingCreeps[0].pos);
                creep.move(thisDirection);
                creep.say("\uD83D\uDCA6", true);
            }
        }
    }
};

function setupCreepMemory(creep) {
    var cooldownObject = {};
    cooldownObject.GENERATE_OPS = Game.time;
    cooldownObject.OPERATE_SPAWN = Game.time;
    cooldownObject.OPERATE_TOWER = Game.time;
    cooldownObject.OPERATE_LAB = Game.time;
    cooldownObject.OPERATE_EXTENSION = Game.time;
    cooldownObject.REGEN_SOURCE = Game.time;
    creep.memory.cooldowns = cooldownObject;

    creep.memory.sources = Memory.sourceList[creep.room.name];
    creep.memory.empoweredSources = [Game.time, Game.time];

    creep.memory.spawnList = [];
    creep.memory.empoweredSpawns = [];
    var roomSpawns = creep.room.find(FIND_MY_STRUCTURES, {
        filter: {
            structureType: STRUCTURE_SPAWN
        }
    });
    for (var thisSpawn in roomSpawns) {
        creep.memory.spawnList.push(roomSpawns[thisSpawn].id);
        creep.memory.empoweredSpawns.push(Game.time);
    }

    //Can ignore first 3 labs, never set to run reactions
    creep.memory.empoweredLabs = [Game.time, Game.time, Game.time, Game.time, Game.time, Game.time, Game.time]

    if (!Game.flags[creep.room.name + "RoomOperator"]) {
        Game.rooms[creep.room.name].createFlag(47, 2, creep.room.name + "RoomOperator");
    }

    if (Memory.linkList[creep.room.name].length >= 4) {
        creep.memory.linkSource = Memory.linkList[creep.room.name][3];
    }

    creep.memory.jobFocus = undefined;

    creep.memory.initialSetup = true;
}

function findNeededWork(creep) {
    if (creep.memory.cooldowns.OPERATE_EXTENSION <= Game.time && totalOps >= 2 && creep.room.storage && creep.room.energyAvailable < creep.room.energyCapacityAvailable) {
        return 'OPERATE_EXTENSION';
    } else if (creep.memory.cooldowns.REGEN_SOURCE <= Game.time && (creep.memory.empoweredSources[0] <= Game.time || creep.memory.empoweredSources[1] <= Game.time)) {
        return 'REGEN_SOURCE';
    } else if (!Game.flags[creep.room.name + "WarBoosts"] && creep.memory.cooldowns.OPERATE_LAB <= Game.time && totalOps >= 10 && checkForLabNeed(creep)) {
        return 'OPERATE_LAB';
    } else if (creep.room.energyAvailable < creep.room.energyCapacityAvailable) {
        return 'FILL_SPAWNS';
    }
}

function checkForLabNeed(creep) {
    for (var thisLab in creep.memory.empoweredLabs) {
        if (creep.memory.empoweredLabs[thisLab] <= Game.time) {
            return true;
        }
    }
    return false;
}

function getNeededLab(creep) {
    var labIndex = 3;
    for (var thisLab in creep.memory.empoweredLabs) {
        if (creep.memory.empoweredLabs[thisLab] <= Game.time) {
            var thisLab = Game.getObjectById(Memory.labList[creep.room.name][labIndex]);
            if (thisLab) {
                return thisLab;
            }
        }
        labIndex++;
    }
    return undefined;
}

function updateLabBoost(creep) {
    for (var thisLab in creep.memory.empoweredLabs) {
        if (creep.memory.empoweredLabs[thisLab] <= Game.time) {
            creep.memory.empoweredLabs[thisLab] = Game.time + 1000;
            break;
        }
    }
}

function checkForSpawnNeed(creep) {
    for (var thisSpawnCD in creep.memory.empoweredSpawns) {
        if (creep.memory.empoweredSpawns[thisSpawnCD] <= Game.time) {
            return true;
        }
    }
    return false;
}

module.exports = creep_baseOp;<commit_msg>Missed default case<commit_after>var creep_baseOp = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (!creep.memory.initialSetup) {
            setupCreepMemory(creep);
        }
        //Resource generation
        var totalOps = creep.carry[RESOURCE_OPS];
        if (totalOps < 600 && creep.memory.cooldowns.GENERATE_OPS <= Game.time) {
            if (creep.usePower(PWR_GENERATE_OPS) == OK) {
                creep.memory.cooldowns.GENERATE_OPS = Game.time + 50;
                totalOps = totalOps + 6;
            }
        }

        //Note - Empowered sources generate 7,000 per 300 ticks (lvl 4)

        //LIMITED ACTIONS (Due to Ops expenses)
        //When under attack - OPERATE_TOWER/OPERATE_SPAWN
        //When RunningAssault flag exists - OPERATE_SPAWN
        //if creep.memory.cooldowns.OPERATE_SPAWN <= Game.time && totalOps >= 100 && checkForSpawnNeed(creep)

        if (!creep.memory.jobFocus) {
            //Try to find work that needs doing
            creep.memory.jobFocus = findNeededWork(creep);
        }

        //Main work loop
        //Should change to focus on a job until it's done (Exception : Keeping creep alive)
        if (creep.ticksToLive <= 100 && Memory.powerSpawnList[creep.room.name]) {
            var powerSpawnTarget = Game.getObjectById(Memory.powerSpawnList[creep.room.name][0]);
            if (powerSpawnTarget) {
                var renewResult = creep.renew(powerSpawnTarget);
                if (renewResult == ERR_NOT_IN_RANGE) {
                    creep.travelTo(powerSpawnTarget);
                }
            }
        } else if (creep.memory.jobFocus == 'OPERATE_EXTENSION') {
            var useResult = creep.usePower(PWR_OPERATE_EXTENSION, creep.room.storage);
            if (useResult == ERR_NOT_IN_RANGE) {
                creep.travelTo(creep.room.storage, {
                    range: 3
                });
            } else if (useResult == OK) {
                creep.memory.cooldowns.OPERATE_EXTENSION = Game.time + 50;
                totalOps = totalOps - 2;
                creep.memory.jobFocus = undefined;
            }
        } else if (creep.memory.jobFocus == 'REGEN_SOURCE') {
            var targetSource;
            if (creep.memory.empoweredSources[0] <= Game.time) {
                targetSource = Game.getObjectById(creep.memory.sources[0]);
            } else {
                targetSource = Game.getObjectById(creep.memory.sources[1]);
            }

            var useResult = creep.usePower(PWR_REGEN_SOURCE, targetSource);
            if (useResult == ERR_NOT_IN_RANGE) {
                creep.travelTo(targetSource, {
                    range: 3
                });
            } else if (useResult == OK) {
                creep.memory.cooldowns.REGEN_SOURCE = Game.time + 100;
                if (targetSource.id == creep.memory.sources[0]) {
                    creep.memory.empoweredSources[0] = Game.time + 300;
                } else {
                    creep.memory.empoweredSources[1] = Game.time + 300;
                }
                creep.memory.jobFocus = undefined;
            }
        } else if (creep.memory.jobFocus == 'OPERATE_LAB') {
            var targetLab = getNeededLab(creep);
            //Creep will do nothing if lab is undefined, add handling?
            if (targetLab) {
                var useResult = creep.usePower(PWR_OPERATE_LAB, targetLab);
                if (useResult == ERR_NOT_IN_RANGE) {
                    creep.travelTo(targetLab, {
                        range: 3
                    });
                } else if (useResult == OK) {
                    creep.memory.cooldowns.OPERATE_LAB = Game.time + 50;
                    updateLabBoost(creep);
                    creep.memory.jobFocus = undefined;
                }
            }
        } else if (creep.memory.jobFocus == 'FILL_SPAWNS') {
            //Power only fills extentions, fill spawns.
            if (creep.carry[RESOURCE_ENERGY] <= 900) {
                let neededAmount = 2000 - creep.carry[RESOURCE_ENERGY];
                creep.memory.structureTarget = undefined;
                //Get from storage
                //Check overflow link first
                var linkTarget = undefined;
                if (creep.memory.linkSource) {
                    linkTarget = Game.getObjectById(creep.memory.linkSource)
                }
                if (linkTarget && linkTarget.energy >= 400) {
                    if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(linkTarget, {
                            ignoreRoads: true
                        });
                    }
                } else {
                    var storageTarget = creep.room.storage;
                    if (creep.room.terminal && storageTarget.store[RESOURCE_ENERGY] < 250000 && creep.room.terminal.store[RESOURCE_ENERGY] > 31000) {
                        storageTarget = creep.room.terminal;
                    }
                    if (storageTarget) {
                        let withdrawResult = creep.withdraw(storageTarget, RESOURCE_ENERGY, neededAmount)
                        if (withdrawResult == ERR_NOT_IN_RANGE) {
                            creep.travelTo(storageTarget, {
                                ignoreRoads: true
                            });
                        } else if (withdrawResult == ERR_NOT_ENOUGH_RESOURCES) {
                            creep.withdraw(storageTarget, RESOURCE_ENERGY)
                        }
                    }
                }
            } else {
                let savedTarget = Game.getObjectById(creep.memory.structureTarget);
                var getNewStructure = false;
                if (savedTarget && savedTarget.energy < savedTarget.energyCapacity) {
                    if (creep.transfer(savedTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(savedTarget);
                    } else {
                        creep.memory.jobFocus = undefined;
                        creep.memory.structureTarget = undefined;
                    }
                }
                if (!creep.memory.structureTarget) {
                    var target = undefined;
                    target = creep.pos.findClosestByPath(FIND_STRUCTURES, {
                        filter: (structure) => {
                            return (structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                        }
                    });

                    if (!target) {
                        //Find closest by path will not return anything if path is blocked
                        target = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_SPAWN) && structure.energy < structure.energyCapacity;
                            }
                        });
                    }

                    if (target) {
                        if (creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                            creep.travelTo(target);
                            creep.memory.structureTarget = target.id;
                        } else {
                            //OK
                            creep.memory.jobFocus = undefined;
                            creep.memory.structureTarget = undefined;
                        }
                    }
                }
            }
        } else {
            //Busywork - dump overflow link
            if (creep.carry[RESOURCE_ENERGY] <= 1200) {
                var linkTarget = undefined;
                creep.memory.structureTarget = undefined;
                if (creep.memory.linkSource) {
                    linkTarget = Game.getObjectById(creep.memory.linkSource)
                }
                if (linkTarget && linkTarget.energy >= 400) {
                    if (creep.withdraw(linkTarget, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(linkTarget, {
                            ignoreRoads: true
                        });
                    }
                }
            } else {
                //Saved Target
                if (creep.memory.structureTarget) {
                    var thisTarget = Game.getObjectById(creep.memory.structureTarget);
                    if (thisTarget) {
                        let tResult = creep.transfer(thisTarget, RESOURCE_ENERGY)
                        if (tResult == ERR_NOT_IN_RANGE) {
                            creep.travelTo(thisTarget);
                        } else if (tResult == OK) {
                            creep.memory.structureTarget = undefined;
                        }
                    } else {
                        creep.memory.structureTarget = undefined;
                    }
                } else {
                    //Terminal
                    let foundWork = false;
                    if (creep.room.terminal) {
                        let targetEnergy = 0;
                        if (creep.room.storage) {
                            if (creep.room.storage.store[RESOURCE_ENERGY] >= 275000) {
                                targetEnergy = 60000;
                            } else if (creep.room.storage.store[RESOURCE_ENERGY] >= 50000) {
                                targetEnergy = 30000;
                            }
                        }
                        if (creep.room.terminal.store[RESOURCE_ENERGY] < targetEnergy && (creep.room.terminal.storeCapacity - 5000) > _.sum(creep.room.terminal.store)) {
                            foundWork = true;
                            creep.memory.structureTarget = creep.room.terminal.id;
                            if (creep.transfer(creep.room.terminal, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.travelTo(creep.room.terminal);
                            }
                        }
                    }
                    //PowerSpawn/Nuker
                    if (!foundWork && creep.room.controller.level == 8) {
                        var target = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => {
                                return (structure.structureType == STRUCTURE_POWER_SPAWN ||
                                    structure.structureType == STRUCTURE_NUKER) && structure.energy < structure.energyCapacity;
                            }
                        });
                        if (target) {
                            foundWork = true;
                            creep.memory.structureTarget = target.id;
                            if (creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                                creep.travelTo(target);
                            } else {
                                creep.memory.structureTarget = undefined;
                            }
                        }
                    }

                    if (!foundWork && creep.room.storage && creep.transfer(creep.room.storage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.memory.structureTarget = creep.room.storage.id;
                        creep.travelTo(creep.room.storage);
                    }
                }

            }
        }

        let talkingCreeps = creep.pos.findInRange(FIND_MY_CREEPS, 1, {
            filter: (thisCreep) => (creep.id != thisCreep.id && thisCreep.saying && thisCreep.saying != "\u261D\uD83D\uDE3C" && thisCreep.saying != "\uD83D\uDC4C\uD83D\uDE39")
        })
        if (talkingCreeps.length) {
            let coords = talkingCreeps[0].saying.split(";");
            if (coords.length == 2 && creep.pos.x == parseInt(coords[0]) && creep.pos.y == parseInt(coords[1])) {
                //Standing in the way of a creep
                let thisDirection = creep.pos.getDirectionTo(talkingCreeps[0].pos);
                creep.move(thisDirection);
                creep.say("\uD83D\uDCA6", true);
            }
        }
    }
};

function setupCreepMemory(creep) {
    var cooldownObject = {};
    cooldownObject.GENERATE_OPS = Game.time;
    cooldownObject.OPERATE_SPAWN = Game.time;
    cooldownObject.OPERATE_TOWER = Game.time;
    cooldownObject.OPERATE_LAB = Game.time;
    cooldownObject.OPERATE_EXTENSION = Game.time;
    cooldownObject.REGEN_SOURCE = Game.time;
    creep.memory.cooldowns = cooldownObject;

    creep.memory.sources = Memory.sourceList[creep.room.name];
    creep.memory.empoweredSources = [Game.time, Game.time];

    creep.memory.spawnList = [];
    creep.memory.empoweredSpawns = [];
    var roomSpawns = creep.room.find(FIND_MY_STRUCTURES, {
        filter: {
            structureType: STRUCTURE_SPAWN
        }
    });
    for (var thisSpawn in roomSpawns) {
        creep.memory.spawnList.push(roomSpawns[thisSpawn].id);
        creep.memory.empoweredSpawns.push(Game.time);
    }

    //Can ignore first 3 labs, never set to run reactions
    creep.memory.empoweredLabs = [Game.time, Game.time, Game.time, Game.time, Game.time, Game.time, Game.time]

    if (!Game.flags[creep.room.name + "RoomOperator"]) {
        Game.rooms[creep.room.name].createFlag(47, 2, creep.room.name + "RoomOperator");
    }

    if (Memory.linkList[creep.room.name].length >= 4) {
        creep.memory.linkSource = Memory.linkList[creep.room.name][3];
    }

    creep.memory.jobFocus = undefined;

    creep.memory.initialSetup = true;
}

function findNeededWork(creep) {
    if (creep.memory.cooldowns.OPERATE_EXTENSION <= Game.time && totalOps >= 2 && creep.room.storage && creep.room.energyAvailable < creep.room.energyCapacityAvailable) {
        return 'OPERATE_EXTENSION';
    } else if (creep.memory.cooldowns.REGEN_SOURCE <= Game.time && (creep.memory.empoweredSources[0] <= Game.time || creep.memory.empoweredSources[1] <= Game.time)) {
        return 'REGEN_SOURCE';
    } else if (!Game.flags[creep.room.name + "WarBoosts"] && creep.memory.cooldowns.OPERATE_LAB <= Game.time && totalOps >= 10 && checkForLabNeed(creep)) {
        return 'OPERATE_LAB';
    } else if (creep.room.energyAvailable < creep.room.energyCapacityAvailable) {
        return 'FILL_SPAWNS';
    }
    return undefined;
}

function checkForLabNeed(creep) {
    for (var thisLab in creep.memory.empoweredLabs) {
        if (creep.memory.empoweredLabs[thisLab] <= Game.time) {
            return true;
        }
    }
    return false;
}

function getNeededLab(creep) {
    var labIndex = 3;
    for (var thisLab in creep.memory.empoweredLabs) {
        if (creep.memory.empoweredLabs[thisLab] <= Game.time) {
            var thisLab = Game.getObjectById(Memory.labList[creep.room.name][labIndex]);
            if (thisLab) {
                return thisLab;
            }
        }
        labIndex++;
    }
    return undefined;
}

function updateLabBoost(creep) {
    for (var thisLab in creep.memory.empoweredLabs) {
        if (creep.memory.empoweredLabs[thisLab] <= Game.time) {
            creep.memory.empoweredLabs[thisLab] = Game.time + 1000;
            break;
        }
    }
}

function checkForSpawnNeed(creep) {
    for (var thisSpawnCD in creep.memory.empoweredSpawns) {
        if (creep.memory.empoweredSpawns[thisSpawnCD] <= Game.time) {
            return true;
        }
    }
    return false;
}

module.exports = creep_baseOp;<|endoftext|>


<commit_before>var app = angular.module('submissionApp', ['ui.bootstrap']);
app.controller('formCtrl', function ($scope,$window,$http) {
	$scope.state = "new";
	$scope.user = "new";
	$scope.disableform = false;
	$scope.enableplus = true;
	$scope.showSponsorError = false;
	$scope.showMemberError = false;
	$scope.forms = {};
    $scope.categories= [
        {"category":"Account Management-Small/Mid","noOfMembers":3},
        {"category":"Account Management-Large","noOfMembers":5},
        {"category":"Development Center (DC) Management-Large","noOfMembers":4},
        {"category":"Development Center (DC) Management-Small","noOfMembers":6},
        {"category":"Infosys Champions-Technology Champion","noOfMembers":2},
        {"category":"Infosys Champions-Domain Champion","noOfMembers":7},
        {"category":"Innovation-IP, Products, Platforms and Solutions","noOfMembers":5},
        {"category":"Innovation-Culture","noOfMembers":4},
        {"category":"Internal Customer Delight","noOfMembers":8},
        {"category":"People Development","noOfMembers":6},
        {"category":"Complex/Business Transformation Program","noOfMembers":9},
        {"category":"Large Business Operation Program","noOfMembers":7},
        {"category":"Sales and Marketing - Brand Management","noOfMembers":2},
        {"category": "Sales and Marketing - Sales Management","noOfMembers":4},
        {"category":"Systems and Processes","noOfMembers":5},
        {"category":"Value Champions","noOfMembers":9},
        {"category":"Sustainability/Social Consciousness","noOfMembers":10}
    ];
    $scope.levels=[
        "Bangalore",
        "Bhubaneswar",
        "Chandigarh (including New Delhi, Mohali)",
        "Chennai (Mahindra City/ Sholinganallur)",
        "Hyderabad",
        "Jaipur",
        "Mangalore",
        "Mysore",
        "Pune",
        "Trivandrum",
        "Americas",
        "ANZ",
        "APAC",
        "EMEA"
    ];
    $scope.nomination = {
        "selectedCategory":"Account Management-Small/Mid",
        "selectedLevel":"Bangalore",
        "nomination":"",
        "sponsormailid":"",
        "sponsorname":"",
        "sponsornumber":"",
        "members":[],
        "filekey":'',
        "email":false,
        "uploadfile":{},
        "filename":"",
        "filetype":"",
		"filesize":""
    };

    angular.element('#typeahead').typeahead({
	  hint: true,
	  highlight: true,
	  minLength: 3
	});

    $scope.nominations = [];
    $scope.sponsors = [];
    $scope.employees = [];
    $scope.chosenemployee = {};
    $scope.initnomination={};
    $scope.initmember = {
        employeeEmailID: '',
        eNo: '',
        Name: '',
        Unit: '',
        contribution: ''
    };
    $scope.chosen;
    $scope.addmember = {};
    $scope.addrow = function () {
    	if($scope.addmember.contribution == ""){
    			alert("Please fill individual contribution");
    			return;
    	}
    	var membersallowed=0;
    	for(var i=0;i<$scope.categories.length;i++){
    		if($scope.nomination.selectedCategory == $scope.categories[i].category){
    			membersallowed=$scope.categories[i].noOfMembers;
    			break;
    		}
    	}
        var data = {};
        angular.copy($scope.addmember, data);
        angular.copy($scope.initmember, $scope.addmember);
        if($scope.nomination.members == undefined)
        	$scope.nomination.members=[];
        $scope.nomination.members.push(data);
        $scope.nomination.membertypeahead = null;
        if($scope.nomination.members.length == membersallowed){
        	$scope.enableplus = false;
        }
    };
    $scope.removerow = function (index) {
        $scope.nomination.members.splice(index, 1);
    };
    $scope.editmember = function (index) {
        $scope.chosen = index;
    };
    $scope.savemember = function (index){
        $scope.chosen = '';
    };
    $scope.removenomination = function (index) {
    	Simplity.getResponse('submission.deletenomination',JSON.stringify($scope.nominations[index]));
    	$scope.nominations.splice(index, 1);
    };
    $scope.getTemplate = function (index) {
        if (index === $scope.chosen) return 'editmembers';
        else return 'displaymembers';
    };
    $scope.fileupload = function(file){
    	$scope.nomination.uploadfile = file.files[0];
      if($scope.nomination.uploadfile.size > 5242880){
        	alert("File is too large to upload. Please limit it to 5MB only");
      }
    };
    $scope.submit=function(status){
    	$scope.showSponsorError = false;
    	$scope.showMemberError = false;
    	if(status == "Submitted"){
    			if($scope.nomination.sponsormailid == ""){
    				$scope.showSponsorError = true;
    			}
    			if($scope.nomination.members.length == 0){
    				$scope.showMemberError = true;
    			}
    	}
    	if($scope.showSponsorError == true || $scope.showMemberError == true)
    		return;
     	var data = {
				"selectedCategory":$scope.nomination.selectedCategory,
		        "selectedLevel":$scope.nomination.selectedLevel,
		        "nomination":$scope.nomination.nomination,
		        "sponsormailid":$scope.nomination.sponsormailid,
		        "sponsorname":$scope.nomination.sponsorname,
		        "sponsornumber":$scope.nomination.sponsornumber,
		        "members":$scope.nomination.members,
		        "status":status,
		        "filekey":$scope.nomination.filekey,
		        "filename":$scope.nomination.filename,
		        "filetype":$scope.nomination.filetype,
				"filesize":$scope.nomination.filesize
		 	}
		if(status == "Saved")
			data.email=false;
		else
			data.email=true;

    	if(!angular.equals($scope.nomination.uploadfile, {})){
    		var fileDetails = $scope.nomination.uploadfile;
    		Simplity.uploadFile($scope.nomination.uploadfile, function(key) {
    			data.filekey=key;
				data.filename=fileDetails.name;
				data.filetype=fileDetails.type;
				data.filesize=fileDetails.size;
				Simplity.getResponse('submission.newnomination',JSON.stringify(data));
    		});
    	}else{
			Simplity.getResponse('submission.newnomination',JSON.stringify(data));
    	}
    	$scope.nomination.uploadfile = {};
 	 };

	 $scope.init=function(){
			 angular.copy($scope.nomination,$scope.initnomination);
			 angular.copy($scope.initmember,$scope.addmember);
	 };
	 $scope.newnominationhtml=function(){
		 $scope.state="new";
		 angular.copy($scope.initnomination,$scope.nomination);
		 $scope.disableform=false;
	 };
	 $scope.viewsubmissionhtml=function(){
		 $scope.state="view";
		 Simplity.getResponse("submission.getnominations",null,function(json){
			 if(json.nominations != null){
				 $scope.nominations = json.nominations;
				 angular.copy($scope.nominations[0],$scope.nomination );
				 $scope.changeformstatus($scope.nominations[0]);
				 $scope.$apply();
			 }
		 });

	 };
	 $scope.downloadfile=function(filekey,filename,filetype){
		 Simplity.downloadFile(filekey,filename,filetype);
	 };
	 $scope.viewsponsorhtml=function(){
		 $scope.state="sponsor";
		 Simplity.getResponse("submission.getnomsponsor",null,function(json){
			 if(json.sponsors != null){
				 $scope.sponsors = json.sponsors;
				 angular.copy($scope.sponsors[0],$scope.nomination );
				 $scope.changeformstatus($scope.sponsors[0]);
				 $scope.$apply();
			 }
		 });

	 };

	 $scope.viewsubmission=function(nomination){
		 angular.copy(nomination,$scope.nomination);
		 $scope.changeformstatus(nomination);
	};

	 $scope.updatenomination=function(selectednomination,status){
		if(status == "Saved")
			selectednomination.email=false;
		else
			 selectednomination.email=true;
		selectednomination.status=status;
		console.log(selectednomination);
		if(!($scope.nomination.uploadfile == undefined || angular.equals($scope.nomination.uploadfile, {}))){
    		var fileDetails = $scope.nomination.uploadfile;
    		Simplity.uploadFile($scope.nomination.uploadfile, function(key) {
    			selectednomination.filekey=key;
    			selectednomination.filename=fileDetails.name;
    			selectednomination.filetype=fileDetails.type;
    			selectednomination.filesize=fileDetails.size;
				Simplity.getResponse('submission.updatenomination',JSON.stringify(selectednomination));
    		});
    	}else{
    		Simplity.getResponse('submission.updatenomination',JSON.stringify(selectednomination));
    	}
	 };

	 $scope.changeformstatus=function(selectednomination){
		 if(selectednomination.status == "Saved"){
			 $scope.disableform=false;
		 }
		 else{
			 $scope.disableform=true;
		 }
	 }

	 $scope.getmailsuggestion=function(mailidpart){
		 $http({
			 method:'GET',
			 url   :'http://10.68.122.228:8080/LDAPLookup/a._s?_serviceName=lookup.ldaplookup&mailidpart='+mailidpart
		 }).then(function successCallback(response) {
			 $scope.employees = response.data.employees;
		 },function errorCallback(response){
			 console.log(response);
		 });
	 }
	 $scope.populatesponsordata=function(chosen){
		 	$scope.nomination.sponsormailid = chosen.mail;
		    $scope.nomination.sponsorname   = chosen.Name;
		    $scope.nomination.sponsornumber = chosen.eNo;
	 };
	 $scope.populatememberdata=function(chosen){
		 	$scope.addmember.employeeEmailID = chosen.mail;
		    $scope.addmember.Name            = chosen.Name;
		    $scope.addmember.eNo             = chosen.eNo;
		    $scope.addmember.Unit            = chosen.Unit ;
	 };

});
<commit_msg>Universal ldaplookup updated<commit_after>var app = angular.module('submissionApp', ['ui.bootstrap']);
app.controller('formCtrl', function ($scope,$window,$http) {
	$scope.state = "new";
	$scope.user = "new";
	$scope.disableform = false;
	$scope.enableplus = true;
	$scope.showSponsorError = false;
	$scope.showMemberError = false;
	$scope.forms = {};
    $scope.categories= [
        {"category":"Account Management-Small/Mid","noOfMembers":3},
        {"category":"Account Management-Large","noOfMembers":5},
        {"category":"Development Center (DC) Management-Large","noOfMembers":4},
        {"category":"Development Center (DC) Management-Small","noOfMembers":6},
        {"category":"Infosys Champions-Technology Champion","noOfMembers":2},
        {"category":"Infosys Champions-Domain Champion","noOfMembers":7},
        {"category":"Innovation-IP, Products, Platforms and Solutions","noOfMembers":5},
        {"category":"Innovation-Culture","noOfMembers":4},
        {"category":"Internal Customer Delight","noOfMembers":8},
        {"category":"People Development","noOfMembers":6},
        {"category":"Complex/Business Transformation Program","noOfMembers":9},
        {"category":"Large Business Operation Program","noOfMembers":7},
        {"category":"Sales and Marketing - Brand Management","noOfMembers":2},
        {"category": "Sales and Marketing - Sales Management","noOfMembers":4},
        {"category":"Systems and Processes","noOfMembers":5},
        {"category":"Value Champions","noOfMembers":9},
        {"category":"Sustainability/Social Consciousness","noOfMembers":10}
    ];
    $scope.levels=[
        "Bangalore",
        "Bhubaneswar",
        "Chandigarh (including New Delhi, Mohali)",
        "Chennai (Mahindra City/ Sholinganallur)",
        "Hyderabad",
        "Jaipur",
        "Mangalore",
        "Mysore",
        "Pune",
        "Trivandrum",
        "Americas",
        "ANZ",
        "APAC",
        "EMEA"
    ];
    $scope.nomination = {
        "selectedCategory":"Account Management-Small/Mid",
        "selectedLevel":"Bangalore",
        "nomination":"",
        "sponsormailid":"",
        "sponsorname":"",
        "sponsornumber":"",
        "members":[],
        "filekey":'',
        "email":false,
        "uploadfile":{},
        "filename":"",
        "filetype":"",
		"filesize":""
    };

    angular.element('#typeahead').typeahead({
	  hint: true,
	  highlight: true,
	  minLength: 3
	});

    $scope.nominations = [];
    $scope.sponsors = [];
    $scope.employees = [];
    $scope.chosenemployee = {};
    $scope.initnomination={};
    $scope.initmember = {
        employeeEmailID: '',
        eNo: '',
        Name: '',
        Unit: '',
        contribution: ''
    };
    $scope.chosen;
    $scope.addmember = {};
    $scope.addrow = function () {
    	if($scope.addmember.contribution == ""){
    			alert("Please fill individual contribution");
    			return;
    	}
    	var membersallowed=0;
    	for(var i=0;i<$scope.categories.length;i++){
    		if($scope.nomination.selectedCategory == $scope.categories[i].category){
    			membersallowed=$scope.categories[i].noOfMembers;
    			break;
    		}
    	}
        var data = {};
        angular.copy($scope.addmember, data);
        angular.copy($scope.initmember, $scope.addmember);
        if($scope.nomination.members == undefined)
        	$scope.nomination.members=[];
        $scope.nomination.members.push(data);
        $scope.nomination.membertypeahead = null;
        if($scope.nomination.members.length == membersallowed){
        	$scope.enableplus = false;
        }
    };
    $scope.removerow = function (index) {
        $scope.nomination.members.splice(index, 1);
    };
    $scope.editmember = function (index) {
        $scope.chosen = index;
    };
    $scope.savemember = function (index){
        $scope.chosen = '';
    };
    $scope.removenomination = function (index) {
    	Simplity.getResponse('submission.deletenomination',JSON.stringify($scope.nominations[index]));
    	$scope.nominations.splice(index, 1);
    };
    $scope.getTemplate = function (index) {
        if (index === $scope.chosen) return 'editmembers';
        else return 'displaymembers';
    };
    $scope.fileupload = function(file){
    	$scope.nomination.uploadfile = file.files[0];
      if($scope.nomination.uploadfile.size > 5242880){
        	alert("File is too large to upload. Please limit it to 5MB only");
      }
    };
    $scope.submit=function(status){
    	$scope.showSponsorError = false;
    	$scope.showMemberError = false;
    	if(status == "Submitted"){
    			if($scope.nomination.sponsormailid == ""){
    				$scope.showSponsorError = true;
    			}
    			if($scope.nomination.members.length == 0){
    				$scope.showMemberError = true;
    			}
    	}
    	if($scope.showSponsorError == true || $scope.showMemberError == true)
    		return;
     	var data = {
				"selectedCategory":$scope.nomination.selectedCategory,
		        "selectedLevel":$scope.nomination.selectedLevel,
		        "nomination":$scope.nomination.nomination,
		        "sponsormailid":$scope.nomination.sponsormailid,
		        "sponsorname":$scope.nomination.sponsorname,
		        "sponsornumber":$scope.nomination.sponsornumber,
		        "members":$scope.nomination.members,
		        "status":status,
		        "filekey":$scope.nomination.filekey,
		        "filename":$scope.nomination.filename,
		        "filetype":$scope.nomination.filetype,
				"filesize":$scope.nomination.filesize
		 	}
		if(status == "Saved")
			data.email=false;
		else
			data.email=true;

    	if(!angular.equals($scope.nomination.uploadfile, {})){
    		var fileDetails = $scope.nomination.uploadfile;
    		Simplity.uploadFile($scope.nomination.uploadfile, function(key) {
    			data.filekey=key;
				data.filename=fileDetails.name;
				data.filetype=fileDetails.type;
				data.filesize=fileDetails.size;
				Simplity.getResponse('submission.newnomination',JSON.stringify(data));
    		});
    	}else{
			Simplity.getResponse('submission.newnomination',JSON.stringify(data));
    	}
    	$scope.nomination.uploadfile = {};
 	 };

	 $scope.init=function(){
			 angular.copy($scope.nomination,$scope.initnomination);
			 angular.copy($scope.initmember,$scope.addmember);
	 };
	 $scope.newnominationhtml=function(){
		 $scope.state="new";
		 angular.copy($scope.initnomination,$scope.nomination);
		 $scope.disableform=false;
	 };
	 $scope.viewsubmissionhtml=function(){
		 $scope.state="view";
		 Simplity.getResponse("submission.getnominations",null,function(json){
			 if(json.nominations != null){
				 $scope.nominations = json.nominations;
				 angular.copy($scope.nominations[0],$scope.nomination );
				 $scope.changeformstatus($scope.nominations[0]);
				 $scope.$apply();
			 }
		 });

	 };
	 $scope.downloadfile=function(filekey,filename,filetype){
		 Simplity.downloadFile(filekey,filename,filetype);
	 };
	 $scope.viewsponsorhtml=function(){
		 $scope.state="sponsor";
		 Simplity.getResponse("submission.getnomsponsor",null,function(json){
			 if(json.sponsors != null){
				 $scope.sponsors = json.sponsors;
				 angular.copy($scope.sponsors[0],$scope.nomination );
				 $scope.changeformstatus($scope.sponsors[0]);
				 $scope.$apply();
			 }
		 });

	 };

	 $scope.viewsubmission=function(nomination){
		 angular.copy(nomination,$scope.nomination);
		 $scope.changeformstatus(nomination);
	};

	 $scope.updatenomination=function(selectednomination,status){
		if(status == "Saved")
			selectednomination.email=false;
		else
			 selectednomination.email=true;
		selectednomination.status=status;
		console.log(selectednomination);
		if(!($scope.nomination.uploadfile == undefined || angular.equals($scope.nomination.uploadfile, {}))){
    		var fileDetails = $scope.nomination.uploadfile;
    		Simplity.uploadFile($scope.nomination.uploadfile, function(key) {
    			selectednomination.filekey=key;
    			selectednomination.filename=fileDetails.name;
    			selectednomination.filetype=fileDetails.type;
    			selectednomination.filesize=fileDetails.size;
				Simplity.getResponse('submission.updatenomination',JSON.stringify(selectednomination));
    		});
    	}else{
    		Simplity.getResponse('submission.updatenomination',JSON.stringify(selectednomination));
    	}
	 };

	 $scope.changeformstatus=function(selectednomination){
		 if(selectednomination.status == "Saved"){
			 $scope.disableform=false;
		 }
		 else{
			 $scope.disableform=true;
		 }
	 }

	 $scope.getmailsuggestion=function(mailidpart){
		 $http({
			 method:'GET',
			 url   :'http://sparsh-ic:8080/LDAPLookup/a._s?_serviceName=lookup.ldaplookup&mailidpart='+mailidpart
		 }).then(function successCallback(response) {
			 $scope.employees = response.data.employees;
		 },function errorCallback(response){
			 console.log(response);
		 });
	 }
	 $scope.populatesponsordata=function(chosen){
		 	$scope.nomination.sponsormailid = chosen.mail;
		    $scope.nomination.sponsorname   = chosen.Name;
		    $scope.nomination.sponsornumber = chosen.eNo;
	 };
	 $scope.populatememberdata=function(chosen){
		 	$scope.addmember.employeeEmailID = chosen.mail;
		    $scope.addmember.Name            = chosen.Name;
		    $scope.addmember.eNo             = chosen.eNo;
		    $scope.addmember.Unit            = chosen.Unit ;
	 };

});
<|endoftext|>


<commit_before>/*
 * grunt-appcache
 * http://canvace.com/
 *
 * Copyright (c) 2013 Canvace Srl
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

	var path = require('path');
	var appcache = require('./lib/appcache').init(grunt);

	function identity(input) {
		return input;
	}

	function isAbsolutePath(path) {
		return (/^https?:\/\//i).test(path);
	}

	function expand(input) {
		var list = [];
		input.forEach(function (pattern) {
			if(isAbsolutePath(pattern)) {
				list.push(pattern);
			}
			else {
				list.push.apply(list, grunt.file.expand(pattern).filter(function (filepath) {
					return grunt.file.exists(filepath) && grunt.file.isFile(filepath);
				}));
			}
		});
		return list;
	}

	function filter(input, action) {
		if (!Array.isArray(input)) {
			input = [input];
		}
		return action(input);
	}

	grunt.registerMultiTask('appcache', 'Automatically generates an HTML5 AppCache manifest from a list of files.', function () {
		var options = this.options({
			basePath: process.cwd(),
			ignoreManifest: true
		});

		options.basePath = path.normalize(options.basePath);

		var ignored = [];
		if (this.data.ignored) {
			ignored = filter(this.data.ignored, expand).map(function (filepath) {
				return path.normalize(filepath);
			});
		}

		if (options.ignoreManifest) {
			ignored.push(path.normalize(this.data.dest));
		}

		var manifest = {
			version: {
				revision: 1,
				date: new Date()
			},
			cache: filter(this.data.cache, expand).filter(function (filepath) {
				return (-1 === ignored.indexOf(path.normalize(filepath)));
			}).map(function (filepath) {
				if (isAbsolutePath(filepath)) {
					return filepath;
				}
				return path.relative(options.basePath, path.normalize(filepath));
			}),
			network: filter(this.data.network || [], identity),
			fallback: filter(this.data.fallback || [], identity)
		};

		if (grunt.file.exists(this.data.dest)) {
			var original = appcache.readManifest(this.data.dest);
			manifest.version.revision = (1 + original.version.revision);
		}

		if (!appcache.writeManifest(this.data.dest, manifest)) {
			grunt.log.error('AppCache manifest creation failed.');
			return false;
		}

		grunt.log.writeln('AppCache manifest "' + this.data.dest + '" created.');
	});

};
<commit_msg>add support for protocol-relative URLs<commit_after>/*
 * grunt-appcache
 * http://canvace.com/
 *
 * Copyright (c) 2013 Canvace Srl
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

	var path = require('path');
	var appcache = require('./lib/appcache').init(grunt);

	function identity(input) {
		return input;
	}

	function isAbsolutePath(path) {
		return (/^(?:https?:)?\/\//i).test(path);
	}

	function expand(input) {
		var list = [];
		input.forEach(function (pattern) {
			if(isAbsolutePath(pattern)) {
				list.push(pattern);
			}
			else {
				list.push.apply(list, grunt.file.expand(pattern).filter(function (filepath) {
					return grunt.file.exists(filepath) && grunt.file.isFile(filepath);
				}));
			}
		});
		return list;
	}

	function filter(input, action) {
		if (!Array.isArray(input)) {
			input = [input];
		}
		return action(input);
	}

	grunt.registerMultiTask('appcache', 'Automatically generates an HTML5 AppCache manifest from a list of files.', function () {
		var options = this.options({
			basePath: process.cwd(),
			ignoreManifest: true
		});

		options.basePath = path.normalize(options.basePath);

		var ignored = [];
		if (this.data.ignored) {
			ignored = filter(this.data.ignored, expand).map(function (filepath) {
				return path.normalize(filepath);
			});
		}

		if (options.ignoreManifest) {
			ignored.push(path.normalize(this.data.dest));
		}

		var manifest = {
			version: {
				revision: 1,
				date: new Date()
			},
			cache: filter(this.data.cache, expand).filter(function (filepath) {
				return (-1 === ignored.indexOf(path.normalize(filepath)));
			}).map(function (filepath) {
				if (isAbsolutePath(filepath)) {
					return filepath;
				}
				return path.relative(options.basePath, path.normalize(filepath));
			}),
			network: filter(this.data.network || [], identity),
			fallback: filter(this.data.fallback || [], identity)
		};

		if (grunt.file.exists(this.data.dest)) {
			var original = appcache.readManifest(this.data.dest);
			manifest.version.revision = (1 + original.version.revision);
		}

		if (!appcache.writeManifest(this.data.dest, manifest)) {
			grunt.log.error('AppCache manifest creation failed.');
			return false;
		}

		grunt.log.writeln('AppCache manifest "' + this.data.dest + '" created.');
	});

};
<|endoftext|>