<commit_before>var _ = require('underscore');
var request = require('request');
var cheerio = require('cheerio');

var models = require('../models');

var Scrape = models.Scrape;

var makerPage = function(req, res) {

    Scrape.ScrapeModel.findByOwner(req.session.account._id, function(err, docs) {

        if(err) {
            console.log(err);
            return res.status(400).json({error:'An error occurred'});
        }

        res.render('gallery', {scrapes: docs});
    });
};

function getTestResults(){
    var x = [];
    request('http://forum.miata.net/vb/forumdisplay.php?f=124', function (error, response, html) {
        if (!error && response.statusCode == 200) {
            var $ = cheerio.load(html);
            console.log('zxcvbnm');
            var tRes= $("a:contains('wheels')").each(function(){
                var t = $(this).text();
                var a = $(this).attr('href');
                var item={};
            });
        }
    });

    return [{url:'http://www.example.com/'},{url:'http://www.example.com/'}];
}

var testResults = getTestResults();

var makeScrape = function(req, res) {
    if(!req.body.url || !req.body.query) {
        return res.status(400).json({error: "Both URL and Query are required"});
    }

    var scrapeData = {
        url: req.body.url,
        query: req.body.query,
        results: testResults,
        owner: req.session.account._id
    };

    var newScrape = new Scrape.ScrapeModel(scrapeData);

    newScrape.save(function(err) {
        if(err) {
            console.log(err);
            return res.status(400).json({error:'An error occurred'});
        }

        res.json({redirect: '/gallery'});
    });

};

module.exports.makerPage = makerPage;
module.exports.make = makeScrape;<commit_msg>added request and cheerio, wrote a hard coded test query to get all of the links on a page<commit_after>var _ = require('underscore');
var request = require('request');
var cheerio = require('cheerio');

var models = require('../models');

var Scrape = models.Scrape;

var makerPage = function(req, res) {

    Scrape.ScrapeModel.findByOwner(req.session.account._id, function(err, docs) {

        if(err) {
            console.log(err);
            return res.status(400).json({error:'An error occurred'});
        }

        res.render('gallery', {scrapes: docs});
    });
};

function getTestResults(){
    var x = [];
    request('http://forum.miata.net/vb/forumdisplay.php?f=124', function (error, response, html) {
        if (!error && response.statusCode == 200) {
            var $ = cheerio.load(html);
            console.log('zxcvbnm');
            var tRes= $("a:contains('wheels')").each(function(){
                var t = $(this).text();
                var a = $(this).attr('href');
                var item={url: a};
            });
        }
    });

    return [{url:'http://www.example.com/'},{url:'http://www.example.com/'}];
}

var testResults = getTestResults();

var makeScrape = function(req, res) {
    if(!req.body.url || !req.body.query) {
        return res.status(400).json({error: "Both URL and Query are required"});
    }

    var scrapeData = {
        url: req.body.url,
        query: req.body.query,
        results: testResults,
        owner: req.session.account._id
    };

    var newScrape = new Scrape.ScrapeModel(scrapeData);

    newScrape.save(function(err) {
        if(err) {
            console.log(err);
            return res.status(400).json({error:'An error occurred'});
        }

        res.json({redirect: '/gallery'});
    });

};

module.exports.makerPage = makerPage;
module.exports.make = makeScrape;<|endoftext|>


<commit_before>'use strict'

function HomeWorld() {
    this.__init__()
}

const GLOBAL_TODOS_POSITION_X = 0
const GLOBAL_TODOS_POSITION_Z = -1000
const GLOBAL_TODOS_POSITION_Y_TOP = 800

HomeWorld.prototype = {
    hello_message: null,

    //
    day_entities: null,
    y_offsets: null,

    //
    radius: null,
    number_of_segments: null,
    angle_delta: null,

    //
    days: null,

    //
    button_3d: null,

    // TODO : Add a daily todos section.
    // TODO : Add a global todos section.

    // Global todos.
    global_tasks_title: null,
    create_global_task_button: null,

    create_global_task_button_clicked: function() {
        this.entity_editor.set_to_visible()
    },

    create_task_clicked: function(data) {
        console.log('SAVE THE ENTITY DATA!!!')
        console.log(data)

        this.global_todos_wall.add_single_text_row(JSON.stringify(data))

        this.entity_editor.set_to_invisible()
    },

    __init__: function() {

        World.call(this)

        // Going to try to create a plane here.
        var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 10, 10)
        plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
        //var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
        var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: true})
        var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
        this.add_to_scene(plane_mesh)

        var light3 = new THREE.PointLight(0xccffcc, .8, 0)
        light3.position.set(5, 100, 5)
        this.add_to_scene(light3)

        var color1 = '#b9ffd2'
        var color2 = '#090920'
        var light2 = new THREE.HemisphereLight(color1, color2, .5)
        this.add_to_scene(light2)

        var light = new THREE.AmbientLight(0x404040, .2) // soft white light
        this.add_to_scene(light)

        /* __        __   __               ___  __   __   __   __
          / _` |    /  \ |__)  /\  |        |  /  \ |  \ /  \ /__`    |  |  /\  |    |
          \__> |___ \__/ |__) /~~\ |___     |  \__/ |__/ \__/ .__/    |/\| /~~\ |___ |___ */

        /*
        this.global_tasks_title = new Floating3DText(256, 'Global Tasks', TYPE_TITLE, this.scene)
        this.global_tasks_title.update_position_and_look_at(new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP, GLOBAL_TODOS_POSITION_Z - 5), new THREE.Vector3(0, GLOBAL_TODOS_POSITION_Y_TOP, 0))

        this.create_global_task_button = new Floating2DText(64, 'Create Entity', TYPE_BUTTON, this.scene)
        this.create_global_task_button.update_position_and_look_at(new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP - 32, GLOBAL_TODOS_POSITION_Z), new THREE.Vector3(0, GLOBAL_TODOS_POSITION_Y_TOP - 32, 0))
        */

        //this.create_global_task_button.set_engage_function(this.create_global_task_button_clicked.bind(this))

        this.global_todos_wall = new InteractiveWall(256, 800, new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP / 2, GLOBAL_TODOS_POSITION_Z), new THREE.Vector3(0, 400, 0), this.scene)
        this.global_todos_wall.add_title('Global Tasks')
        this.global_todos_wall.add_input_button('Create Task', this.create_global_task_button_clicked.bind(this))

        this.entity_editor = new EntityEditor('Create Task', new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP - 32, GLOBAL_TODOS_POSITION_Z + 26), new THREE.Vector3(0, GLOBAL_TODOS_POSITION_Y_TOP - 32, 0), this.scene)
        this.entity_editor.set_to_invisible()
        this.entity_editor.set_create_entity_buttion_click(this.create_task_clicked.bind(this))
        //this.entity_editor.create_entity = this.create_task_clicked.bind(this)
        /*
        var wall_position = new THREE.Vector3(1000, 400, 1000)
        var wall_look_at  = new THREE.Vector3(0, 400, 0)
        this.daily_tasks_wall = new InteractiveWall(400, 800, wall_position, wall_look_at, this.scene)

        var wall_position2 = new THREE.Vector3(-1000, 400, -1000)
        var wall_look_at2  = new THREE.Vector3(0, 400, 0)
        this.daily_tasks_wall2 = new InteractiveWall(400, 800, wall_position2, wall_look_at2, this.scene)
        */

        /* __             ___       __        __           __   ___
          /  `  /\  |    |__  |\ | |  \  /\  |__)     /\  |__) |__   /\
          \__, /~~\ |___ |___ | \| |__/ /~~\ |  \    /~~\ |  \ |___ /~~\ */

        this.button_3d = new Button3D(50, 'Hello Button', this.scene)
        this.button_3d.update_position_and_look_at(new THREE.Vector3(50, 50, 50), new THREE.Vector3(50, 150, 50))

        this.ajax_status = new Floating2DText(400, '', TYPE_TITLE, this.scene)
        this.ajax_status.update_position_and_look_at(new THREE.Vector3(150, 100, 45), new THREE.Vector3(150, 100, 55))

        this.day_indexes = []
        this.y_offsets = []
        this.day_entities = []

        this.days = get_list_of_dates_consisting_of_this_and_next_week()
        this.number_of_segments = this.days.length
        for (var d = 0; d < this.days.length; d++) {
            this.y_offsets.push(40)
            this.day_entities.push([])
            this.day_indexes.push(this.days[d])
        }

        this.angle_delta = (Math.PI * 2.0) / this.number_of_segments
        this.radius = 600

        var week = 0

        for (var i = 0; i < this.number_of_segments; i++) {
            var day_string = ''
            var x_position = Math.cos(this.angle_delta * i) * this.radius
            var z_position = Math.sin(this.angle_delta * i) * this.radius
            var day_value = this.day_indexes[i].split('/')[1]
            switch(i % 7) {
            case 0:
                day_string = 'Monday ' + day_value
                if (week == 0) {
                    var week_title = new Floating3DText(256, 'Current Week', TYPE_TITLE, this.scene)
                    week_title.update_position_and_look_at(new THREE.Vector3(x_position, 90 + 300, z_position), new THREE.Vector3(0, 90 + 300, 0))
                    week += 1
                    this.day_entities[i].push(week_title)
                } else if (week == 1) {
                    var week_title = new Floating3DText(256, 'Next Week', TYPE_TITLE, this.scene)
                    week_title.update_position_and_look_at(new THREE.Vector3(x_position, 90 + 300, z_position), new THREE.Vector3(0, 90 + 300, 0))
                    this.day_entities[i].push(week_title)
                }
                break
            case 1:
                day_string = 'Tuesday ' + day_value
                break
            case 2:
                day_string = 'Wednesday ' + day_value
                break
            case 3:
                day_string = 'Thursday ' + day_value
                break
            case 4:
                day_string = 'Friday ' + day_value
                break
            case 5:
                day_string = 'Saturday ' + day_value
                break
            case 6:
                day_string = 'Sunday ' + day_value
                break
            }

            var day_floating_text = new Floating2DText(150, day_string, TYPE_TITLE, this.scene)
            day_floating_text.update_position_and_look_at(new THREE.Vector3(x_position, 50 + 300, z_position), new THREE.Vector3(0, 50 + 300, 0))
            this.day_entities[i].push(day_floating_text)
            this.y_offsets[i] += 40
        }

        this.interactive_objects = [
        ]
        var wall_objects = this.entity_editor.interactive_wall.get_all_interactive_objects()
        var wall_objects_length = wall_objects.length
        for (var x = 0; x < wall_objects_length; x++) {
            this.interactive_objects.push(wall_objects[x])
        }
        wall_objects = this.global_todos_wall.get_all_interactive_objects()
        wall_objects_length = wall_objects.length
        for (x = 0; x < wall_objects_length; x++) {
            this.interactive_objects.push(wall_objects[x])
        }
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event)
    },

    add_entity: function(entity_string, day_index) {
        for (var t = 0; t < this.days.length; t++) {
            if (day_index === this.days[t]) {
                var x_position = Math.cos(this.angle_delta * t) * this.radius
                var z_position = Math.sin(this.angle_delta * t) * this.radius

                var floating_entity = new Floating2DText(256, entity_string, TYPE_STATUS, this.scene)
                floating_entity.update_position_and_look_at(new THREE.Vector3(x_position, 50 + 300 - this.y_offsets[t], z_position), new THREE.Vector3(0, 50 + 300 - this.y_offsets[t], 0))

                this.day_entities[t].push(floating_entity)
                this.y_offsets[t] += 40
            }
        }
    },

    update: function() {
        this.update_interactive_objects()
    },

    enter_world: function() {
        this.current_world = true
        if (this.hello_message === null) {
            this.ajax_status.update_text('Welcome back ' + this.player.get_username())
        }
        this.player.set_position(new THREE.Vector3(130, 90, 300))
    },

    exit_world: function() {
        this.current_world = false
    }
}

<commit_msg>design cleanup 34<commit_after>'use strict'

function HomeWorld() {
    this.__init__()
}

const GLOBAL_TODOS_POSITION_X = 0
const GLOBAL_TODOS_POSITION_Z = -1000
const GLOBAL_TODOS_POSITION_Y_TOP = 800

HomeWorld.prototype = {
    hello_message: null,

    //
    day_entities: null,
    y_offsets: null,

    //
    radius: null,
    number_of_segments: null,
    angle_delta: null,

    //
    days: null,

    //
    button_3d: null,

    // TODO : Add a daily todos section.
    // TODO : Add a global todos section.

    // Global todos.
    global_tasks_title: null,
    create_global_task_button: null,

    create_global_task_button_clicked: function() {
        this.entity_editor.set_to_visible()
    },

    create_task_clicked: function(data) {
        console.log('SAVE THE ENTITY DATA!!!')
        console.log(data)

        this.global_todos_wall.add_single_text_row(JSON.stringify(data))

        this.entity_editor.set_to_invisible()
    },

    __init__: function() {

        World.call(this)

        // Going to try to create a plane here.
        var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 10, 10)
        plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
        //var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
        var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: true})
        var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
        this.add_to_scene(plane_mesh)

        var light3 = new THREE.PointLight(0xccffcc, .8, 0)
        light3.position.set(5, 100, 5)
        this.add_to_scene(light3)

        var color1 = '#b9ffd2'
        var color2 = '#090920'
        var light2 = new THREE.HemisphereLight(color1, color2, .5)
        this.add_to_scene(light2)

        var light = new THREE.AmbientLight(0x404040, .2) // soft white light
        this.add_to_scene(light)

        /* __        __   __               ___  __   __   __   __
          / _` |    /  \ |__)  /\  |        |  /  \ |  \ /  \ /__`    |  |  /\  |    |
          \__> |___ \__/ |__) /~~\ |___     |  \__/ |__/ \__/ .__/    |/\| /~~\ |___ |___ */

        /*
        this.global_tasks_title = new Floating3DText(256, 'Global Tasks', TYPE_TITLE, this.scene)
        this.global_tasks_title.update_position_and_look_at(new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP, GLOBAL_TODOS_POSITION_Z - 5), new THREE.Vector3(0, GLOBAL_TODOS_POSITION_Y_TOP, 0))

        this.create_global_task_button = new Floating2DText(64, 'Create Entity', TYPE_BUTTON, this.scene)
        this.create_global_task_button.update_position_and_look_at(new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP - 32, GLOBAL_TODOS_POSITION_Z), new THREE.Vector3(0, GLOBAL_TODOS_POSITION_Y_TOP - 32, 0))
        */

        //this.create_global_task_button.set_engage_function(this.create_global_task_button_clicked.bind(this))

        this.global_todos_wall = new InteractiveWall(256 * 2, 800, new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP / 2, GLOBAL_TODOS_POSITION_Z), new THREE.Vector3(0, 400, 0), this.scene)
        this.global_todos_wall.add_title('Global Tasks')
        this.global_todos_wall.add_input_button('Create Task', this.create_global_task_button_clicked.bind(this))

        this.entity_editor = new EntityEditor('Create Task', new THREE.Vector3(GLOBAL_TODOS_POSITION_X, GLOBAL_TODOS_POSITION_Y_TOP - 32, GLOBAL_TODOS_POSITION_Z + 26), new THREE.Vector3(0, GLOBAL_TODOS_POSITION_Y_TOP - 32, 0), this.scene)
        this.entity_editor.set_to_invisible()
        this.entity_editor.set_create_entity_buttion_click(this.create_task_clicked.bind(this))
        //this.entity_editor.create_entity = this.create_task_clicked.bind(this)
        /*
        var wall_position = new THREE.Vector3(1000, 400, 1000)
        var wall_look_at  = new THREE.Vector3(0, 400, 0)
        this.daily_tasks_wall = new InteractiveWall(400, 800, wall_position, wall_look_at, this.scene)

        var wall_position2 = new THREE.Vector3(-1000, 400, -1000)
        var wall_look_at2  = new THREE.Vector3(0, 400, 0)
        this.daily_tasks_wall2 = new InteractiveWall(400, 800, wall_position2, wall_look_at2, this.scene)
        */

        /* __             ___       __        __           __   ___
          /  `  /\  |    |__  |\ | |  \  /\  |__)     /\  |__) |__   /\
          \__, /~~\ |___ |___ | \| |__/ /~~\ |  \    /~~\ |  \ |___ /~~\ */

        this.button_3d = new Button3D(50, 'Hello Button', this.scene)
        this.button_3d.update_position_and_look_at(new THREE.Vector3(50, 50, 50), new THREE.Vector3(50, 150, 50))

        this.ajax_status = new Floating2DText(400, '', TYPE_TITLE, this.scene)
        this.ajax_status.update_position_and_look_at(new THREE.Vector3(150, 100, 45), new THREE.Vector3(150, 100, 55))

        this.day_indexes = []
        this.y_offsets = []
        this.day_entities = []

        this.days = get_list_of_dates_consisting_of_this_and_next_week()
        this.number_of_segments = this.days.length
        for (var d = 0; d < this.days.length; d++) {
            this.y_offsets.push(40)
            this.day_entities.push([])
            this.day_indexes.push(this.days[d])
        }

        this.angle_delta = (Math.PI * 2.0) / this.number_of_segments
        this.radius = 600

        var week = 0

        for (var i = 0; i < this.number_of_segments; i++) {
            var day_string = ''
            var x_position = Math.cos(this.angle_delta * i) * this.radius
            var z_position = Math.sin(this.angle_delta * i) * this.radius
            var day_value = this.day_indexes[i].split('/')[1]
            switch(i % 7) {
            case 0:
                day_string = 'Monday ' + day_value
                if (week == 0) {
                    var week_title = new Floating3DText(256, 'Current Week', TYPE_TITLE, this.scene)
                    week_title.update_position_and_look_at(new THREE.Vector3(x_position, 90 + 300, z_position), new THREE.Vector3(0, 90 + 300, 0))
                    week += 1
                    this.day_entities[i].push(week_title)
                } else if (week == 1) {
                    var week_title = new Floating3DText(256, 'Next Week', TYPE_TITLE, this.scene)
                    week_title.update_position_and_look_at(new THREE.Vector3(x_position, 90 + 300, z_position), new THREE.Vector3(0, 90 + 300, 0))
                    this.day_entities[i].push(week_title)
                }
                break
            case 1:
                day_string = 'Tuesday ' + day_value
                break
            case 2:
                day_string = 'Wednesday ' + day_value
                break
            case 3:
                day_string = 'Thursday ' + day_value
                break
            case 4:
                day_string = 'Friday ' + day_value
                break
            case 5:
                day_string = 'Saturday ' + day_value
                break
            case 6:
                day_string = 'Sunday ' + day_value
                break
            }

            var day_floating_text = new Floating2DText(150, day_string, TYPE_TITLE, this.scene)
            day_floating_text.update_position_and_look_at(new THREE.Vector3(x_position, 50 + 300, z_position), new THREE.Vector3(0, 50 + 300, 0))
            this.day_entities[i].push(day_floating_text)
            this.y_offsets[i] += 40
        }

        this.interactive_objects = [
        ]
        var wall_objects = this.entity_editor.interactive_wall.get_all_interactive_objects()
        var wall_objects_length = wall_objects.length
        for (var x = 0; x < wall_objects_length; x++) {
            this.interactive_objects.push(wall_objects[x])
        }
        wall_objects = this.global_todos_wall.get_all_interactive_objects()
        wall_objects_length = wall_objects.length
        for (x = 0; x < wall_objects_length; x++) {
            this.interactive_objects.push(wall_objects[x])
        }
    },

    key_down_event: function(event) {
        this.key_down_event_for_interactive_objects(event)
    },

    add_entity: function(entity_string, day_index) {
        for (var t = 0; t < this.days.length; t++) {
            if (day_index === this.days[t]) {
                var x_position = Math.cos(this.angle_delta * t) * this.radius
                var z_position = Math.sin(this.angle_delta * t) * this.radius

                var floating_entity = new Floating2DText(256, entity_string, TYPE_STATUS, this.scene)
                floating_entity.update_position_and_look_at(new THREE.Vector3(x_position, 50 + 300 - this.y_offsets[t], z_position), new THREE.Vector3(0, 50 + 300 - this.y_offsets[t], 0))

                this.day_entities[t].push(floating_entity)
                this.y_offsets[t] += 40
            }
        }
    },

    update: function() {
        this.update_interactive_objects()
    },

    enter_world: function() {
        this.current_world = true
        if (this.hello_message === null) {
            this.ajax_status.update_text('Welcome back ' + this.player.get_username())
        }
        this.player.set_position(new THREE.Vector3(130, 90, 300))
    },

    exit_world: function() {
        this.current_world = false
    }
}

<|endoftext|>


<commit_before>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Constant declarations for common key codes.
 *
 */

goog.provide('goog.events.KeyNames');

/**
 * Key names for common characters.
 *
 * This list is not localized and therefore some of the key codes are not
 * correct for non-US keyboard layouts.
 *
 * @see goog.events.KeyCodes
 * @enum {string}
 */
goog.events.KeyNames = {
  8: 'backspace',
  9: 'tab',
  13: 'enter',
  16: 'shift',
  17: 'ctrl',
  18: 'alt',
  19: 'pause',
  20: 'caps-lock',
  27: 'esc',
  32: 'space',
  33: 'pg-up',
  34: 'pg-down',
  35: 'end',
  36: 'home',
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  45: 'insert',
  46: 'delete',
  48: '0',
  49: '1',
  50: '2',
  51: '3',
  52: '4',
  53: '5',
  54: '6',
  55: '7',
  56: '8',
  57: '9',
  61: 'equals',
  65: 'a',
  66: 'b',
  67: 'c',
  68: 'd',
  69: 'e',
  70: 'f',
  71: 'g',
  72: 'h',
  73: 'i',
  74: 'j',
  75: 'k',
  76: 'l',
  77: 'm',
  78: 'n',
  79: 'o',
  80: 'p',
  81: 'q',
  82: 'r',
  83: 's',
  84: 't',
  85: 'u',
  86: 'v',
  87: 'w',
  88: 'x',
  89: 'y',
  90: 'z',
  93: 'context',
  96: 'num-0',
  97: 'num-1',
  98: 'num-2',
  99: 'num-3',
  100: 'num-4',
  101: 'num-5',
  102: 'num-6',
  103: 'num-7',
  104: 'num-8',
  105: 'num-9',
  106: 'num-multiply',
  107: 'num-plus',
  109: 'num-minus',
  110: 'num-period',
  111: 'num-division',
  112: 'f1',
  113: 'f2',
  114: 'f3',
  115: 'f4',
  116: 'f5',
  117: 'f6',
  118: 'f7',
  119: 'f8',
  120: 'f9',
  121: 'f10',
  122: 'f11',
  123: 'f12',
  187: 'equals',
  188: ',',
  190: '.',
  191: '/',
  192: '~',
  220: '\\',
  224: 'win'
};
<commit_msg><commit_after>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Constant declarations for common key codes.
 *
 */

goog.provide('goog.events.KeyNames');

/**
 * Key names for common characters.
 *
 * This list is not localized and therefore some of the key codes are not
 * correct for non-US keyboard layouts.
 *
 * @see goog.events.KeyCodes
 * @enum {string}
 */
goog.events.KeyNames = {
  8: 'backspace',
  9: 'tab',
  13: 'enter',
  16: 'shift',
  17: 'ctrl',
  18: 'alt',
  19: 'pause',
  20: 'caps-lock',
  27: 'esc',
  32: 'space',
  33: 'pg-up',
  34: 'pg-down',
  35: 'end',
  36: 'home',
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  45: 'insert',
  46: 'delete',
  48: '0',
  49: '1',
  50: '2',
  51: '3',
  52: '4',
  53: '5',
  54: '6',
  55: '7',
  56: '8',
  57: '9',
  59: 'semicolon',
  61: 'equals',
  65: 'a',
  66: 'b',
  67: 'c',
  68: 'd',
  69: 'e',
  70: 'f',
  71: 'g',
  72: 'h',
  73: 'i',
  74: 'j',
  75: 'k',
  76: 'l',
  77: 'm',
  78: 'n',
  79: 'o',
  80: 'p',
  81: 'q',
  82: 'r',
  83: 's',
  84: 't',
  85: 'u',
  86: 'v',
  87: 'w',
  88: 'x',
  89: 'y',
  90: 'z',
  93: 'context',
  96: 'num-0',
  97: 'num-1',
  98: 'num-2',
  99: 'num-3',
  100: 'num-4',
  101: 'num-5',
  102: 'num-6',
  103: 'num-7',
  104: 'num-8',
  105: 'num-9',
  106: 'num-multiply',
  107: 'num-plus',
  109: 'num-minus',
  110: 'num-period',
  111: 'num-division',
  112: 'f1',
  113: 'f2',
  114: 'f3',
  115: 'f4',
  116: 'f5',
  117: 'f6',
  118: 'f7',
  119: 'f8',
  120: 'f9',
  121: 'f10',
  122: 'f11',
  123: 'f12',
  186: 'semicolon',
  187: 'equals',
  188: ',',
  190: '.',
  191: '/',
  192: '~',
  219: 'open-square-bracket',
  220: '\\',
  224: 'win'
};
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2014 University Of Southern California
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Created by dcbriggs on 7/14/14.
 */
define(["moment"],
function(moment) {
    "use strict"
    var runsController = function($scope, $window, $http, $state) {

        // Adjust this to change the number of pages you have to request from the server
        var resultsPerPage = 100;

        $scope.alerts = [];
        $scope.getAlertIcon = function(status) {
            return (status == 'success') ? "text-success fa fa-check-circle" : "text-danger fa fa-exclamation-triangle";
        };

        $scope.closeAlert = function(index) {
            $scope.alerts.splice(index, 1);
        };

        function getRuns() {
            $http.get($window.apiLinks.runs, {
                params : {
                    results_per_page : resultsPerPage
                }
            }).success(function(data) {
                $scope.runs = data.objects;
                // Get all the results after the first page
                for(var currentPage = 2; currentPage <= data.total_pages; currentPage++) {
                    $http.get($window.apiLinks.runs, {
                        params : {
                            results_per_page : resultsPerPage,
                            page : currentPage
                        }
                    }).success(function(data) {
                        $scope.runs = $scope.runs.concat(data.objects);
                    }).error(function(data) {
                        $scope.alerts.push({
                            "type" : "danger",
                            "message" : "Unable to get runs, please contact the Pegasus team if this issue persists"
                        });
                    })
                }
            }).error(function(data) {
                console.error(data);
            });
        }
        getRuns();

        $scope.refresh = getRuns;

        // We have to define this with the CSS hardcoded in here because the system does not seem
        // to like inlining the -'s that bootstrap classes use
        $scope.getbgColor = function(exitCode) {
            return (exitCode == 0) ? "bg-success" : (exitCode == -1)  ? "bg-info" : "bg-danger";
        };

        $scope.getExitCodeIcon = function(status) {
            switch (status) {
                case -1:
                    return "text-primary fa fa-check-circle";
                case 0:
                    return "text-success fa fa-check-circle";
                case 256:
                    return "text-warning fa fa-warning";
                default:
                    return "text-danger fa fa-exclamation-triangle";
            }
        };

        $scope.createRun = function() {
            $state.go('createRun');
        };

        $scope.deleteSelected = function() {
            var selected = $scope.runsGrid.selectedItems;
            var deleteTotal = $scope.runsGrid.selectedItems.length;
            var deleteCount = 0;
            for(var i = 0; i < deleteTotal; i++) {
                $http.delete($window.apiLinks.runs + "/" + selected[i].id)
                    .success(function () {
                        // No specifications aside from the then clause
                    }).error(function () {
                        // TODO: display an error popup
                        deleteCount++;

                    })
                    .then(function() {
                        deleteCount++;
                        if(deleteCount == deleteTotal) {
                            getRuns();
                        }
                    })
            }
        };

        $scope.getFormattedDate = function(dateString) {
            var createdOn = moment.utc(dateString).local();
            var s = createdOn.format('ddd MMM DD, YYYY hh:mm:ss A');
            s += ' (' + createdOn.fromNow() + ')';
            return s;
        };

        $scope.runsGrid = {
            data : "runs",
            enablePaging : true,
            showGroupPanel : true,
            showSelectionCheckbox : true,
            selectWithCheckboxOnly : true,
            showFilter : true,
            columnDefs : [
                {field : "name", displayName : "Name", cellTemplate : "
{{row.getProperty(col.field)}}
" },
                {field : "status", displayName : "Status", width : 60, cellTemplate : "" },
                {field : "filename", displayName : "File", cellTemplate : " {{row.getProperty(col.field)}}" },
                {field : "created", displayName : "Created On", cellTemplate : "
{{getFormattedDate(row.getProperty(col.field))}}
" }
            ],
            sortInfo : {fields : ['created'], directions : ['desc']},
            selectedItems : []
        };

        $scope.getDownloadLink = function(id, filename) {
            return $window.apiLinks.download + "/" + id + "/input/" + filename;
        };

    };

    function getFullConstructor() {
        return ["$scope", "$window", "$http", "$state", runsController];
    }

    // For testing so we can mock the injected variables
    function getMinimalConstructor() {
        return runsController;
    }

    return {
        getFullConstructor : getFullConstructor,
        getMinimalConstructor : getMinimalConstructor
    };

});
<commit_msg>If delete button is pressed again after deleting an item, it attempts to delete same item again. Solution: After deleting selected runs, clear out the selectedItems array.<commit_after>/*
 * Copyright 2007-2014 University Of Southern California
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * Created by dcbriggs on 7/14/14.
 */
define(["moment"],
function(moment) {
    "use strict"
    var runsController = function($scope, $window, $http, $state) {

        // Adjust this to change the number of pages you have to request from the server
        var resultsPerPage = 100;

        $scope.alerts = [];
        $scope.getAlertIcon = function(status) {
            return (status == 'success') ? "text-success fa fa-check-circle" : "text-danger fa fa-exclamation-triangle";
        };

        $scope.closeAlert = function(index) {
            $scope.alerts.splice(index, 1);
        };

        function getRuns() {
            $http.get($window.apiLinks.runs, {
                params : {
                    results_per_page : resultsPerPage
                }
            }).success(function(data) {
                $scope.runs = data.objects;
                // Get all the results after the first page
                for(var currentPage = 2; currentPage <= data.total_pages; currentPage++) {
                    $http.get($window.apiLinks.runs, {
                        params : {
                            results_per_page : resultsPerPage,
                            page : currentPage
                        }
                    }).success(function(data) {
                        $scope.runs = $scope.runs.concat(data.objects);
                    }).error(function(data) {
                        $scope.alerts.push({
                            "type" : "danger",
                            "message" : "Unable to get runs, please contact the Pegasus team if this issue persists"
                        });
                    })
                }
            }).error(function(data) {
                console.error(data);
            });
        }
        getRuns();

        $scope.refresh = getRuns;

        // We have to define this with the CSS hardcoded in here because the system does not seem
        // to like inlining the -'s that bootstrap classes use
        $scope.getbgColor = function(exitCode) {
            return (exitCode == 0) ? "bg-success" : (exitCode == -1)  ? "bg-info" : "bg-danger";
        };

        $scope.getExitCodeIcon = function(status) {
            switch (status) {
                case -1:
                    return "text-primary fa fa-check-circle";
                case 0:
                    return "text-success fa fa-check-circle";
                case 256:
                    return "text-warning fa fa-warning";
                default:
                    return "text-danger fa fa-exclamation-triangle";
            }
        };

        $scope.createRun = function() {
            $state.go('createRun');
        };

        $scope.deleteSelected = function() {
            var selected = $scope.runsGrid.selectedItems;
            var deleteTotal = $scope.runsGrid.selectedItems.length;
            var deleteCount = 0;
            for(var i = 0; i < deleteTotal; i++) {
                $http.delete($window.apiLinks.runs + "/" + selected[i].id)
                    .success(function () {
                        // No specifications aside from the then clause
                    }).error(function () {
                        // TODO: display an error popup
                        deleteCount++;

                    })
                    .then(function() {
                        deleteCount++;
                        if(deleteCount == deleteTotal) {
                            $scope.runsGrid.selectedItems.length = 0;
                            getRuns();
                        }
                    })
            }
        };

        $scope.getFormattedDate = function(dateString) {
            var createdOn = moment.utc(dateString).local();
            var s = createdOn.format('ddd MMM DD, YYYY hh:mm:ss A');
            s += ' (' + createdOn.fromNow() + ')';
            return s;
        };

        $scope.runsGrid = {
            data : "runs",
            enablePaging : true,
            showGroupPanel : true,
            showSelectionCheckbox : true,
            selectWithCheckboxOnly : true,
            showFilter : true,
            columnDefs : [
                {field : "name", displayName : "Name", cellTemplate : "
{{row.getProperty(col.field)}}
" },
                {field : "status", displayName : "Status", width : 60, cellTemplate : "" },
                {field : "filename", displayName : "File", cellTemplate : " {{row.getProperty(col.field)}}" },
                {field : "created", displayName : "Created On", cellTemplate : "
{{getFormattedDate(row.getProperty(col.field))}}
" }
            ],
            sortInfo : {fields : ['created'], directions : ['desc']},
            selectedItems : []
        };

        $scope.getDownloadLink = function(id, filename) {
            return $window.apiLinks.download + "/" + id + "/input/" + filename;
        };

    };

    function getFullConstructor() {
        return ["$scope", "$window", "$http", "$state", runsController];
    }

    // For testing so we can mock the injected variables
    function getMinimalConstructor() {
        return runsController;
    }

    return {
        getFullConstructor : getFullConstructor,
        getMinimalConstructor : getMinimalConstructor
    };

});
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _ComposedComponent = require('./ComposedComponent');

var _ComposedComponent2 = _interopRequireDefault(_ComposedComponent);

var _MenuItem = require('material-ui/MenuItem');

var _MenuItem2 = _interopRequireDefault(_MenuItem);

var _SelectField = require('material-ui/SelectField');

var _SelectField2 = _interopRequireDefault(_SelectField);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
                                                                                * Created by steve on 15/09/15.
                                                                                */

var Select = function (_React$Component) {
    _inherits(Select, _React$Component);

    function Select(props) {
        _classCallCheck(this, Select);

        var _this = _possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props));

        _this.onSelected = _this.onSelected.bind(_this);
        _this.state = {
            currentValue: _this.props.model[_this.props.form.key] || (_this.props.form.titleMap != null ? _this.props.form.titleMap[0].value : '')
        };
        return _this;
    }

    _createClass(Select, [{
        key: 'onSelected',
        value: function onSelected(event, selectedIndex, menuItem) {

            this.setState({
                currentValue: menuItem
            });
            event.target.value = menuItem;
            this.props.onChangeValidate(event);
        }
    }, {
        key: 'render',
        value: function render() {
            var menuItems = this.props.form.titleMap.map(function (item, idx) {
                return _react2.default.createElement(_MenuItem2.default, { key: idx,
                    primaryText: item.name,
                    value: item.value });
            });

            return _react2.default.createElement(
                'div',
                { className: this.props.form.htmlClass },
                _react2.default.createElement(
                    _SelectField2.default,
                    {
                        value: this.state.currentValue,
                        floatingLabelText: this.props.form.title,
                        disabled: this.props.form.readonly,
                        onChange: this.onSelected,
                        fullWidth: true },
                    menuItems
                )
            );
        }
    }]);

    return Select;
}(_react2.default.Component);

// Select.propTypes = {
//
// };

var _default = (0, _ComposedComponent2.default)(Select);

exports.default = _default;
;

var _temp = function () {
    if (typeof __REACT_HOT_LOADER__ === 'undefined') {
        return;
    }

    __REACT_HOT_LOADER__.register(Select, 'Select', 'src/Select.js');

    __REACT_HOT_LOADER__.register(_default, 'default', 'src/Select.js');
}();

;<commit_msg>Fix issue with enum not being able to display because of an undefined _this.props.model: https://github.com/networknt/react-schema-form/issues/42<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _ComposedComponent = require('./ComposedComponent');

var _ComposedComponent2 = _interopRequireDefault(_ComposedComponent);

var _MenuItem = require('material-ui/MenuItem');

var _MenuItem2 = _interopRequireDefault(_MenuItem);

var _SelectField = require('material-ui/SelectField');

var _SelectField2 = _interopRequireDefault(_SelectField);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
                                                                                * Created by steve on 15/09/15.
                                                                                */

var Select = function (_React$Component) {
    _inherits(Select, _React$Component);

    function Select(props) {
        _classCallCheck(this, Select);

        var _this = _possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props));

        _this.onSelected = _this.onSelected.bind(_this);
        _this.state = {
            currentValue: _this.props.model !== undefined ? _this.props.model[_this.props.form.key] : (_this.props.form.titleMap != null ? _this.props.form.titleMap[0].value : '')
        };
        return _this;
    }

    _createClass(Select, [{
        key: 'onSelected',
        value: function onSelected(event, selectedIndex, menuItem) {

            this.setState({
                currentValue: menuItem
            });
            event.target.value = menuItem;
            this.props.onChangeValidate(event);
        }
    }, {
        key: 'render',
        value: function render() {
            var menuItems = this.props.form.titleMap.map(function (item, idx) {
                return _react2.default.createElement(_MenuItem2.default, { key: idx,
                    primaryText: item.name,
                    value: item.value });
            });

            return _react2.default.createElement(
                'div',
                { className: this.props.form.htmlClass },
                _react2.default.createElement(
                    _SelectField2.default,
                    {
                        value: this.state.currentValue,
                        floatingLabelText: this.props.form.title,
                        disabled: this.props.form.readonly,
                        onChange: this.onSelected,
                        fullWidth: true },
                    menuItems
                )
            );
        }
    }]);

    return Select;
}(_react2.default.Component);

// Select.propTypes = {
//
// };

var _default = (0, _ComposedComponent2.default)(Select);

exports.default = _default;
;

var _temp = function () {
    if (typeof __REACT_HOT_LOADER__ === 'undefined') {
        return;
    }

    __REACT_HOT_LOADER__.register(Select, 'Select', 'src/Select.js');

    __REACT_HOT_LOADER__.register(_default, 'default', 'src/Select.js');
}();

;
<|endoftext|>


<commit_before>define([
	'goo/entities/EntitySelection',
	'goo/entities/systems/System',
	'goo/entities/SystemBus',
	'goo/math/Transform',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/shapes/Sphere',
	'goo/shapes/Box',
	'goo/shapes/Cylinder'
],
function (
	EntitySelection,
	System,
	SystemBus,
	Transform,
	Material,
	ShaderLib,
	Sphere,
	Box,
	Cylinder
) {
	'use strict';

	/**
	 * Renders all ParticleSystemComponents in the scene.
	 * @extends System
	 */
	function ParticleDebugRenderSystem() {
		System.call(this, 'ParticleDebugRenderSystem', ['ParticleSystemComponent']);

		this.priority = 3;

		this.renderList = [];
		this.camera = null;

		SystemBus.addListener('goo.setCurrentCamera', function (newCam) {
			this.camera = newCam.camera;
		}.bind(this));

		/**
		 * If set to true, all entities with a ParticleSystemComponent attached is rendered, and the selection is disregarded.
		 * @type {boolean}
		 */
		this.renderAll = true;

		/**
		 * The selected entities to be rendered.
		 * @type {EntitySelection}
		 */
		this.selection = new EntitySelection();

		var material = new Material(ShaderLib.simpleColored);
		material.uniforms.color = [0, 1, 0];
		this.sphereRenderable = {
			materials: [material],
			transform: new Transform(),
			meshData: new Sphere(12,12,1)
		};
		this.boxRenderable = {
			materials: [material],
			transform: new Transform(),
			meshData: new Box(1,1,1)
		};
		this.coneRenderable = {
			materials: [material],
			transform: new Transform(),
			meshData: new Cylinder(16, 1, 1, 1)
		};
		this.offsetTransform = new Transform();
	}
	ParticleDebugRenderSystem.prototype = Object.create(System.prototype);
	ParticleDebugRenderSystem.prototype.constructor = ParticleDebugRenderSystem;

	/**
	 * @private
	 * @param  {array} entities
	 */
	ParticleDebugRenderSystem.prototype.process = function (entities, tpf) {};

	/**
	 * @private
	 * @param  {Renderer} renderer
	 */
	ParticleDebugRenderSystem.prototype.render = function (renderer) {
		if (!this.camera || this.passive) {
			return;
		}

		renderer.checkResize(this.camera);

		var entities = this._activeEntities;
		for (var i = 0, N = entities.length; i !== N; i++) {
			var entity = entities[i];

			if (!this.renderAll && !this.selection.contains(entity)) {
				// Render selection is enabled, but this entity is not a part of it
				continue;
			}

			var renderable;
			switch(entity.particleSystemComponent.shapeType){
			case 'sphere':
				renderable = this.sphereRenderable;
				var radius = entity.particleSystemComponent.sphereRadius;
				renderable.transform.scale.setDirect(radius,radius,radius);
				this.offsetTransform.setIdentity();
				break;
			case 'box':
				renderable = this.boxRenderable;
				renderable.transform.scale.copy(entity.particleSystemComponent.boxExtents);
				this.offsetTransform.setIdentity();
				break;
			case 'cone':
				var coneRadius = entity.particleSystemComponent.coneRadius;
				renderable = this.coneRenderable;
				this.offsetTransform.setIdentity();
				renderable.meshData.radiusTop = coneRadius + Math.tan(entity.particleSystemComponent.coneAngle) * entity.particleSystemComponent.coneLength;
				renderable.meshData.radiusBottom = coneRadius;
				renderable.meshData.height = entity.particleSystemComponent.coneLength;
				renderable.meshData.rebuild();
				renderable.meshData.setVertexDataUpdated();
				this.offsetTransform.translation.set(0,0,entity.particleSystemComponent.coneLength * 0.5);
				this.offsetTransform.rotation.rotateX(3 * Math.PI / 2);
				break;
			}

			if(renderable){
				renderable.meshData.indexModes = ['Lines'];

				var transform = renderable.transform;
				var worldTransform = entity.transformComponent.worldTransform;

				transform.rotation.copy(this.offsetTransform.rotation);
				transform.rotation.mul(worldTransform.rotation);

				this.offsetTransform.translation.applyPost(transform.rotation);
				transform.translation.copy(this.offsetTransform.translation).add(worldTransform.translation);

				transform.update();
				renderer.render(renderable, this.camera, null, null, false);
			}
		}
	};

	/**
	 * @private
	 */
	ParticleDebugRenderSystem.prototype.cleanup = function () {};

	/**
	 * @private
	 */
	ParticleDebugRenderSystem.prototype.update = function () {
		var entities = this._activeEntities;
		var l = entities.length;
		while(l--){
			var entity = entities[l];

			if (this.renderAll || this.selection.contains(entity)) {
				entity.particleSystemComponent.play();
				entity.particleSystemComponent.meshEntity.meshRendererComponent.hidden = false;
			} else {
				entity.particleSystemComponent.stop();
				entity.particleSystemComponent._updateVertexData();
				entity.particleSystemComponent.meshEntity.meshRendererComponent.hidden = true;
			}
		}
	};

	return ParticleDebugRenderSystem;
});<commit_msg>fix show/hide glitch in the ParticleDebugRenderSystem<commit_after>define([
	'goo/entities/EntitySelection',
	'goo/entities/systems/System',
	'goo/entities/SystemBus',
	'goo/math/Transform',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/shapes/Sphere',
	'goo/shapes/Box',
	'goo/shapes/Cylinder'
],
function (
	EntitySelection,
	System,
	SystemBus,
	Transform,
	Material,
	ShaderLib,
	Sphere,
	Box,
	Cylinder
) {
	'use strict';

	/**
	 * Renders all ParticleSystemComponents in the scene.
	 * @extends System
	 */
	function ParticleDebugRenderSystem() {
		System.call(this, 'ParticleDebugRenderSystem', ['ParticleSystemComponent']);

		this.priority = 3;

		this.renderList = [];
		this.camera = null;

		SystemBus.addListener('goo.setCurrentCamera', function (newCam) {
			this.camera = newCam.camera;
		}.bind(this));

		/**
		 * If set to true, all entities with a ParticleSystemComponent attached is rendered, and the selection is disregarded.
		 * @type {boolean}
		 */
		this.renderAll = true;

		/**
		 * The selected entities to be rendered.
		 * @type {EntitySelection}
		 */
		this.selection = new EntitySelection();

		var material = new Material(ShaderLib.simpleColored);
		material.uniforms.color = [0, 1, 0];
		this.sphereRenderable = {
			materials: [material],
			transform: new Transform(),
			meshData: new Sphere(12,12,1)
		};
		this.boxRenderable = {
			materials: [material],
			transform: new Transform(),
			meshData: new Box(1,1,1)
		};
		this.coneRenderable = {
			materials: [material],
			transform: new Transform(),
			meshData: new Cylinder(16, 1, 1, 1)
		};
		this.offsetTransform = new Transform();
	}
	ParticleDebugRenderSystem.prototype = Object.create(System.prototype);
	ParticleDebugRenderSystem.prototype.constructor = ParticleDebugRenderSystem;

	/**
	 * @private
	 * @param  {array} entities
	 */
	ParticleDebugRenderSystem.prototype.process = function (entities, tpf) {
		for(var i=0; i<entities.length; i++){
			var entity = entities[i];
			var meshEntity = entity.particleSystemComponent.meshEntity;
			if(meshEntity){
				if(entity.isVisiblyHidden())
					meshEntity.meshRendererComponent.hidden = true;
				else
					meshEntity.meshRendererComponent.hidden = !(this.renderAll || this.selection.contains(entity));
			}
		}
	};

	/**
	 * @private
	 * @param  {Renderer} renderer
	 */
	ParticleDebugRenderSystem.prototype.render = function (renderer) {
		if (!this.camera || this.passive) {
			return;
		}

		renderer.checkResize(this.camera);

		var entities = this._activeEntities;
		for (var i = 0, N = entities.length; i !== N; i++) {
			var entity = entities[i];

			if (!this.renderAll && !this.selection.contains(entity)) {
				// Render selection is enabled, but this entity is not a part of it
				continue;
			}

			var renderable;
			switch(entity.particleSystemComponent.shapeType){
			case 'sphere':
				renderable = this.sphereRenderable;
				var radius = entity.particleSystemComponent.sphereRadius;
				renderable.transform.scale.setDirect(radius,radius,radius);
				this.offsetTransform.setIdentity();
				break;
			case 'box':
				renderable = this.boxRenderable;
				renderable.transform.scale.copy(entity.particleSystemComponent.boxExtents);
				this.offsetTransform.setIdentity();
				break;
			case 'cone':
				var coneRadius = entity.particleSystemComponent.coneRadius;
				renderable = this.coneRenderable;
				this.offsetTransform.setIdentity();
				renderable.meshData.radiusTop = coneRadius + Math.tan(entity.particleSystemComponent.coneAngle) * entity.particleSystemComponent.coneLength;
				renderable.meshData.radiusBottom = coneRadius;
				renderable.meshData.height = entity.particleSystemComponent.coneLength;
				renderable.meshData.rebuild();
				renderable.meshData.setVertexDataUpdated();
				this.offsetTransform.translation.set(0,0,entity.particleSystemComponent.coneLength * 0.5);
				this.offsetTransform.rotation.rotateX(3 * Math.PI / 2);
				break;
			}

			if(renderable){
				renderable.meshData.indexModes = ['Lines'];

				var transform = renderable.transform;
				var worldTransform = entity.transformComponent.worldTransform;

				transform.rotation.copy(this.offsetTransform.rotation);
				transform.rotation.mul(worldTransform.rotation);

				this.offsetTransform.translation.applyPost(transform.rotation);
				transform.translation.copy(this.offsetTransform.translation).add(worldTransform.translation);

				transform.update();
				renderer.render(renderable, this.camera, null, null, false);
			}
		}
	};

	/**
	 * @private
	 */
	ParticleDebugRenderSystem.prototype.cleanup = function () {};

	/**
	 * @private
	 */
	ParticleDebugRenderSystem.prototype.update = function () {
		var entities = this._activeEntities;
		var l = entities.length;
		while(l--){
			var entity = entities[l];

			if (this.renderAll || this.selection.contains(entity)) {
				entity.particleSystemComponent.play();
			} else {
				entity.particleSystemComponent.stop();
			}
		}

		this.process(this._activeEntities);
	};

	return ParticleDebugRenderSystem;
});<|endoftext|>


<commit_before>!function ($) {

    "use strict";

    function accordionGroupTemplate(parentId, $heading){
        var tabSelector = $heading.attr('data-target'),
            active = $heading.parent().is('.active');

        if (!tabSelector) {
            tabSelector = $heading.attr('href');
            tabSelector = tabSelector && tabSelector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
        }

        var $tabContent = $(tabSelector),
            groupId = $tabContent.attr('id') + '-collapse';

        return '
' +
            '
' +
            '       ' +
            '           ' + $heading.html() +
            '       ' +
            '
' +
            '
' +
            '
' +
            '           ' + $tabContent.html() +
            '
' +
            '
' +
            '
';
    }

    function accordionTemplate(id, $headings){
        var accordionTemplate = '
';
        $headings.each(function(){
            var $heading = $(this);
            accordionTemplate += accordionGroupTemplate(id, $heading);
        });
        accordionTemplate += '
';
        return accordionTemplate;
    }

    /* TAB-COLLAPSE PLUGIN DEFINITION
     * ===================== */

    $.fn.tabCollapse = function ( option ) {
        return this.each(function () {
            var $this = $(this),
                $headings =  $this.find('li:not(.dropdown) [data-toggle="tab"], li:not(.dropdown) [data-toggle="pill"]');
            var accordionHtml = accordionTemplate($this.attr('id') + '-accordion', $headings);
            $('.container').append(accordionHtml);
            $this.addClass('hidden-phone');
            $this.find('+ .tab-content').addClass('hidden-phone');
        })
    };

}(window.jQuery);<commit_msg>insert after fix<commit_after>!function ($) {

    "use strict";

    function accordionGroupTemplate(parentId, $heading){
        var tabSelector = $heading.attr('data-target'),
            active = $heading.parent().is('.active');

        if (!tabSelector) {
            tabSelector = $heading.attr('href');
            tabSelector = tabSelector && tabSelector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
        }

        var $tabContent = $(tabSelector),
            groupId = $tabContent.attr('id') + '-collapse';

        return '
' +
            '
' +
            '       ' +
            '           ' + $heading.html() +
            '       ' +
            '
' +
            '
' +
            '
' +
            '           ' + $tabContent.html() +
            '
' +
            '
' +
            '
';
    }

    function accordionTemplate(id, $headings){
        var accordionTemplate = '
';
        $headings.each(function(){
            var $heading = $(this);
            accordionTemplate += accordionGroupTemplate(id, $heading);
        });
        accordionTemplate += '
';
        return accordionTemplate;
    }

    /* TAB-COLLAPSE PLUGIN DEFINITION
     * ===================== */

    $.fn.tabCollapse = function ( ) {
        return this.each(function () {
            var $this = $(this),
                $headings =  $this.find('li:not(.dropdown) [data-toggle="tab"], li:not(.dropdown) [data-toggle="pill"]');
            var accordionHtml = accordionTemplate($this.attr('id') + '-accordion', $headings);
            $this.after(accordionHtml);
            $this.addClass('hidden-phone');
            $this.siblings('.tab-content').addClass('hidden-phone');
        })
    };

}(window.jQuery);<|endoftext|>


<commit_before>"use strict";
var cluster = require("cluster");
var isDevelop = require("../efront/isDevelop");
var isDebug = require("../efront/isDebug")
var message = require("../message");
var clients = require("./clients");
var fs = require("fs");
var path = require("path");

var counter = 0;
var quitting = [], notkilled = [];
var workers = [];
var cpus = require('os').cpus().map(a => 0);
if (isDevelop || isDebug) {
    cpus = [0];
}
var end = function () {
    quitting = quitting.concat(workers);
    if (!quitting.length) {
        console.info("正在退出..");
        afterend();
    }
    workers.splice(0, workers.length);
    exit();
};
var afterend = function () {
    process.removeAllListeners();
    watch.close();
    notkilled.forEach(a => a.kill("SIGKILL"));
    clients.destroy();
    process.stdin.unref();
    process.stdout.unref();
    process.stderr.unref();
};
var exit = function () {
    if (!workers.length) var isQuit = true;
    quitting.splice(0).forEach(function (worker) {
        if (worker.working) message.send(worker, 'quit');
    });
};
var broadcast = function (data) {
    quitting.concat(workers).forEach(function (worker) {
        if (worker.working) message.send(worker, 'onbroadcast', data);
    });
};
var run = function () {
    if (quitting.length) return;
    if (run.ing) {
        run.ing = 2;
        return;
    }
    run.ing = true;
    quitting = quitting.concat(workers);
    if (quitting.length) console.info(`${quitting.length}个子进程准备退出:${quitting.map(a => a.id)}`);
    var working = 0;
    var _workers = cpus.map(function () {
        counter++;
        var mem = require("os").freemem() / 1024 - 256 | 0;
        if (mem < 1024) mem = 1024;
        var worker = cluster.fork({
            "NODE_OPTIONS": "--max-old-space-size=" + mem,
        });
        worker.on("listening", function () {
            this.working = true;
            working++;
            if (working === cpus.length) {
                console.info(`${workers.length}个子进程已启动:${workers.map(a => a.id)}`);
                run.ing = false;
                exit();
            }
        });
        worker.on("exit", function () {
            if (worker.exitedAfterDisconnect !== true) {
                for (var cx = workers.length - 1; cx >= 0; cx--) {
                    if (workers[cx] === this) workers.splice(cx, 1);
                }
            }
            counter--;
            if (!counter && !workers.length) {
                afterend();
            }
        });
        worker.on("message", message);
        return worker;
    });
    workers.push.apply(workers, _workers);
};
var isProduction = function develop() { return develop.name === 'develop' }();
var watch = {
    close: function (watchs) {
        watchs.forEach(a => a.close());
    }.bind(null, isProduction ? [
        "",
        "../efront",
        "../compile",
        "../message",
    ].map(a => path.join(__dirname, a)).filter(fs.existsSync).map(a => fs.watch(a, { recursive: /^(darwin|win32)$/i.test(process.platform) }, run)) : [])
};
message.quit = end;
message.broadcast = broadcast;
message.deliver = function (a) {
    var [clientid, msgid] = a;
    var client = clients.attach(clientid);
    if (!client) return;
    if (client.messages.length) {
        client.deliver(msgid);
        return;
    }
    var count = 0;
    var rest = workers.length;
    client.refresh();
    workers.forEach(function (worker) {
        if (worker.working) message.send(worker, 'deliver', [clientid, msgid], function (a) {
            count += +a || 0;
            rest--;
            if (!rest && !count) {
                client.deliver(msgid);
                client.keep();
            }
        }, null);
    });
};
message.getmark = function () {
    return clients.getMark();
};
message.addmark = function (m) {
    clients.addMark(m);
    workers.forEach(function (worker) {
        if (worker.working) message.send(worker, 'addmark', m);
    });
};
message.receive = function (clientid) {
    var client = clients.get(clientid);
    if (client) {
        var messages = client.messages.slice(0);
        client.clean();
        return messages;
    }
};
message.cluster = function ([id, methord, params]) {
    for (var w of workers) {
        if (w.id === id) return new Promise(function (ok, oh) {
            message.send(w, methord, params, function (error, res) {
                if (error) return oh(error);
                ok(res);
            });
        })
    }
    throw "进程已退出";
};
message.clusterList = function (id) {
    return workers.map(w => w.id);
};
message.rehost = function () {
    var argv = process.__proto__ && process.__proto__.argv || process.argv;
    end();
    var child = require("child_process").spawn(argv[0], argv.slice(1), {
        detached: true,
        stdio: 'ignore'
    });
    child.unref();
};
require("../efront/quitme")(end);
run();<commit_msg>屏蔽一些错误<commit_after>"use strict";
var cluster = require("cluster");
var isDevelop = require("../efront/isDevelop");
var isDebug = require("../efront/isDebug")
var message = require("../message");
var clients = require("./clients");
var fs = require("fs");
var path = require("path");

var counter = 0;
var quitting = [], notkilled = [];
var workers = [];
var cpus = require('os').cpus().map(a => 0);
if (isDevelop || isDebug) {
    cpus = [0];
}
var end = function () {
    quitting = quitting.concat(workers);
    if (!quitting.length) {
        console.info("正在退出..");
        afterend();
    }
    workers.splice(0, workers.length);
    exit();
};
var afterend = function () {
    process.removeAllListeners();
    watch.close();
    notkilled.forEach(a => a.kill("SIGKILL"));
    clients.destroy();
    if (process.stdin.unref) process.stdin.unref();
    if (process.stderr.unref) process.stderr.unref();
    if (process.stdout.unref) process.stdout.unref();
};
var exit = function () {
    if (!workers.length) var isQuit = true;
    quitting.splice(0).forEach(function (worker) {
        if (worker.working) message.send(worker, 'quit');
    });
};
var broadcast = function (data) {
    quitting.concat(workers).forEach(function (worker) {
        if (worker.working) message.send(worker, 'onbroadcast', data);
    });
};
var run = function () {
    if (quitting.length) return;
    if (run.ing) {
        run.ing = 2;
        return;
    }
    run.ing = true;
    quitting = quitting.concat(workers);
    if (quitting.length) console.info(`${quitting.length}个子进程准备退出:${quitting.map(a => a.id)}`);
    var working = 0;
    var _workers = cpus.map(function () {
        counter++;
        var mem = require("os").freemem() / 1024 - 256 | 0;
        if (mem < 1024) mem = 1024;
        var worker = cluster.fork({
            "NODE_OPTIONS": "--max-old-space-size=" + mem,
        });
        worker.on("listening", function () {
            this.working = true;
            working++;
            if (working === cpus.length) {
                console.info(`${workers.length}个子进程已启动:${workers.map(a => a.id)}`);
                run.ing = false;
                exit();
            }
        });
        worker.on("exit", function () {
            if (worker.exitedAfterDisconnect !== true) {
                for (var cx = workers.length - 1; cx >= 0; cx--) {
                    if (workers[cx] === this) workers.splice(cx, 1);
                }
            }
            counter--;
            if (!counter && !workers.length) {
                afterend();
            }
        });
        worker.on("message", message);
        return worker;
    });
    workers.push.apply(workers, _workers);
};
var isProduction = function develop() { return develop.name === 'develop' }();
var watch = {
    close: function (watchs) {
        watchs.forEach(a => a.close());
    }.bind(null, isProduction ? [
        "",
        "../efront",
        "../compile",
        "../message",
    ].map(a => path.join(__dirname, a)).filter(fs.existsSync).map(a => fs.watch(a, { recursive: /^(darwin|win32)$/i.test(process.platform) }, run)) : [])
};
message.quit = end;
message.broadcast = broadcast;
message.deliver = function (a) {
    var [clientid, msgid] = a;
    var client = clients.attach(clientid);
    if (!client) return;
    if (client.messages.length) {
        client.deliver(msgid);
        return;
    }
    var count = 0;
    var rest = workers.length;
    client.refresh();
    workers.forEach(function (worker) {
        if (worker.working) message.send(worker, 'deliver', [clientid, msgid], function (a) {
            count += +a || 0;
            rest--;
            if (!rest && !count) {
                client.deliver(msgid);
                client.keep();
            }
        }, null);
    });
};
message.getmark = function () {
    return clients.getMark();
};
message.addmark = function (m) {
    clients.addMark(m);
    workers.forEach(function (worker) {
        if (worker.working) message.send(worker, 'addmark', m);
    });
};
message.receive = function (clientid) {
    var client = clients.get(clientid);
    if (client) {
        var messages = client.messages.slice(0);
        client.clean();
        return messages;
    }
};
message.cluster = function ([id, methord, params]) {
    for (var w of workers) {
        if (w.id === id) return new Promise(function (ok, oh) {
            message.send(w, methord, params, function (error, res) {
                if (error) return oh(error);
                ok(res);
            });
        })
    }
    throw "进程已退出";
};
message.clusterList = function (id) {
    return workers.map(w => w.id);
};
message.rehost = function () {
    var argv = process.__proto__ && process.__proto__.argv || process.argv;
    end();
    var child = require("child_process").spawn(argv[0], argv.slice(1), {
        detached: true,
        stdio: 'ignore'
    });
    child.unref();
};
require("../efront/quitme")(end);
run();<|endoftext|>


<commit_before>'use strict';

describe('farmbuild.nutrientCalculator module', function() {

  // instantiate service
  var cowsPurchased;

  beforeEach(module('farmbuild.nutrientCalculator'));

  beforeEach(inject(function (_cowsPurchased_) {
    cowsPurchased = _cowsPurchased_;
  }));

  describe('cowsPurchased factory', function(){

    it('cowsPurchased should be defined', inject(function() {
      expect(cowsPurchased).toBeDefined();
    }));

    it('cowsPurchased.addTypes should return undefined if type\'s name is not alphabetical', inject(function() {
      expect(cowsPurchased.addType(2, 50)).toBeUndefined();
      expect(cowsPurchased.addType('!2', 50)).toBeUndefined();
      expect(cowsPurchased.addType('new', 'w')).toBeUndefined();
    }));

    it('cowsPurchased.addTypes should return new type if type\'s is valid', inject(function() {
      expect(cowsPurchased.addType('newType', 50)).toBeDefined();
      expect(cowsPurchased.addType('newType', 50.4).addType).toBeDefined();
    }));

    it('cowsPurchased.removeTypeByIndex should return undefined for invalid index', inject(function() {
      expect(cowsPurchased.removeTypeByIndex(cowsPurchased.types().length)).toBeUndefined();
      expect(cowsPurchased.removeTypeByIndex(-1)).toBeUndefined();
    }));

    it('cowsPurchased.removeTypeByIndex should remove item for valid index', inject(function() {
      var count = cowsPurchased.types().length;
      expect(cowsPurchased.removeTypeByIndex(count-1).length).toEqual(count-1);
    }));

    it('cowsPurchased.removeTypeByIndex should remove correct item for valid index', inject(function() {
      var item = cowsPurchased.types()[2],
        name = item.name, weight = item.weight,
        found = '',
      reducedCows = cowsPurchased.removeTypeByIndex(2);
      angular.forEach(reducedCows, function(cow){
        if(cow.name === name && cow.weight === weight){
          found = cow;
        }
      });
      expect(found).toEqual('');
    }));

    it('cowsPurchased.removeTypeByName should remove correct item for valid name', inject(function() {
      var item = cowsPurchased.types()[2],
        name = item.name,
        found = '',
      reducedCows = cowsPurchased.removeTypeByName(name);
      angular.forEach(reducedCows, function(cow){
        if(cow.name === name){
          found = cow;
        }
      });
      expect(found).toEqual('');
    }));

    it('cowsPurchased.removeTypeByName should remove all correct items with the specified name', inject(function() {
      var item = cowsPurchased.types()[2],
        name = item.name,
        found = '',
        reducedCows;
      cowsPurchased.addType(name, 100001);
      reducedCows = cowsPurchased.removeTypeByName(name);
      angular.forEach(reducedCows, function(cow){
        if(cow.name === name){
          found = cow;
        }
      });
      expect(found).toEqual('');
    }));

    it('cowsPurchased.calculate should return nutrient data', inject(function() {
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}])).toBeDefined();
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).cows).toBeDefined();
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).weight).toEqual(1800);
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).numberOfCows).toEqual(3);
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).sulphurInKg).toEqual(14.4);
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).nitrogenInKg).toEqual(50.4);
    }));

    it('cowsPurchased.addType should return undefined if cows parameter passed is not correct (alphabetical name, number for weight)', inject(function() {
      expect(cowsPurchased.addType('@', 50)).toBeUndefined();
      expect(cowsPurchased.addType('newType', -50)).toBeUndefined();
    }));

    it('cowsPurchased.calculate should return undefined for negative number', inject(function() {
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:-2}, {name:'Average adult cattle', weight: 500, numberOfCows:-1}])).toBeUndefined();
    }));

  });

});
<commit_msg>update test case reference<commit_after>//Automated test case as described by TC05

'use strict';

describe('farmbuild.nutrientCalculator module', function() {

  // instantiate service
  var cowsPurchased;

  beforeEach(module('farmbuild.nutrientCalculator'));

  beforeEach(inject(function (_cowsPurchased_) {
    cowsPurchased = _cowsPurchased_;
  }));

  describe('cowsPurchased factory', function(){

    it('cowsPurchased should be defined', inject(function() {
      expect(cowsPurchased).toBeDefined();
    }));

    it('cowsPurchased.addTypes should return undefined if type\'s name is not alphabetical', inject(function() {
      expect(cowsPurchased.addType(2, 50)).toBeUndefined();
      expect(cowsPurchased.addType('!2', 50)).toBeUndefined();
      expect(cowsPurchased.addType('new', 'w')).toBeUndefined();
    }));

    it('cowsPurchased.addTypes should return new type if type\'s is valid', inject(function() {
      expect(cowsPurchased.addType('newType', 50)).toBeDefined();
      expect(cowsPurchased.addType('newType', 50.4).addType).toBeDefined();
    }));

    it('cowsPurchased.removeTypeByIndex should return undefined for invalid index', inject(function() {
      expect(cowsPurchased.removeTypeByIndex(cowsPurchased.types().length)).toBeUndefined();
      expect(cowsPurchased.removeTypeByIndex(-1)).toBeUndefined();
    }));

    it('cowsPurchased.removeTypeByIndex should remove item for valid index', inject(function() {
      var count = cowsPurchased.types().length;
      expect(cowsPurchased.removeTypeByIndex(count-1).length).toEqual(count-1);
    }));

    it('cowsPurchased.removeTypeByIndex should remove correct item for valid index', inject(function() {
      var item = cowsPurchased.types()[2],
        name = item.name, weight = item.weight,
        found = '',
      reducedCows = cowsPurchased.removeTypeByIndex(2);
      angular.forEach(reducedCows, function(cow){
        if(cow.name === name && cow.weight === weight){
          found = cow;
        }
      });
      expect(found).toEqual('');
    }));

    it('cowsPurchased.removeTypeByName should remove correct item for valid name', inject(function() {
      var item = cowsPurchased.types()[2],
        name = item.name,
        found = '',
      reducedCows = cowsPurchased.removeTypeByName(name);
      angular.forEach(reducedCows, function(cow){
        if(cow.name === name){
          found = cow;
        }
      });
      expect(found).toEqual('');
    }));

    it('cowsPurchased.removeTypeByName should remove all correct items with the specified name', inject(function() {
      var item = cowsPurchased.types()[2],
        name = item.name,
        found = '',
        reducedCows;
      cowsPurchased.addType(name, 100001);
      reducedCows = cowsPurchased.removeTypeByName(name);
      angular.forEach(reducedCows, function(cow){
        if(cow.name === name){
          found = cow;
        }
      });
      expect(found).toEqual('');
    }));

    it('cowsPurchased.calculate should return nutrient data', inject(function() {
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}])).toBeDefined();
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).cows).toBeDefined();
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).weight).toEqual(1800);
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).numberOfCows).toEqual(3);
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).sulphurInKg).toEqual(14.4);
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:2}, {name:'Average adult cattle', weight: 500, numberOfCows:1}]).nitrogenInKg).toEqual(50.4);
    }));

    it('cowsPurchased.addType should return undefined if cows parameter passed is not correct (alphabetical name, number for weight)', inject(function() {
      expect(cowsPurchased.addType('@', 50)).toBeUndefined();
      expect(cowsPurchased.addType('newType', -50)).toBeUndefined();
    }));

    it('cowsPurchased.calculate should return undefined for negative number', inject(function() {
      expect(cowsPurchased.calculate([{name:'Heavy adult cattle', weight: 650, numberOfCows:-2}, {name:'Average adult cattle', weight: 500, numberOfCows:-1}])).toBeUndefined();
    }));

  });

});
<|endoftext|>