code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
"use strict";
const people = require("./people");
const util = require("./util");
/*
This is the main model code for building the buddy list.
We also rely on presence.js to compute the actual presence
for users. We glue in other "people" data and do
filtering/sorting of the data that we'll send into the view.
*/
exports.max_size_before_shrinking = 600;
const fade_config = {
get_user_id(item) {
return item.user_id;
},
fade(item) {
item.faded = true;
},
unfade(item) {
item.faded = false;
},
};
exports.get_user_circle_class = function (user_id) {
const status = exports.buddy_status(user_id);
switch (status) {
case "active":
return "user_circle_green";
case "idle":
return "user_circle_orange";
case "away_them":
case "away_me":
return "user_circle_empty_line";
default:
return "user_circle_empty";
}
};
exports.status_description = function (user_id) {
const status = exports.buddy_status(user_id);
switch (status) {
case "active":
return i18n.t("Active");
case "idle":
return i18n.t("Idle");
case "away_them":
case "away_me":
return i18n.t("Unavailable");
default:
return i18n.t("Offline");
}
};
exports.level = function (user_id) {
if (people.is_my_user_id(user_id)) {
// Always put current user at the top.
return 0;
}
const status = exports.buddy_status(user_id);
switch (status) {
case "active":
return 1;
case "idle":
return 2;
case "away_them":
return 3;
default:
return 3;
}
};
exports.buddy_status = function (user_id) {
if (user_status.is_away(user_id)) {
if (people.is_my_user_id(user_id)) {
return "away_me";
}
return "away_them";
}
// get active/idle/etc.
return presence.get_status(user_id);
};
exports.compare_function = function (a, b) {
const level_a = exports.level(a);
const level_b = exports.level(b);
const diff = level_a - level_b;
if (diff !== 0) {
return diff;
}
// Sort equivalent PM names alphabetically
const person_a = people.get_by_user_id(a);
const person_b = people.get_by_user_id(b);
const full_name_a = person_a ? person_a.full_name : "";
const full_name_b = person_b ? person_b.full_name : "";
return util.strcmp(full_name_a, full_name_b);
};
exports.sort_users = function (user_ids) {
// TODO sort by unread count first, once we support that
user_ids.sort(exports.compare_function);
return user_ids;
};
function filter_user_ids(user_filter_text, user_ids) {
if (user_filter_text === "") {
return user_ids;
}
user_ids = user_ids.filter((user_id) => !people.is_my_user_id(user_id));
let search_terms = user_filter_text.toLowerCase().split(/[,|]+/);
search_terms = search_terms.map((s) => s.trim());
const persons = user_ids.map((user_id) => people.get_by_user_id(user_id));
const user_id_dict = people.filter_people_by_search_terms(persons, search_terms);
return Array.from(user_id_dict.keys());
}
exports.matches_filter = function (user_filter_text, user_id) {
// This is a roundabout way of checking a user if you look
// too hard at it, but it should be fine for now.
return filter_user_ids(user_filter_text, [user_id]).length === 1;
};
function get_num_unread(user_id) {
return unread.num_unread_for_person(user_id.toString());
}
exports.get_my_user_status = function (user_id) {
if (!people.is_my_user_id(user_id)) {
return undefined;
}
if (user_status.is_away(user_id)) {
return i18n.t("(unavailable)");
}
return i18n.t("(you)");
};
exports.user_last_seen_time_status = function (user_id) {
const status = presence.get_status(user_id);
if (status === "active") {
return i18n.t("Active now");
}
if (page_params.realm_is_zephyr_mirror_realm) {
// We don't send presence data to clients in Zephyr mirroring realms
return i18n.t("Unknown");
}
// There are situations where the client has incomplete presence
// history on a user. This can happen when users are deactivated,
// or when they just haven't been present in a long time (and we
// may have queries on presence that go back only N weeks).
//
// We give the somewhat vague status of "Unknown" for these users.
const last_active_date = presence.last_active_date(user_id);
if (last_active_date === undefined) {
return i18n.t("More than 2 weeks ago");
}
return timerender.last_seen_status_from_date(last_active_date.clone());
};
exports.info_for = function (user_id) {
const user_circle_class = exports.get_user_circle_class(user_id);
const person = people.get_by_user_id(user_id);
const my_user_status = exports.get_my_user_status(user_id);
const user_circle_status = exports.status_description(user_id);
return {
href: hash_util.pm_with_uri(person.email),
name: person.full_name,
user_id,
my_user_status,
is_current_user: people.is_my_user_id(user_id),
num_unread: get_num_unread(user_id),
user_circle_class,
user_circle_status,
};
};
function get_last_seen(active_status, last_seen) {
if (active_status === "active") {
return last_seen;
}
const last_seen_text = i18n.t("Last active: __last_seen__", {last_seen});
return last_seen_text;
}
exports.get_title_data = function (user_ids_string, is_group) {
if (is_group === true) {
// For groups, just return a string with recipient names.
return {
first_line: people.get_recipients(user_ids_string),
second_line: "",
third_line: "",
};
}
// Since it's not a group, user_ids_string is a single user ID.
const user_id = Number.parseInt(user_ids_string, 10);
const person = people.get_by_user_id(user_id);
if (person.is_bot) {
const bot_owner = people.get_bot_owner_user(person);
if (bot_owner) {
const bot_owner_name = i18n.t("Owner: __name__", {name: bot_owner.full_name});
return {
first_line: person.full_name,
second_line: bot_owner_name,
third_line: "",
};
}
// Bot does not have an owner.
return {
first_line: person.full_name,
second_line: "",
third_line: "",
};
}
// For buddy list and individual PMS. Since is_group=False, it's
// a single, human, user.
const active_status = presence.get_status(user_id);
const last_seen = exports.user_last_seen_time_status(user_id);
// Users has a status.
if (user_status.get_status_text(user_id)) {
return {
first_line: person.full_name,
second_line: user_status.get_status_text(user_id),
third_line: get_last_seen(active_status, last_seen),
};
}
// Users does not have a status.
return {
first_line: person.full_name,
second_line: get_last_seen(active_status, last_seen),
third_line: "",
};
};
exports.get_item = function (user_id) {
const info = exports.info_for(user_id);
compose_fade.update_user_info([info], fade_config);
return info;
};
function user_is_recently_active(user_id) {
// return true if the user has a green/orange circle
return exports.level(user_id) <= 2;
}
function maybe_shrink_list(user_ids, user_filter_text) {
if (user_ids.length <= exports.max_size_before_shrinking) {
return user_ids;
}
if (user_filter_text) {
// If the user types something, we want to show all
// users matching the text, even if they have not been
// online recently.
// For super common letters like "s", we may
// eventually want to filter down to only users that
// are in presence.get_user_ids().
return user_ids;
}
user_ids = user_ids.filter(user_is_recently_active);
return user_ids;
}
function get_user_id_list(user_filter_text) {
let user_ids;
if (user_filter_text) {
// If there's a filter, select from all users, not just those
// recently active.
user_ids = filter_user_ids(user_filter_text, people.get_active_user_ids());
} else {
// From large realms, the user_ids in presence may exclude
// users who have been idle more than three weeks. When the
// filter text is blank, we show only those recently active users.
user_ids = presence.get_user_ids();
}
user_ids = user_ids.filter((user_id) => {
const person = people.get_by_user_id(user_id);
if (!person) {
blueslip.warn("Got user_id in presence but not people: " + user_id);
return false;
}
// if the user is bot, do not show in presence data.
return !person.is_bot;
});
return user_ids;
}
exports.get_filtered_and_sorted_user_ids = function (user_filter_text) {
let user_ids;
user_ids = get_user_id_list(user_filter_text);
user_ids = maybe_shrink_list(user_ids, user_filter_text);
return exports.sort_users(user_ids);
};
exports.get_items_for_users = function (user_ids) {
const user_info = user_ids.map(exports.info_for);
compose_fade.update_user_info(user_info, fade_config);
return user_info;
};
exports.huddle_fraction_present = function (huddle) {
const user_ids = huddle.split(",").map((s) => Number.parseInt(s, 10));
let num_present = 0;
for (const user_id of user_ids) {
if (presence.is_active(user_id)) {
num_present += 1;
}
}
if (num_present === user_ids.length) {
return 1;
} else if (num_present !== 0) {
return 0.5;
}
return undefined;
};
window.buddy_data = exports;
| showell/zulip | static/js/buddy_data.js | JavaScript | apache-2.0 | 10,121 |
// test inv
var assert = require('assert'),
approx = require('../../../tools/approx'),
error = require('../../../lib/error/index'),
math = require('../../../index')(),
inv = math.inv;
describe('inv', function() {
it('should return the inverse of a number', function() {
assert.deepEqual(inv(4), 1/4);
assert.deepEqual(inv(math.bignumber(4)), math.bignumber(1/4));
});
it('should return the inverse of a matrix with just one value', function() {
assert.deepEqual(inv([4]), [1/4]);
assert.deepEqual(inv([[4]]), [[1/4]]);
});
it('should return the inverse for each element in an array', function() {
assert.deepEqual(inv([4]), [1/4]);
assert.deepEqual(inv([[4]]), [[1/4]]);
approx.deepEqual(inv([
[ 1, 4, 7],
[ 3, 0, 5],
[-1, 9, 11]
]), [
[ 5.625, -2.375, -2.5],
[ 4.75, -2.25, -2],
[-3.375, 1.625, 1.5]
]);
approx.deepEqual(inv([
[ 2, -1, 0],
[-1, 2, -1],
[ 0, -1, 2]
]), [
[3/4, 1/2, 1/4],
[1/2, 1, 1/2],
[1/4, 1/2, 3/4]
]);
// the following will force swapping of empty rows in the middle of the matrix
approx.deepEqual(inv([
[1, 0, 0],
[0, 0, 1],
[0, 1, 0]
]), [
[1, 0, 0],
[0, 0, 1],
[0, 1, 0]
]);
});
it('should return the inverse for each element in a matrix', function() {
assert.deepEqual(inv(math.matrix([4])), math.matrix([1/4]));
assert.deepEqual(inv(math.matrix([[4]])), math.matrix([[1/4]]));
assert.deepEqual(inv(math.matrix([[1,2],[3,4]])), math.matrix([[-2, 1],[1.5, -0.5]]));
});
it('should throw an error in case of non-square matrices', function() {
assert.throws(function () {inv([1,2,3])}, /Matrix must be square/);
assert.throws(function () {inv([[1,2,3], [4,5,6]])}, /Matrix must be square/);
});
it('should throw an error in case of multi dimensional matrices', function() {
assert.throws(function () {inv([[[1,2,3], [4,5,6]]])}, /Matrix must be two dimensional/);
});
it('should throw an error in case of non-invertable matrices', function() {
assert.throws(function () {inv([[0]])}, /Cannot calculate inverse, determinant is zero/);
assert.throws(function () {inv([[1,0], [0,0]])}, /Cannot calculate inverse, determinant is zero/);
assert.throws(function () {inv([[1,1,1], [1,0,0], [0,0,0]])}, /Cannot calculate inverse, determinant is zero/);
});
it('should throw an error in case of wrong number of arguments', function() {
assert.throws(function () {inv()}, error.ArgumentsError);
assert.throws(function () {inv([], [])}, error.ArgumentsError);
});
it('should throw an error in case of invalid type of arguments', function() {
assert.throws(function () {math.concat(inv('str'))}, math.error.TypeError);
});
}); | kelonye/mathjs | test/function/matrix/inv.test.js | JavaScript | apache-2.0 | 2,834 |
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.floor((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
Date.prototype.getStartOfWeek = function() {
var day = this.getDay() - 1;
var startOfWeek;
if (day != -1) {
startOfWeek = new Date(this.getTime() - (24 * 60 * 60 * 1000 * day ));
} else {
startOfWeek = new Date(this.getTime() - (24 * 60 * 60 * 1000 * 6 ));
}
return startOfWeek;
}
var startOfWeek;
$(document).ready(function() {
$('.week-picker').datepicker({
chooseWeek:true,
calendarWeeks:true,
weekStart:1,
format: 'dd M yy'
}).on('changeDate',function(ev){
$("#weekValue").val(ev.date.getWeek()+1);
$("#yearValue").val(ev.date.getFullYear());
$("#selectedWeekRange").html($(".week-picker").val());
startOfWeek = ev.date.getStartOfWeek();
getEmployeeTimesheet();
});
if($("#weekValue").val() == "" && $("#yearValue").val() == ""){
var today = new Date();
var todaysWeek = today.getWeek() + 1;
$("#weekValue").val(today.getWeek() + 1);
$("#yearValue").val(today.getFullYear());
var day = today.getDay() - 1;
startOfWeek = new Date(today.getTime() - (24 * 60 * 60 * 1000 * day ));
var endOfWeek = new Date(today.getTime() + (24 * 60 * 60 * 1000 * (6 - day) ));
$('.week-picker').val($.datepicker.formatDate('dd M yy', startOfWeek) + " - " +
$.datepicker.formatDate('dd M yy', endOfWeek));
$("#selectedWeekRange").html($(".week-picker").val());
getEmployeeTimesheet();
}
$("#thisWeek").click(function(){
$("#weekValue").val(todaysWeek);
$("#yearValue").val(todaysWeek);
});
$("#previousWeek").click(function(){
$("#weekValue").val($("#weekValue").val() - 1 );
getEmployeeTimesheet();
});
$("#weekInfo .goButton").click(getEmployeeTimesheet);
$("#getEmployeeTimesheet").click(getEmployeeTimesheet);
});
function populateDateRange(startDate){
for(i = 0 ;i <= 6 ; i++) {
dateToBeShown = new Date(startDate.getTime() + (24 * 60 * 60 * 1000 * i ));
var dateObj = new Date(dateToBeShown.getMonth()+1 + "/" + dateToBeShown.getDate() + "/" +dateToBeShown.getFullYear());
$('#dayLabel_' + i ).html(moment(dateObj).format("DD MMM"));
}
}
function getEmployeeTimesheet(){
$.get('/timesheet/getTimesheetTable', {id: $('#employeeID').val(),week:$('#weekValue').val(),year:$('#yearValue').val()},
function(response) {
$(".worksheetDiv").empty();
$(".worksheetDiv").html(response);
populateDateRange(startOfWeek);
});
}
| paperlotus/Time-Trotter | target/scala-2.10/classes/public/customScripts/timesheet.js | JavaScript | apache-2.0 | 2,581 |
/*
* CodePress regular expressions for Perl syntax highlighting
*/
Language.syntax = [ // Ruby
{
input : /\"(.*?)(\"|<br>|<\/P>)/g,
output : '<s>"$1$2</s>', // strings double quote
},{
input : /\'(.*?)(\'|<br>|<\/P>)/g,
output : '<s>\'$1$2</s>', // strings single quote
},{
input : /([\$\@\%]+)([\w\.]*)/g,
output : '<a>$1$2</a>', // vars
},{
input : /(def\s+)([\w\.]*)/g,
output : '$1<em>$2</em>', // functions
},{
input : /\b(alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|false|for|if|in|module|next|nil|not|or|redo|rescue|retry|return|self|super|then|true|undef|unless|until|when|while|yield)\b/g,
output : '<b>$1</b>', // reserved words
},{
input : /([\(\){}])/g,
output : '<u>$1</u>', // special chars
},{
input : /#(.*?)(<br>|<\/P>)/g,
output : '<i>#$1</i>$2' // comments
}
];
Language.snippets = [];
Language.complete = [ // Auto complete only for 1 character
{input : '\'',output : '\'$0\'' },
{input : '"', output : '"$0"' },
{input : '(', output : '\($0\)' },
{input : '[', output : '\[$0\]' },
{input : '{', output : '{\n\t$0\n}' }
];
Language.shortcuts = []; | niikoo/NProj | Web/2008/Fenile/_data/codepress/languages/ruby.js | JavaScript | apache-2.0 | 1,156 |
/**
* Copyright 2013-2018 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* 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.
*/
/* eslint-disable consistent-return */
const _ = require('lodash');
const chalk = require('chalk');
const BaseGenerator = require('../generator-base');
const constants = require('../generator-constants');
const prompts = require('./prompts');
const statistics = require('../statistics');
const SERVER_MAIN_SRC_DIR = constants.SERVER_MAIN_SRC_DIR;
const SERVER_TEST_SRC_DIR = constants.SERVER_TEST_SRC_DIR;
let useBlueprint;
module.exports = class extends BaseGenerator {
constructor(args, opts) {
super(args, opts);
this.argument('name', { type: String, required: true });
this.name = this.options.name;
this.option('default', {
type: Boolean,
default: false,
description: 'default option'
});
this.defaultOption = this.options.default;
const blueprint = this.config.get('blueprint');
if (!opts.fromBlueprint) {
// use global variable since getters dont have access to instance property
useBlueprint = this.composeBlueprint(
blueprint,
'spring-controller',
{
force: this.options.force,
arguments: [this.name],
default: this.options.default
}
);
} else {
useBlueprint = false;
}
}
// Public API method used by the getter and also by Blueprints
_initializing() {
return {
initializing() {
this.log(`The spring-controller ${this.name} is being created.`);
const configuration = this.getAllJhipsterConfig(this, true);
this.baseName = configuration.get('baseName');
this.packageName = configuration.get('packageName');
this.packageFolder = configuration.get('packageFolder');
this.databaseType = configuration.get('databaseType');
this.reactiveController = false;
this.applicationType = configuration.get('applicationType');
if (this.applicationType === 'reactive') {
this.reactiveController = true;
}
this.controllerActions = [];
}
};
}
get initializing() {
if (useBlueprint) return;
return this._initializing();
}
// Public API method used by the getter and also by Blueprints
_prompting() {
return {
askForControllerActions: prompts.askForControllerActions
};
}
get prompting() {
if (useBlueprint) return;
return this._prompting();
}
// Public API method used by the getter and also by Blueprints
_default() {
return {
insight() {
statistics.sendSubGenEvent('generator', 'spring-controller');
}
};
}
get default() {
if (useBlueprint) return;
return this._default();
}
// Public API method used by the getter and also by Blueprints
_writing() {
return {
writing() {
this.controllerClass = _.upperFirst(this.name) + (this.name.endsWith('Resource') ? '' : 'Resource');
this.controllerInstance = _.lowerFirst(this.controllerClass);
this.apiPrefix = _.kebabCase(this.name);
if (this.controllerActions.length === 0) {
this.log(chalk.green('No controller actions found, adding a default action'));
this.controllerActions.push({
actionName: 'defaultAction',
actionMethod: 'Get'
});
}
// helper for Java imports
this.usedMethods = _.uniq(this.controllerActions.map(action => action.actionMethod));
this.usedMethods = this.usedMethods.sort();
this.mappingImports = this.usedMethods.map(method => `org.springframework.web.bind.annotation.${method}Mapping`);
this.mockRequestImports = this.usedMethods.map(method => `static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.${method.toLowerCase()}`);
// IntelliJ optimizes imports after a certain count
this.mockRequestImports = this.mockRequestImports.length > 3 ? ['static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*'] : this.mockRequestImports;
this.mainClass = this.getMainClassName();
this.controllerActions.forEach((action) => {
action.actionPath = _.kebabCase(action.actionName);
action.actionNameUF = _.upperFirst(action.actionName);
this.log(chalk.green(`adding ${action.actionMethod} action '${action.actionName}' for /api/${this.apiPrefix}/${action.actionPath}`));
});
this.template(
`${this.fetchFromInstalledJHipster('spring-controller/templates')}/${SERVER_MAIN_SRC_DIR}package/web/rest/Resource.java.ejs`,
`${SERVER_MAIN_SRC_DIR}${this.packageFolder}/web/rest/${this.controllerClass}.java`
);
this.template(
`${this.fetchFromInstalledJHipster('spring-controller/templates')}/${SERVER_TEST_SRC_DIR}package/web/rest/ResourceIntTest.java.ejs`,
`${SERVER_TEST_SRC_DIR}${this.packageFolder}/web/rest/${this.controllerClass}IntTest.java`
);
}
};
}
get writing() {
if (useBlueprint) return;
return this._writing();
}
};
| robertmilowski/generator-jhipster | generators/spring-controller/index.js | JavaScript | apache-2.0 | 6,433 |
/* global L, leafLet, emp */
leafLet.internalPrivateClass.AirspaceTrackEditor = function()
{
var publicInterface = {
initialize: function (args)
{
//var oOptions = {
//};
//L.Util.setOptions(this, oOptions);
leafLet.editor.Airspace.prototype.initialize.call(this, args);
},
_addWidthCP: function()
{
var oCP;
var oMidCoord;
var iIndex;
var cAirspaceAttribute = leafLet.typeLibrary.AirspaceAttribute;
var oCoordList = this.getCoordinateList();
var oFeature = this.getFeature();
if (oCoordList.length === 0)
{
return;
}
if (oCoordList.length >= oFeature.getMinPoints())
{
var Pt1;
var Pt2;
var dBearing;
var dDist;
var oAttributes;
var dLeftWidth;
var dRightWidth;
var oNewCoord;
for (iIndex = 1; iIndex < oCoordList.length; iIndex++)
{
oAttributes = oFeature.getAttributes(iIndex - 1);
dLeftWidth = oAttributes.getValue(cAirspaceAttribute.AIRSPACE_LEFT_WIDTH);
dRightWidth = oAttributes.getValue(cAirspaceAttribute.AIRSPACE_RIGHT_WIDTH);
Pt1 = oCoordList[iIndex - 1];
Pt2 = oCoordList[iIndex];
dBearing = Pt1.bearingTo(Pt2);
oMidCoord = Pt1.pointAt3QtrDistanceTo(Pt2);
oNewCoord = oMidCoord.destinationPoint((dBearing + 270.0) % 360, dLeftWidth);
oCP = new leafLet.editor.ControlPoint(oFeature,
leafLet.ControlPoint.Type.LEFT_WIDTH_CP,
oNewCoord, iIndex - 1, iIndex, dLeftWidth);
this.addControlPoint(oCP);
oNewCoord = oMidCoord.destinationPoint((dBearing + 90.0) % 360, dRightWidth);
oCP = new leafLet.editor.ControlPoint(oFeature,
leafLet.ControlPoint.Type.RIGHT_WIDTH_CP,
oNewCoord, iIndex - 1, iIndex, dRightWidth);
this.addControlPoint(oCP);
}
}
},
_addNewCP: function()
{
var oCP;
var oNewCoord;
var iIndex;
var oCoordList = this.getCoordinateList();
var oFeature = this.getFeature();
if (oCoordList.length === 0)
{
return;
}
if (oCoordList.length >= oFeature.getMinPoints())
{
for (iIndex = 1; iIndex < oCoordList.length; iIndex++)
{
// Lets add the new CP.
oNewCoord = oCoordList[iIndex - 1].midPointTo(oCoordList[iIndex]);
oCP = new leafLet.editor.ControlPoint(oFeature,
leafLet.ControlPoint.Type.NEW_POSITION_CP,
oNewCoord, iIndex, 0);
this.addControlPoint(oCP);
}
}
},
assembleControlPoints: function()
{
var oCP;
var oCoordList = this.getCoordinateList();
var oFeature = this.getFeature();
if (oCoordList.length === 0)
{
return;
}
for (var iIndex = 0; iIndex < oCoordList.length; iIndex++)
{
oCP = new leafLet.editor.ControlPoint(oFeature,
leafLet.ControlPoint.Type.POSITION_CP,
oCoordList[iIndex], iIndex, 0);
this.addControlPoint(oCP);
}
if (oCoordList.length >= oFeature.getMinPoints())
{
this.removeAllCPByType(leafLet.ControlPoint.Type.LEFT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.RIGHT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.NEW_POSITION_CP);
this._addWidthCP();
this._addNewCP();
}
},
doAddControlPoint: function(oLatLng)
{
var oCoordList = this.getCoordinateList();
var oFeature = this.getFeature();
var oAttributeList = oFeature.getAttributeList();
var oAttributes;
var iIndex = oCoordList.length;
if (oCoordList.length >= oFeature.getMaxPoints())
{
return undefined;
}
oCoordList.push(oLatLng);
this.setCoordinates(oCoordList);
var oCP = new leafLet.editor.ControlPoint(oFeature,
leafLet.ControlPoint.Type.POSITION_CP,
oLatLng, iIndex, 0);
if (oCoordList.length >= oFeature.getMinPoints())
{
oAttributes = oAttributeList.get(iIndex - 1);
if (!oAttributes)
{
if (iIndex === 1)
{
oAttributes = new leafLet.typeLibrary.airspace.Attributes(oFeature.getProperties(), {});
oAttributes.setRequiredAttributes(emp.typeLibrary.airspaceSymbolCode.SHAPE3D_TRACK);
}
else
{
oAttributes = oAttributeList.get(iIndex - 2);
oAttributes = oAttributes.duplicateAttribute();
}
oAttributeList.add(oAttributes);
}
if (this.updateLeafletObject(oCoordList))
{
this.removeAllCPByType(leafLet.ControlPoint.Type.LEFT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.RIGHT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.NEW_POSITION_CP);
this._addWidthCP();
this._addNewCP();
}
}
return oCP;
},
doDeleteControlPoint: function(oCP)
{
var oCoordList = this.getCoordinateList();
var oFeature = this.getFeature();
var iIndex = oCP.getIndex();
var oAttributeList = oFeature.getAttributeList();
if (oCP.getType() !== leafLet.ControlPoint.Type.POSITION_CP)
{
return false;
}
if (oCoordList.length >= oFeature.getMinPoints())
{
oCoordList.splice(iIndex, 1);
this.setCoordinates(oCoordList);
if (iIndex === oAttributeList.length() - 1)
{
oAttributeList.remove(iIndex - 1);
}
else
{
oAttributeList.remove(iIndex);
}
if (this.updateLeafletObject(oCoordList))
{
this.removeAllCPByType(leafLet.ControlPoint.Type.LEFT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.RIGHT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.NEW_POSITION_CP);
this._addWidthCP();
this._addNewCP();
}
return true;
}
return false;
},
doControlPointMoved: function(oCP, oEvent)
{
var oAttributes;
var oNewCoord;
var iIndex = oCP.getIndex();
var iIndex2 = oCP.getSubIndex();
var oCoordList = this.getCoordinateList();
var cAirspaceAttribute = leafLet.typeLibrary.AirspaceAttribute;
var oFeature = this.getFeature();
var oAttributeList = oFeature.getAttributeList();
switch (oCP.getType())
{
case leafLet.ControlPoint.Type.LEFT_WIDTH_CP:
case leafLet.ControlPoint.Type.RIGHT_WIDTH_CP:
var dWidth;
var Pt1 = oCoordList[iIndex];
var Pt2 = oCoordList[iIndex2];
var dBearing = Pt1.bearingTo(Pt2);
var dDist;
var oMidCoord = Pt1.pointAt3QtrDistanceTo(Pt2);
var oCPPos = oCP.getPosition();
var dMouseBearing = oMidCoord.bearingTo(oEvent.latlng);
oAttributes = oFeature.getAttributes(iIndex);
dBearing = oMidCoord.bearingTo(oCPPos);
dDist = oMidCoord.distanceTo(oEvent.latlng);
var dDelatAngle = Math.abs(dMouseBearing - dBearing);
dDist = Math.round(Math.abs(dDist * Math.cos(dDelatAngle.toRad())));
oNewCoord = oMidCoord.destinationPoint(dBearing, dDist);
dWidth = dDist;
oCP.setCPPosition(oNewCoord);
oCP.setValue(dWidth);
if (oCP.getType() === leafLet.ControlPoint.Type.LEFT_WIDTH_CP)
{
oAttributes.setValue(cAirspaceAttribute.AIRSPACE_LEFT_WIDTH, dWidth);
}
else
{
oAttributes.setValue(cAirspaceAttribute.AIRSPACE_RIGHT_WIDTH, dWidth);
}
this.setCoordinates(oCoordList);
this.removeAllCPByType(leafLet.ControlPoint.Type.NEW_POSITION_CP);
this.updateLeafletObject(oCoordList);
this._addNewCP();
return [];
case leafLet.ControlPoint.Type.NEW_POSITION_CP:
// We need to convert the new control point to a position control point
// and add new control points before and after it.
// We need to add the coordiante to our list in the correct position.
this.removeAllCPByType(leafLet.ControlPoint.Type.LEFT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.RIGHT_WIDTH_CP);
this.updateCPIndex(iIndex, 1);
oCoordList.splice(iIndex, 0, oEvent.latlng);
this.setCoordinates(oCoordList);
oCP.setCPPosition(oEvent.latlng);
oCP.setType(leafLet.ControlPoint.Type.POSITION_CP);
// We need to add a set of attributes for the new segment.
oAttributes = oFeature.getAttributes(iIndex - 1);
oAttributes = oAttributes.duplicateAttribute();
oAttributeList.insert(iIndex, oAttributes);
this.updateLeafletObject(oCoordList);
this._addWidthCP();
this._issueCPAddEvent(iIndex);
break;
case leafLet.ControlPoint.Type.POSITION_CP:
// We need to update the position of the control point
// and the new control points beore and after it..
oCoordList[iIndex].lat = oEvent.latlng.lat;
oCoordList[iIndex].lng = oEvent.latlng.lng;
this.setCoordinates(oCoordList);
oCP.setCPPosition(oCoordList[iIndex]);
this.removeAllCPByType(leafLet.ControlPoint.Type.LEFT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.RIGHT_WIDTH_CP);
this.removeAllCPByType(leafLet.ControlPoint.Type.NEW_POSITION_CP);
this.updateLeafletObject(oCoordList);
this._addNewCP();
this._addWidthCP();
return [iIndex];
}
return undefined;
}
};
return publicInterface;
};
leafLet.editor.AirspaceTrack = leafLet.editor.Airspace.extend(leafLet.internalPrivateClass.AirspaceTrackEditor());
| missioncommand/emp3-web | src/mapengine/leaflet/js/editor/airspace/leaflet-eng.editor.airspace.track.js | JavaScript | apache-2.0 | 12,438 |
/*
* Copyright 2013 BlackBerry Ltd.
*
* 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.
*/
var root = __dirname + "/../../",
fs = require("fs"),
cp = require("child_process"),
plugin = require(root + "routes/plugin"),
mockResponse = {
send: jasmine.createSpy()
};
describe("plugin", function () {
beforeEach(function () {
spyOn(console, "log");
});
afterEach(function () {
mockResponse.send.reset();
});
it("calls webworks-cli plugin", function () {
spyOn(fs, "existsSync").andReturn(true);
spyOn(cp, "exec").andCallFake(function (execStr, options, callback) {
callback(undefined, "", "");
});
plugin.get({
query: {
path: "hellow1",
cmd: "add",
args: "com.blackberry.app"
}
}, mockResponse);
expect(fs.existsSync).toHaveBeenCalled();
expect(cp.exec).toHaveBeenCalled();
expect(cp.exec.mostRecentCall.args[0]).toMatch(/".*webworks"\splugin\sadd\scom.blackberry.app/);
expect(mockResponse.send).toHaveBeenCalledWith(200, {
success: true,
code: 0,
path: "hellow1",
cmd: "add",
args: "com.blackberry.app",
stdout: "",
stderr: ""
});
});
});
| blackberry/webworks-gui | test/unit/plugin.spec.js | JavaScript | apache-2.0 | 1,864 |
module.exports={A:{A:{"2":"H E G D A B qB"},B:{"1":"EB M","2":"9 C N I J K L"},C:{"2":"0 1 2 3 4 5 6 7 8 9 nB SB F q H E G D A B C N I J K L g R o S T U V W X Y Z a b c d e f CB h i j k l m n Q p O r s t u v w x y z FB HB DB AB IB JB KB LB MB NB OB PB QB gB fB"},D:{"1":"NB OB PB QB eB EB M ZB WB wB XB","2":"0 1 2 3 4 5 6 7 8 9 F q H E G D A B C N I J K L g R o S T U V W X Y Z a b c d e f CB h i j k l m n Q p O r s t u v w x y z FB HB DB AB IB JB KB LB MB"},E:{"2":"F q H E G D A B C N YB UB aB bB cB dB TB P BB hB iB"},F:{"1":"4 5 6 7 8","2":"0 1 2 3 D B C I J K L g R o S T U V W X Y Z a b c d e f CB h i j k l m n Q p O r s t u v w x y z jB kB lB mB P RB oB BB"},G:{"2":"G UB pB GB rB sB tB uB vB VB xB yB zB 0B 1B 2B 3B 4B 5B 6B"},H:{"2":"7B"},I:{"1":"M","2":"SB F 8B 9B AC BC GB CC DC"},J:{"2":"E A"},K:{"2":"A B C O P RB BB"},L:{"1":"M"},M:{"2":"AB"},N:{"2":"A B"},O:{"2":"EC"},P:{"1":"P","2":"F FC GC HC IC JC TB"},Q:{"2":"KC"},R:{"2":"LC"},S:{"2":"MC"}},B:7,C:"IntersectionObserver V2"};
| BigBoss424/portfolio | v8/development/node_modules/caniuse-lite/data/features/intersectionobserver-v2.js | JavaScript | apache-2.0 | 999 |
/**
* Copyright 2014-2015 IBM Corp. 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.
*/
/* global document */
'use strict';
const SunburstWidget = require('./widget');
class PersonalitySunburstChartImpl {
constructor(options, D3PersonalityProfile, ChartRenderer, PersonalityTraitNames) {
this.D3PersonalityProfile = D3PersonalityProfile;
this.ChartRenderer = ChartRenderer;
this._options = options;
this._selector = options.selector;
this._element = options.element;
this._locale = options.locale;
this._colors = options.colors;
this._imageUrl = '';
this._profile = null;
this._widget = null;
this._traitNames = new PersonalityTraitNames({ locale: this._locale });
}
setLocale(locale, render = true) {
if (this._locale !== locale) {
this._locale = locale;
this._traitNames.setLocale(locale);
if (this._profile && this._widget) {
const d3Profile = new this.D3PersonalityProfile(this._profile, this._traitNames);
this._widget.setData(d3Profile.d3Json());
if (render) {
this._widget.updateText();
}
}
}
}
setImage(url, render = true) {
if (this._imageUrl !== url) {
this._imageUrl = url;
if (this._widget && render) {
this._widget.changeImage(url);
}
}
}
setProfile(profile, render = true) {
if (this._profile !== profile) {
this._profile = profile;
if (this._widget) {
if (this._profile) {
const d3Profile = new this.D3PersonalityProfile(this._profile, this._traitNames);
this._widget.setData(d3Profile.d3Json());
} else {
this._widget.clearData();
}
}
} else if (this._widget && this._profile && !this._widget.hasData()) {
// initilize data
const d3Profile = new this.D3PersonalityProfile(this._profile, this._traitNames);
this._widget.setData(d3Profile.d3Json());
}
if (render) {
this.render();
}
}
setColors(colors, render = true) {
if (!colors) {
return;
}
this._colors = colors;
if (this._widget) {
this._widget.setColors(this._colors);
if (render) {
this._widget.updateColors();
}
}
}
render() {
if (this._widget) {
this._widget.init();
// Render widget
this._widget.render();
this._widget.updateText();
this._widget.updateColors();
// Expand all sectors of the sunburst chart - sectors at each level can be hidden
this._widget.expandAll();
// Add an image of the person for whom the profile was generated
if (this._imageUrl) {
this._widget.addImage(this._imageUrl);
}
} else {
this.show();
}
}
/**
* Renders the sunburst visualization. The parameter is the tree as returned
* from the Personality Insights JSON API.
* It uses the arguments widgetId, widgetWidth, widgetHeight and personImageUrl
* declared on top of this script.
*/
show(theProfile, personImageUrl, colors) {
if (!this._widget) {
// Create widget
this._widget = new SunburstWidget(this._options, this.ChartRenderer);
const element = this._element || document.querySelector(this._selector);
this._widget.setElement(element);
}
// Clear DOM element that will display the sunburst chart
this._widget.clear();
this.setProfile(theProfile || this._profile, false);
this.setImage(personImageUrl || this._imageUrl, false);
this.setColors(colors || this._colors, false);
// Render widget
this.render();
}
}
module.exports = PersonalitySunburstChartImpl;
| personality-insights/sunburst-chart | src/personality-sunburst-chart.js | JavaScript | apache-2.0 | 4,179 |
/*
* 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.
*/
//改造窗体的层次
Ext.override(Ext.ZIndexManager, {
tempHidden : [],
show : function() {
var comp, x, y;
while (comp = this.tempHidden.shift()) {
x = comp.x;
y = comp.y;
comp.show();
comp.setPosition(x, y);
}
}
});
Ext.Loader.setConfig({
enabled : true,
paths : {
'Ext.ux' : 'resources/resources/extjs/ux',
'Wdesktop':'resources/desktop'
}
});
Ext.require([ 'Wdesktop.desktop.system.App']);
var myDesktopApp;
if(!returnCitySN){
var returnCitySN = {
'cip' : '10.28.20.100',
'cname' : '江西省赣州市'
};
}
var wmsmodulx = [], wmsmoduly = [];
var startLoadingTime = new Date().getTime();
Ext.onReady(function() {
Ext.MessageBox.show({
title : "正在加载桌面, 请稍候...",
msg: "<br/>加载系统基础组件....",
progressText: "20%",
width:300,
progress:true,
closable:false,
icon:"ext-mb-download"
});
Ext.MessageBox.updateProgress(0.2);
myDesktopApp = new Wdesktop.desktop.system.App();
window.setTimeout(function(){
Ext.MessageBox.hide();
},1000);
});
| kuainiao/MultimediaDesktop | Client/src/main/webapp/resources/desktop/loader.js | JavaScript | apache-2.0 | 1,649 |
(function (pageMenuController) {
'use strict';
var Promise = require('bluebird'),
navigationMenuConfigs = require("../../configs/page-menu.config");
pageMenuController.init = function (app) {
pageMenuController.getNavigationMenus = function () {
return Promise.resolve(navigationMenuConfigs.getNavigationMenus(app));
};
};
})(module.exports); | avsek477/blogSite | lib/controllers/view-controller/page-navigation-menus.controller.js | JavaScript | apache-2.0 | 396 |
var $ = require('jquery');
var m = require('mithril');
function Panel(title, header, inner, args, selected) {
panel = m.component(Panel, title, header, inner, args);
panel.title = title;
panel.selected = selected || false;
return panel;
}
Panel.controller = function(title, header, inner, args) {
var self = this;
self.title = title;
self.header = header === null ? null : header || title;
self.inner = m.component.apply(self, [inner].concat(args || []));
};
Panel.view = function(ctrl) {
return m('#' + ctrl.title.toLowerCase() + 'Panel', [
!ctrl.header ? '' :
m('.osf-panel-header', $.isFunction(ctrl.header) ? ctrl.header() : ctrl.header),
m('', ctrl.inner)
]);
};
var Spinner = m.component({
controller: function(){},
view: function() {
return m('.fangorn-loading', [
m('.logo-spin.text-center', [
m('img[src=/static/img/logo_spin.png][alt=loader]')
]),
m('p.m-t-sm.fg-load-message', ' Loading... ')
]);
}
});
module.exports = {
Panel: Panel,
Spinner: Spinner,
};
| jinluyuan/osf.io | website/static/js/filepage/util.js | JavaScript | apache-2.0 | 1,134 |
/**
* Copyright © 2013 Environmental Systems Research Institute, Inc. (Esri)
*
* 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<br>
*
* 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.
*/
define(["cmwapi/Channels", "cmwapi/map/feature/Plot", "cmwapi/map/Error", "cmwapi/Validator",
"test/mock/OWF", "test/mock/Ozone"],
function(Channels, Plot, Error, Validator, OWF, Ozone) {
describe(Channels.MAP_FEATURE_PLOT + " module", function() {
var INSTANCE_ID = OWF.getInstanceId();
beforeEach(function() {
// Mock the necessary OWF methods and attach them to the window.
// OWF should be in global scope when other libraries attempt to
// access it.
window.OWF = OWF;
window.Ozone = Ozone;
});
afterEach(function() {
// Remove our mock objects from the window so neither they nor
// any spies upon them hang around for other test suites.
delete window.OWF;
delete window.Ozone;
});
it("sends data to the correct channel", function() {
var eventing = OWF.Eventing;
expect(eventing).not.toBe(null);
spyOn(Plot, 'send').andCallThrough();
spyOn(eventing, 'publish').andCallThrough();
spyOn(Error, 'send');
Plot.send({featureId:"myFeatureId", feature: "some kml data"});
expect(Plot.send).toHaveBeenCalled();
// expect publish to be called
expect(eventing.publish).toHaveBeenCalled();
var payload = Ozone.util.parseJson(eventing.publish.mostRecentCall.args[1]);
expect(eventing.publish.mostRecentCall.args[0]).toEqual(Channels.MAP_FEATURE_PLOT);
expect(payload.overlayId).toEqual(INSTANCE_ID);
expect(payload.featureId).toEqual("myFeatureId");
expect(payload.feature).toEqual("some kml data");
expect(payload.name).toBe(undefined);
expect(payload.format).toEqual("kml");
expect(payload.zoom).toBe(false);
// don't expect error to be called
expect(Error.send.calls.length).toEqual(0);
});
it("fails data missing a feature id", function() {
var eventing = OWF.Eventing;
expect(eventing).not.toBe(null);
spyOn(Plot, 'send').andCallThrough();
spyOn(eventing, 'publish');
spyOn(Error, 'send').andCallThrough();
Plot.send({feature: "some kml data"});
expect(Plot.send).toHaveBeenCalled();
// expect publish to be called on the error channel.
expect(eventing.publish).toHaveBeenCalled();
expect(eventing.publish.mostRecentCall.args[0]).toEqual(Channels.MAP_ERROR);
expect(Error.send.calls.length).toEqual(1);
});
it("fails data missing a feature", function() {
var eventing = OWF.Eventing;
expect(eventing).not.toBe(null);
spyOn(Plot, 'send').andCallThrough();
spyOn(eventing, 'publish');
spyOn(Error, 'send').andCallThrough();
Plot.send({featureId: "myFeatureId"});
expect(Plot.send).toHaveBeenCalled();
// expect publish to be called on the error channel.
expect(eventing.publish).toHaveBeenCalled();
expect(eventing.publish.mostRecentCall.args[0]).toEqual(Channels.MAP_ERROR);
expect(Error.send.calls.length).toEqual(1);
});
it("unsubscribes the correct channel when removeHandlers is called", function() {
var eventing = OWF.Eventing;
spyOn(Plot, 'removeHandlers').andCallThrough();
spyOn(Error, 'send');
spyOn(eventing, 'unsubscribe');
Plot.removeHandlers();
expect(Plot.removeHandlers).toHaveBeenCalled();
expect(eventing.unsubscribe.mostRecentCall.args[0]).toEqual(Channels.MAP_FEATURE_PLOT);
expect(Error.send.calls.length).toEqual(0);
});
it("wraps added handlers and passes along any optional elements; missing overlayId, zoom and format are filled in", function() {
var eventing = OWF.Eventing;
spyOn(eventing, 'subscribe');
var testHandler = jasmine.createSpy('testHandler');
var newHandler = Plot.addHandler(testHandler);
expect(eventing.subscribe.mostRecentCall.args[0]).toEqual(Channels.MAP_FEATURE_PLOT);
// Test the behavior for newHandler Plot a sender an empty payload to pass along
// Our code should fill in the payload and pass it along to the testHandler.
var jsonVal = {
featureId: "myFeatureId",
feature: "some kml data",
name: "myName"
};
var sender = {
id: INSTANCE_ID
};
// Spy on Error and call our wrapper handler.
spyOn(Error, 'send');
newHandler(Ozone.util.toString(sender), jsonVal);
// We don't expect error to be called
expect(Error.send.calls.length).toEqual(0);
// We DO expect testHandler to have been called and the missing jsonVal items to have been
// filled in.
expect(testHandler.calls.length).toEqual(1);
expect(testHandler.mostRecentCall.args[1].overlayId).toEqual(INSTANCE_ID);
expect(testHandler.mostRecentCall.args[1].featureId).toEqual("myFeatureId");
expect(testHandler.mostRecentCall.args[1].feature).toEqual("some kml data");
expect(testHandler.mostRecentCall.args[1].name).toEqual("myName");
expect(testHandler.mostRecentCall.args[1].format).toEqual("kml");
expect(testHandler.mostRecentCall.args[1].zoom).toBe(false);
});
it("passes object arrays to added handlers", function() {
var eventing = OWF.Eventing;
spyOn(eventing, 'subscribe');
var testHandler = jasmine.createSpy('testHandler');
var newHandler = Plot.addHandler(testHandler);
expect(eventing.subscribe.mostRecentCall.args[0]).toEqual(Channels.MAP_FEATURE_PLOT);
// Test the behavior for newHandler Create a sender an empty payload to pass along
// Our code should fill in the payload and pass it along to the testHandler.
var jsonVal = [{
featureId: "myFeatureId1",
feature: "some kml data.1"
},{
overlayId: "myOverlayId2",
featureId: "myFeatureId2",
feature: "some kml data.2",
name: "myName",
format: "wms",
zoom: true
}];
var sender = {
id: INSTANCE_ID
};
// Spy on Error and call our wrapper handler.
spyOn(Error, 'send');
newHandler(Ozone.util.toString(sender), jsonVal);
// We don't expect error to be called
expect(Error.send.calls.length).toEqual(0);
// We DO expect testHandler to have been called and the jsonVal values to
// carry through unchanged. Any missing elements with defaults should be filled in.
expect(testHandler.calls.length).toEqual(1);
expect(testHandler.mostRecentCall.args[1].length).toEqual(2);
expect(testHandler.mostRecentCall.args[1][0].overlayId).toEqual(INSTANCE_ID);
expect(testHandler.mostRecentCall.args[1][0].featureId).toEqual("myFeatureId1");
expect(testHandler.mostRecentCall.args[1][0].feature).toEqual("some kml data.1");
expect(testHandler.mostRecentCall.args[1][0].name).toBe(undefined);
expect(testHandler.mostRecentCall.args[1][0].format).toEqual("kml");
expect(testHandler.mostRecentCall.args[1][0].zoom).toBe(false);
expect(testHandler.mostRecentCall.args[1][1].overlayId).toEqual("myOverlayId2");
expect(testHandler.mostRecentCall.args[1][1].featureId).toEqual("myFeatureId2");
expect(testHandler.mostRecentCall.args[1][1].feature).toEqual("some kml data.2");
expect(testHandler.mostRecentCall.args[1][1].name).toEqual("myName");
expect(testHandler.mostRecentCall.args[1][1].format).toEqual("wms");
expect(testHandler.mostRecentCall.args[1][1].zoom).toBe(true);
});
});
});
| aconyteds/Esri-Ozone-Map-Widget | test/spec/cmwapi/map/feature/Plot.spec.js | JavaScript | apache-2.0 | 9,001 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* @class
* Initializes a new instance of the ServiceGroupDescription class.
* @constructor
* The description of the service group
*
* @member {string} [applicationName]
*
* @member {string} [serviceName]
*
* @member {string} [serviceTypeName]
*
* @member {object} [partitionDescription]
*
* @member {string} [partitionDescription.partitionScheme] Possible values
* include: 'Invalid', 'Singleton', 'UniformInt64', 'Named'
*
* @member {number} [partitionDescription.count]
*
* @member {array} [partitionDescription.names]
*
* @member {string} [partitionDescription.lowKey]
*
* @member {string} [partitionDescription.highKey]
*
* @member {string} [placementConstraints]
*
* @member {object} [correlationScheme]
*
* @member {string} [correlationScheme.serviceName]
*
* @member {string} [correlationScheme.serviceCorrelationScheme] Possible
* values include: 'Invalid', 'Affinity', 'AlignedAffinity',
* 'NonAlignedAffinity'
*
* @member {object} [serviceLoadMetrics]
*
* @member {string} [serviceLoadMetrics.serviceName]
*
* @member {string} [serviceLoadMetrics.serviceCorrelationScheme] Possible
* values include: 'Invalid', 'Affinity', 'AlignedAffinity',
* 'NonAlignedAffinity'
*
* @member {object} [servicePlacementPolicies]
*
* @member {string} [servicePlacementPolicies.serviceName]
*
* @member {string} [servicePlacementPolicies.serviceCorrelationScheme]
* Possible values include: 'Invalid', 'Affinity', 'AlignedAffinity',
* 'NonAlignedAffinity'
*
* @member {number} [flags]
*
* @member {array} [serviceGroupMemberDescription]
*
* @member {string} serviceKind Polymorphic Discriminator
*
*/
class ServiceGroupDescription {
constructor() {
}
/**
* Defines the metadata of ServiceGroupDescription
*
* @returns {object} metadata of ServiceGroupDescription
*
*/
mapper() {
return {
required: false,
serializedName: 'ServiceGroupDescription',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'ServiceKind',
clientName: 'serviceKind'
},
uberParent: 'ServiceGroupDescription',
className: 'ServiceGroupDescription',
modelProperties: {
applicationName: {
required: false,
serializedName: 'ApplicationName',
type: {
name: 'String'
}
},
serviceName: {
required: false,
serializedName: 'ServiceName',
type: {
name: 'String'
}
},
serviceTypeName: {
required: false,
serializedName: 'ServiceTypeName',
type: {
name: 'String'
}
},
partitionDescription: {
required: false,
serializedName: 'PartitionDescription',
type: {
name: 'Composite',
className: 'PartitionDescription'
}
},
placementConstraints: {
required: false,
serializedName: 'PlacementConstraints',
type: {
name: 'String'
}
},
correlationScheme: {
required: false,
serializedName: 'CorrelationScheme',
type: {
name: 'Composite',
className: 'ServiceCorrelationDescription'
}
},
serviceLoadMetrics: {
required: false,
serializedName: 'ServiceLoadMetrics',
type: {
name: 'Composite',
className: 'ServiceCorrelationDescription'
}
},
servicePlacementPolicies: {
required: false,
serializedName: 'ServicePlacementPolicies',
type: {
name: 'Composite',
className: 'ServiceCorrelationDescription'
}
},
flags: {
required: false,
serializedName: 'Flags',
type: {
name: 'Number'
}
},
serviceGroupMemberDescription: {
required: false,
serializedName: 'ServiceGroupMemberDescription',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ServiceGroupMemberDescriptionElementType',
type: {
name: 'Composite',
className: 'ServiceGroupMemberDescription'
}
}
}
},
serviceKind: {
required: true,
serializedName: 'ServiceKind',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ServiceGroupDescription;
| begoldsm/azure-sdk-for-node | lib/services/serviceFabric/lib/models/serviceGroupDescription.js | JavaScript | apache-2.0 | 5,239 |
/**
* Copyright 2019 The AMP HTML 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.
*/
'use strict';
const argv = require('minimist')(process.argv.slice(2));
const {
doBuildExtension,
maybeInitializeExtensions,
getExtensionsToBuild,
} = require('../tasks/extension-helpers');
const {doBuildJs, compileCoreRuntime} = require('../tasks/helpers');
const {jsBundles} = require('../compile/bundles.config');
const extensionBundles = {};
maybeInitializeExtensions(extensionBundles, /* includeLatest */ true);
/**
* Gets the unminified name of the bundle if it can be lazily built.
*
* @param {!Object} bundles
* @param {string} name
* @return {string}
*/
function maybeGetUnminifiedName(bundles, name) {
if (argv.compiled) {
for (const key of Object.keys(bundles)) {
if (
key == name ||
(bundles[key].options && bundles[key].options.minifiedName == name)
) {
return key;
}
}
}
return name;
}
/**
* Checks for a previously triggered build for a bundle, and triggers one if
* required.
*
* @param {string} url
* @param {string|RegExp} matcher
* @param {!Object} bundles
* @param {function(!Object, string, ?Object):Promise} buildFunc
* @param {function(): void} next
*/
async function lazyBuild(url, matcher, bundles, buildFunc, next) {
const match = url.match(matcher);
if (match && match.length == 2) {
const name = maybeGetUnminifiedName(bundles, match[1]);
const bundle = bundles[name];
if (bundle) {
await build(bundles, name, buildFunc);
}
}
next();
}
/**
* Actually build a JS file or extension. Only will allow one build per
* bundle at a time.
*
* @param {!Object} bundles
* @param {string} name
* @param {function(!Object, string, ?Object):Promise} buildFunc
* @return {Promise<void>}
*/
async function build(bundles, name, buildFunc) {
const bundle = bundles[name];
if (bundle.pendingBuild) {
return await bundle.pendingBuild;
}
if (bundle.watched) {
return;
}
bundle.watched = true;
bundle.pendingBuild = buildFunc(bundles, name, {
watch: true,
minify: argv.compiled,
onWatchBuild: async (bundlePromise) => {
bundle.pendingBuild = bundlePromise;
await bundlePromise;
bundle.pendingBuild = undefined;
},
});
await bundle.pendingBuild;
bundle.pendingBuild = undefined;
}
/**
* Lazy builds the correct version of an extension when requested.
*
* @param {!Object} req
* @param {!Object} _res
* @param {function(): void} next
*/
async function lazyBuildExtensions(req, _res, next) {
const matcher = argv.compiled
? /\/dist\/v0\/([^\/]*)\.js/ // '/dist/v0/*.js'
: /\/dist\/v0\/([^\/]*)\.max\.js/; // '/dist/v0/*.max.js'
await lazyBuild(req.url, matcher, extensionBundles, doBuildExtension, next);
}
/**
* Lazy builds a non-extension JS file when requested.
*
* @param {!Object} req
* @param {!Object} _res
* @param {function(): void} next
*/
async function lazyBuildJs(req, _res, next) {
const matcher = /\/.*\/([^\/]*\.js)/;
await lazyBuild(req.url, matcher, jsBundles, doBuildJs, next);
}
/**
* Pre-builds the core runtime and the JS files that it loads.
*/
async function preBuildRuntimeFiles() {
await build(jsBundles, 'amp.js', (_bundles, _name, options) =>
compileCoreRuntime(options)
);
await build(jsBundles, 'ww.max.js', doBuildJs);
}
/**
* Pre-builds default extensions and ones requested via command line flags.
*/
async function preBuildExtensions() {
const extensions = getExtensionsToBuild(/* preBuild */ true);
for (const extensionBundle in extensionBundles) {
const extension = extensionBundles[extensionBundle].name;
if (extensions.includes(extension) && !extensionBundle.endsWith('latest')) {
await build(extensionBundles, extensionBundle, doBuildExtension);
}
}
}
module.exports = {
lazyBuildExtensions,
lazyBuildJs,
preBuildExtensions,
preBuildRuntimeFiles,
};
| lannka/amphtml | build-system/server/lazy-build.js | JavaScript | apache-2.0 | 4,481 |
(function(tirequire,__dirname,__filename){module.id=__filename;module.loaded=false;module.filename=__filename;var require=tirequire("node_modules/ti-commonjs/lib/ti-commonjs")(__dirname,module);module.require=require;module.exports = function(grunt) {
grunt.registerTask("component", function() {
var config = JSON.parse(grunt.file.read("component.json"));
config.files = grunt.file.expand("lang/*.js");
config.files.unshift("moment.js");
grunt.file.write("component.json", JSON.stringify(config, true, 2));
});
};
module.loaded=true;})(require,"/node_modules/moment/tasks","/node_modules/moment/tasks/component.js"); | k0sukey/TiTodoMVC | Resources/iphone/node_modules/moment/tasks/component.js | JavaScript | apache-2.0 | 657 |
/*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxBulletChart extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['animationDuration','barSize','description','disabled','height','labelsFormat','labelsFormatFunction','orientation','pointer','rtl','ranges','showTooltip','target','ticks','title','tooltipFormatFunction','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxBulletChart(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxBulletChart('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxBulletChart(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
animationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('animationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('animationDuration');
}
};
barSize(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('barSize', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('barSize');
}
};
description(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('description', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('description');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('disabled');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('height', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('height');
}
};
labelsFormat(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('labelsFormat', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('labelsFormat');
}
};
labelsFormatFunction(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('labelsFormatFunction', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('labelsFormatFunction');
}
};
orientation(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('orientation', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('orientation');
}
};
pointer(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('pointer', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('pointer');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('rtl');
}
};
ranges(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('ranges', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('ranges');
}
};
showTooltip(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('showTooltip', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('showTooltip');
}
};
target(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('target', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('target');
}
};
ticks(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('ticks', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('ticks');
}
};
title(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('title', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('title');
}
};
tooltipFormatFunction(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('tooltipFormatFunction', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('tooltipFormatFunction');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('width', arg)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('width');
}
};
destroy() {
JQXLite(this.componentSelector).jqxBulletChart('destroy');
};
performRender() {
JQXLite(this.componentSelector).jqxBulletChart('render');
};
refresh() {
JQXLite(this.componentSelector).jqxBulletChart('refresh');
};
val(value) {
if (value !== undefined) {
JQXLite(this.componentSelector).jqxBulletChart('val', value)
} else {
return JQXLite(this.componentSelector).jqxBulletChart('val');
}
};
render() {
let id = 'jqxBulletChart' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
| liamray/nexl-js | frontend/jqwidgets/jqwidgets-react/react_jqxbulletchart.js | JavaScript | apache-2.0 | 7,386 |
import { errors } from 'arsenal';
import bucketShield from './apiUtils/bucket/bucketShield';
import { convertToXml } from './apiUtils/bucket/bucketWebsite';
import collectCorsHeaders from '../utilities/collectCorsHeaders';
import { isBucketAuthorized } from './apiUtils/authorization/aclChecks';
import metadata from '../metadata/wrapper';
import { pushMetric } from '../utapi/utilities';
const requestType = 'bucketOwnerAction';
/**
* Bucket Get Website - Get bucket website configuration
* @param {AuthInfo} authInfo - Instance of AuthInfo class with requester's info
* @param {object} request - http request object
* @param {object} log - Werelogs logger
* @param {function} callback - callback to server
* @return {undefined}
*/
export default function bucketGetWebsite(authInfo, request, log, callback) {
const bucketName = request.bucketName;
const canonicalID = authInfo.getCanonicalID();
metadata.getBucket(bucketName, log, (err, bucket) => {
if (err) {
log.debug('metadata getbucket failed', { error: err });
return callback(err);
}
if (bucketShield(bucket, requestType)) {
return callback(errors.NoSuchBucket);
}
log.trace('found bucket in metadata');
const corsHeaders = collectCorsHeaders(request.headers.origin,
request.method, bucket);
if (!isBucketAuthorized(bucket, requestType, canonicalID)) {
log.debug('access denied for user on bucket', {
requestType,
method: 'bucketGetWebsite',
});
return callback(errors.AccessDenied, null, corsHeaders);
}
const websiteConfig = bucket.getWebsiteConfiguration();
if (!websiteConfig) {
log.debug('bucket website configuration does not exist', {
method: 'bucketGetWebsite',
});
return callback(errors.NoSuchWebsiteConfiguration, null,
corsHeaders);
}
log.trace('converting website configuration to xml');
const xml = convertToXml(websiteConfig);
pushMetric('getBucketWebsite', log, {
authInfo,
bucket: bucketName,
});
return callback(null, xml, corsHeaders);
});
}
| lucisilv/Silviu_S3-Antidote | lib/api/bucketGetWebsite.js | JavaScript | apache-2.0 | 2,285 |
/*
* asf -- Ada Server Faces
* Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
* Written by Stephane Carrez ([email protected])
*
* 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.
*/
var ASF = {};
(function () {
/**
* Execute the AJAX response action represented by the JSON object <b>action</b>.
*
* @param node the current node
* @param action the JSON action object
*/
ASF.ExecuteOne = function(node, action) {
var id = action.id ? action.id : node;
if (action.child) {
id = $(id).children(action.child);
}
if (action.action === "update") {
$(id).html(action.data);
} else if (action.action === "prepend") {
$(id).prepend(action.data);
} else if (action.action === "append") {
$(id).append(action.data);
} else if (action.action === "show") {
$(id).show('slow');
} else if (action.action === "hide") {
$(id).hide('slow');
} else if (action.action === "delete") {
$(id).remove();
} else if (action.action === "removeClass") {
$(id).removeClass(action.data);
} else if (action.action === "addClass") {
$(id).addClass(action.data);
} else if (action.action === "fadeIn") {
$(id).fadeIn('slow');
} else if (action.action === "fadeOut") {
$(id).fadeOut('slow');
} else if (action.action === "slideUp") {
$(id).slideUp('slow');
} else if (action.action === "slideDown") {
$(id).slideDown('slow');
} else if (action.action === "closeDialog") {
$(id).dialog('close');
} else if (action.action === "closePopup") {
$(id).popup('close');
} else if (action.action === "redirect") {
document.location = action.url;
} else if (action.action === "message") {
ASF.Message(node, action.id, action.data);
} else if (action.action === "notification") {
ASF.Message(node, action.id, action.data, 'asf-notification').message('autoClose');
} else if (action.action === "script") {
try {
eval(action.script);
} catch (e) {
alert(e);
}
} else if (action.action === "clear") {
$(id).each(function() {
switch (this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
break;
}
});
}
};
ASF.Execute = function(node, data) {
if (data) {
for (var i = 0; i < data.length; i++) {
ASF.ExecuteOne(node, data[i]);
}
}
};
/**
* Handle an AJAX operation that failed.
*/
ASF.AjaxError = function(jqXHDR, status, error, node) {
var contentType = jqXHDR.getResponseHeader('Content-type');
if (contentType && contentType.match(/^application\/json(;.*)?$/i)) {
var data = $.parseJSON(jqXHDR.responseText);
ASF.Execute(node, data);
} else {
ASF.Message(node, null, "Operation failed");
}
};
/**
* Update the target container with the content of the AJAX GET request
* on the given URL. The target parameter is optional.
*
* @param node the current element
* @param url the URL to fetch using an HTTP GET
* @param target the optional target element
* @param complete an optional function called when the response is received
*/
ASF.Update = function(node, url, target, complete) {
/* Find the container to update */
var d;
if (target != null) {
d = $(target);
} else {
d = $(node);
if (!d.is('.asf-container')) {
d = d.parent('.asf-container');
}
}
if (d.length > 0) {
/* Perform the HTTP GET */
jQuery.ajax({
url: url,
context: document.body,
success: function(data, status, jqXHDR) {
var contentType = jqXHDR.getResponseHeader('Content-type');
if (contentType == null) {
contentType = "text/html";
}
if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
d.html(jqXHDR.responseText);
} else if (contentType.match(/^application\/json(;.*)?$/i)) {
ASF.Execute(d, data);
}
if (complete != null) {
complete(d, jqXHDR);
}
},
error: function(jqXHDR, status, error) {
ASF.AjaxError(jqXHDR, status, error, d);
}
});
}
};
/**
* Submit the current form. The <b>node</b> element refers to the element being clicked.
* From that element, we can identify the form to submit. The element to refresh upon
* the form submit is an outer element that should have the <b>asf-container</b> class.
* If not such element as parent node, the parent node of the form is used.
*
* After the form is submitted, the response is executed if it is a JSON response.
* If the response is an HTML content, the container element is refreshed with it.
*
* @param node the current element
* @param url the URL to fetch using an HTTP GET
* @param target the optional target element
*/
ASF.Submit = function(node) {
/* Find the form and container to update */
var f = $(node).closest("form");
var d = $(f);
if (!d.is('.asf-container,ui-dialog-content')) {
d = d.closest('.asf-container,.ui-dialog-content');
}
if (d.length == 0) {
d = $(f).parent();
}
if (d.length > 0) {
var params;
var params = $(f).serialize();
var url = $(f).attr('action');
if (node.tagName == 'a' || node.tagName == 'A') {
params = node.id + "=1&" + $(f).serialize();
} else {
params = node.name + "=1&" + $(f).serialize();
}
/**
* Send notification on form to indicate a form submit is now in progress.
*/
$(f).triggerHandler("notifySubmit", d);
/* Perform the HTTP POST */
jQuery.ajax({
type: "POST",
url: url,
data: params,
context: document.body,
success: function(data, status, jqXHDR) {
var contentType = jqXHDR.getResponseHeader('Content-type');
if (contentType == null) {
contentType = "text/html";
}
$(f).triggerHandler("successSubmit", d);
if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
d.fadeOut("fast", function() {
d.html(jqXHDR.responseText);
d.fadeIn("fast");
});
} else if (contentType.match(/^application\/json(;.*)?$/i)) {
ASF.Execute(d, data);
}
},
error: function(jqXHDR, status, error) {
ASF.AjaxError(jqXHDR, status, error, d);
}
});
}
return false;
};
/**
* Perform an HTTP POST on the given URL.
*
* @param node the node element that will be updated by default on the AJAX response.
* @param url the HTTP URL.
* @param params the HTTP POST parameters.
*/
ASF.Post = function(node, url, params) {
/* Perform the HTTP POST */
jQuery.ajax({
type: "POST",
url: url,
data: params,
context: document.body,
success: function(data, status, jqXHDR) {
var contentType = jqXHDR.getResponseHeader('Content-type');
if (contentType == null) {
contentType = "text/html";
}
if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
$(node).html(jqXHDR.responseText);
} else if (contentType.match(/^application\/json(;.*)?$/i)) {
ASF.Execute(node, data);
}
},
error: function(jqXHDR, status, error) {
ASF.AjaxError(jqXHDR, status, error, node);
}
});
return false;
};
/**
* Open a popup form attached to the node element and which is filled by
* the given URL.
*
* The popup form is created when the page refered by <tt>url</tt> is fetched.
* It can be referenced by the unique id given in <tt>id</tt>.
*
* @param node the node element where the popup is attached to.
* @param id the popup unique id.
* @param url the URL to fetch to fill the popup content.
* @param params the popup creation parameters.
*/
ASF.Popup = function(node, id, url, params) {
jQuery.ajax({
type: "GET",
url: url,
context: document.body,
success: function(data, status, jqXHDR) {
var contentType = jqXHDR.getResponseHeader('Content-type');
if (contentType == null) {
contentType = "text/html";
}
var div = $('#' + id);
if (div.length == 0) {
div = document.createElement("div");
div.id = id;
$(document.body).append($(div));
}
if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
$(div).html(jqXHDR.responseText);
} else if (contentType.match(/^application\/json(;.*)?$/i)) {
ASF.Execute(div, data);
}
$(div).popup(params).popup('open');
$(div).find('form:not(.filter) :input:visible:first').focus();
},
error: function(jqXHDR, status, error) {
ASF.AjaxError(jqXHDR, status, error, node);
}
});
return false;
};
/**
* Open a dialog box and fetch the dialog content from the given URI.
*
* @param node the current element
* @param id the dialog id
* @param url the URL to fetch using an HTTP GET
* @param params the optional dialog options
*/
ASF.OpenDialog = function(node, id, url, params) {
var div = $(id);
if (div.length > 0) {
return false;
}
div = document.createElement("div");
div.id = id;
div = $(div);
var d = $(document);
if (d.length == 0) {
return false;
}
$(d).append($(div));
/* Perform the HTTP GET */
jQuery.ajax({
url: url,
context: document.body,
success: function(data, status, jqXHDR) {
var contentType = jqXHDR.getResponseHeader('Content-type');
if (contentType == null) {
contentType = "text/html";
}
if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
$(div).dialog({
autoOpen: false,
show: "blind",
hide: "explode",
minWidth: 600,
close: function() {
$(div).dialog('destroy');
$(div).remove();
if (params && params.close) {
params.close(node);
}
}
});
$(div).html(jqXHDR.responseText);
/**
* Extract a title from the inner form to setup the dialog box.
*/
var dTitle, dBox = $(div).children('div');
if (dBox.length == 0) {
dTitle = $(div).children('h2');
} else {
dTitle = $(dBox).children('h2');
}
if (dTitle.length > 0) {
$(div).dialog("option", "title", dTitle.html());
dTitle.remove();
} else {
dTitle = $(div).children('div').attr('title');
if (dTitle != null) {
$(div).dialog("option", "title", dTitle );
/* $(div).attr('title', title); */
}
}
$(div).dialog('open');
} else if (contentType.match(/^application\/json(;.*)?$/i)) {
ASF.Execute(node, data);
}
},
error: function(jqXHDR, status, error) {
ASF.AjaxError(jqXHDR, status, error, d);
}
});
return false;
};
/**
* Close the dialog box identified by the given identifier.
*
* @param id the dialog box identifier
*/
ASF.CloseDialog = function(id) {
$('#' + id).dialog('close');
return false;
};
/**
* Create and display a popup message near the node element.
*
* @param node the element giving the location of the message
* @param id the message id or null
* @param message the HTML message content
* @param css the optional CSS to set on the message content.
*/
ASF.Message = function(node, id, message, css) {
if (!id) {
id = "#asf-message";
}
var div = $(id);
if (div.length == 0) {
div = document.createElement("div");
div.id = id.substring(1);
$(document.body).append($(div));
} else {
$(div).removeClass();
}
if (css) {
$(div).addClass(css);
}
return $(div).html(message).message({}).message("attachment", node);
};
})();
| google-code/ada-asf | web/js/asf.js | JavaScript | apache-2.0 | 15,242 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Trigger Rollover Request.
*
*/
class TriggerRolloverRequest {
/**
* Create a TriggerRolloverRequest.
* @property {string} [serverCertificate] Certificate Data
*/
constructor() {
}
/**
* Defines the metadata of TriggerRolloverRequest
*
* @returns {object} metadata of TriggerRolloverRequest
*
*/
mapper() {
return {
required: false,
serializedName: 'TriggerRolloverRequest',
type: {
name: 'Composite',
className: 'TriggerRolloverRequest',
modelProperties: {
serverCertificate: {
required: false,
serializedName: 'serverCertificate',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = TriggerRolloverRequest;
| xingwu1/azure-sdk-for-node | lib/services/storagesyncManagement/lib/models/triggerRolloverRequest.js | JavaScript | apache-2.0 | 1,138 |
// Copyright 2008 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 Protocol Buffer 2 Serializer which serializes messages
* into PB-Lite ("JsPbLite") format.
*
* PB-Lite format is an array where each index corresponds to the associated tag
* number. For example, a message like so:
*
* message Foo {
* optional int bar = 1;
* optional int baz = 2;
* optional int bop = 4;
* }
*
* would be represented as such:
*
* [, (bar data), (baz data), (nothing), (bop data)]
*
* Note that since the array index is used to represent the tag number, sparsely
* populated messages with tag numbers that are not continuous (and/or are very
* large) will have many (empty) spots and thus, are inefficient.
*
*
*
*/
goog.provide('goog.proto2.PbLiteSerializer');
goog.require('goog.proto2.LazyDeserializer');
goog.require('goog.proto2.Util');
/**
* PB-Lite serializer.
*
* @constructor
* @extends {goog.proto2.LazyDeserializer}
*/
goog.proto2.PbLiteSerializer = function() {};
goog.inherits(goog.proto2.PbLiteSerializer, goog.proto2.LazyDeserializer);
/**
* Serializes a message to a PB-Lite object.
*
* @param {goog.proto2.Message} message The message to be serialized.
*
* @return {Object} The serialized form of the message.
*/
goog.proto2.PbLiteSerializer.prototype.serialize = function(message) {
var descriptor = message.getDescriptor();
var fields = descriptor.getFields();
var serialized = [];
// Add the known fields.
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (!message.has(field)) {
continue;
}
var tag = field.getTag();
if (field.isRepeated()) {
serialized[tag] = [];
for (var j = 0; j < message.countOf(field); j++) {
serialized[tag][j] =
this.getSerializedValue(field, message.get(field, j));
}
} else {
serialized[tag] = this.getSerializedValue(field, message.get(field));
}
}
// Add any unknown fields.
message.forEachUnknown(function(tag, value) {
serialized[tag] = value;
});
return serialized;
};
/** @inheritDoc */
goog.proto2.PbLiteSerializer.prototype.deserializeField =
function(message, field, value) {
if (value == null) {
// Since value double-equals null, it may be either null or undefined.
// Ensure we return the same one, since they have different meanings.
return value;
}
if (field.isRepeated()) {
var data = [];
goog.proto2.Util.assert(goog.isArray(value));
for (var i = 0; i < value.length; i++) {
data[i] = this.getDeserializedValue(field, value[i]);
}
return data;
} else {
return this.getDeserializedValue(field, value);
}
};
/** @inheritDoc */
goog.proto2.PbLiteSerializer.prototype.getSerializedValue =
function(field, value) {
if (field.getFieldType() == goog.proto2.Message.FieldType.BOOL) {
// Booleans are serialized in numeric form.
return value ? 1 : 0;
}
return goog.proto2.Serializer.prototype.getSerializedValue.apply(this,
arguments);
};
/** @inheritDoc */
goog.proto2.PbLiteSerializer.prototype.getDeserializedValue =
function(field, value) {
if (field.getFieldType() == goog.proto2.Message.FieldType.BOOL) {
// Booleans are serialized in numeric form.
return value === 1;
}
return goog.proto2.Serializer.prototype.getDeserializedValue.apply(this,
arguments);
};
| maxogden/googlyscript | closure-library/closure/goog/proto2/pbliteserializer.js | JavaScript | apache-2.0 | 4,095 |
var v0 = {
packetCnt: 5,
ctx: [{
name: 'buffer',
value: 12344
}, {
name: 'meter',
value: 124
}, {
name: 'table',
value: 0
}],
key: [{
name: 'Internal',
attrs: [{
name: 'in_port',
value: 4,
}, {
name: 'in_phy_port',
value: 6,
}, {
name: 'tunnel',
value: 12435
}]
}]
}
};
| flowgrammable/flowsim | spike/arrival.js | JavaScript | apache-2.0 | 391 |
/*
* Copyright 2015 Basho Technologies, Inc.
*
* 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.
*/
var FetchSet = require('../../../lib/commands/crdt/fetchset');
var Rpb = require('../../../lib/protobuf/riakprotobuf');
var DtFetchReq = Rpb.getProtoFor('DtFetchReq');
var DtFetchResp = Rpb.getProtoFor('DtFetchResp');
var DtValue = Rpb.getProtoFor('DtValue');
var RpbErrorResp = Rpb.getProtoFor('RpbErrorResp');
var ByteBuffer = require('bytebuffer');
var ByteBuffer = require('bytebuffer');
var assert = require('assert');
describe('FetchSet', function() {
describe('Build', function() {
var builder = new FetchSet.Builder().
withBucketType('sets_type').
withBucket('set_bucket').
withKey('cool_set');
it('builds a DtFetchSet correctly', function(done){
var fetchSet = builder.
withCallback(function(){}).
withR(1).
withPr(2).
withNotFoundOk(true).
withUseBasicQuorum(true).
withTimeout(12345).
build();
var protobuf = fetchSet.constructPbRequest();
assert.equal(protobuf.getType().toString('utf8'),
'sets_type');
assert.equal(protobuf.getBucket().toString('utf8'),
'set_bucket');
assert.equal(protobuf.getKey().toString('utf8'),
'cool_set');
assert.equal(protobuf.getR(), 1);
assert.equal(protobuf.getPr(), 2);
assert.equal(protobuf.getNotfoundOk(), true);
assert.equal(protobuf.getBasicQuorum(), true);
assert.equal(protobuf.getTimeout(), 12345);
done();
});
it('calls back with successful results as buffers', function(done){
var resp = new DtFetchResp();
resp.type = 2;
resp.context = ByteBuffer.fromUTF8("asdf");
var value = new DtValue();
resp.setValue(value);
value.set_value = [ByteBuffer.fromUTF8("zedo"),
ByteBuffer.fromUTF8("piper"),
ByteBuffer.fromUTF8("little one")];
var includesBuffer = function(haystack, needle) {
var needleBuf = new Buffer(needle);
var len = haystack.length;
for (var i = 0; i < len; i++) {
if (haystack[i].equals(needleBuf)) return true;
}
return false;
};
var callback = function(err, response) {
assert.equal(response.context.toString("utf8"), "asdf");
assert(includesBuffer(response.values, "zedo"));
assert(includesBuffer(response.values, "piper"));
assert(includesBuffer(response.values, "little one"));
done();
};
var fetch = builder.
withCallback(callback).
withSetsAsBuffers(true).
build();
fetch.onSuccess(resp);
});
it('calls back with successful results as strings', function(done){
var resp = new DtFetchResp();
resp.type = 2;
resp.context = ByteBuffer.fromUTF8("asdf");
var value = new DtValue();
resp.setValue(value);
value.set_value = [ByteBuffer.fromUTF8("zedo"),
ByteBuffer.fromUTF8("piper"),
ByteBuffer.fromUTF8("little one")];
var includes = function(haystack, needle) {
var len = haystack.length;
for (var i = 0; i < len; i++) {
if (haystack[i] === needle) return true;
}
return false;
};
var callback = function(err, response) {
assert.equal(response.context.toString("utf8"), "asdf");
assert(includes(response.values, "zedo"));
assert(includes(response.values, "piper"));
assert(includes(response.values, "little one"));
done();
};
var fetch = builder.
withCallback(callback).
withSetsAsBuffers(false).
build();
fetch.onSuccess(resp);
});
it('calls back with an error message', function(done) {
var errorMessage = "couldn't crdt :(";
var errorResp = new RpbErrorResp();
errorResp.setErrmsg(new Buffer(errorMessage));
var callback = function(err, response) {
assert(err);
assert.equal(err, errorMessage);
done();
};
var fetch = builder.
withCallback(callback).
build();
fetch.onRiakError(errorResp);
});
});
});
| GabrielNicolasAvellaneda/riak-nodejs-client | test/unit/crdt/fetchset.js | JavaScript | apache-2.0 | 5,621 |
// Add a leaflet map to the div
var map = L.map('map');
// Get the features into a leaflet recognised geojson
var features = {% autoescape off %} {{ cells }} {% endautoescape %};
geojson = L.geoJson(features, {style : style,
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.description);
}
}
);
geojson.addTo(map);
// Add a scale bar
L.control.scale().addTo(map);
// Get the bounds of the features and derive the zoom level
map.fitBounds(geojson.getBounds());
var zoomLevel = map.getZoom();
// Source some tiles
L.tileLayer('http://{s}.tile.cloudmade.com/b04077cbdf8c4aa7b32ebffb94fb8004/{styleId}/256/{z}/{x}/{y}.png', {
maxZoom: 18,
styleId: 22677
}).addTo(map);
| robrant/simple-flask-socketio-example | static/trackapp.js | JavaScript | bsd-2-clause | 744 |
"use strict";
exports.init = function (config, context, callback) {
console.log("Common initialization - this one is OK to be displayed");
callback();
};
exports.shutdown = function (callback) {
console.log("Common shutdown - this one is OK to be displayed");
callback();
};
| qminer/qtopology | demo/std_nodes/disabled/init_and_shutdown.js | JavaScript | bsd-2-clause | 293 |
/**
* @module ol/style/RegularShape
*/
import ImageState from '../ImageState.js';
import ImageStyle from './Image.js';
import {asArray} from '../color.js';
import {asColorLike} from '../colorlike.js';
import {createCanvasContext2D} from '../dom.js';
import {
defaultFillStyle,
defaultLineCap,
defaultLineJoin,
defaultLineWidth,
defaultMiterLimit,
defaultStrokeStyle,
} from '../render/canvas.js';
/**
* Specify radius for regular polygons, or radius1 and radius2 for stars.
* @typedef {Object} Options
* @property {import("./Fill.js").default} [fill] Fill style.
* @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points
* is the number of sides.
* @property {number} [radius] Radius of a regular polygon.
* @property {number} [radius1] Outer radius of a star.
* @property {number} [radius2] Inner radius of a star.
* @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's point facing up.
* @property {Array<number>} [displacement=[0,0]] Displacement of the shape
* @property {import("./Stroke.js").default} [stroke] Stroke style.
* @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
* @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.
*/
/**
* @typedef {Object} RenderOptions
* @property {import("../colorlike.js").ColorLike} [strokeStyle]
* @property {number} strokeWidth
* @property {number} size
* @property {CanvasLineCap} lineCap
* @property {Array<number>} lineDash
* @property {number} lineDashOffset
* @property {CanvasLineJoin} lineJoin
* @property {number} miterLimit
*/
/**
* @classdesc
* Set regular shape style for vector features. The resulting shape will be
* a regular polygon when `radius` is provided, or a star when `radius1` and
* `radius2` are provided.
* @api
*/
class RegularShape extends ImageStyle {
/**
* @param {Options} options Options.
*/
constructor(options) {
/**
* @type {boolean}
*/
const rotateWithView =
options.rotateWithView !== undefined ? options.rotateWithView : false;
super({
opacity: 1,
rotateWithView: rotateWithView,
rotation: options.rotation !== undefined ? options.rotation : 0,
scale: 1,
displacement:
options.displacement !== undefined ? options.displacement : [0, 0],
});
/**
* @private
* @type {HTMLCanvasElement}
*/
this.canvas_ = null;
/**
* @private
* @type {HTMLCanvasElement}
*/
this.hitDetectionCanvas_ = null;
/**
* @private
* @type {import("./Fill.js").default}
*/
this.fill_ = options.fill !== undefined ? options.fill : null;
/**
* @private
* @type {Array<number>}
*/
this.origin_ = [0, 0];
/**
* @private
* @type {number}
*/
this.points_ = options.points;
/**
* @protected
* @type {number}
*/
this.radius_ =
options.radius !== undefined ? options.radius : options.radius1;
/**
* @private
* @type {number|undefined}
*/
this.radius2_ = options.radius2;
/**
* @private
* @type {number}
*/
this.angle_ = options.angle !== undefined ? options.angle : 0;
/**
* @private
* @type {import("./Stroke.js").default}
*/
this.stroke_ = options.stroke !== undefined ? options.stroke : null;
/**
* @private
* @type {Array<number>}
*/
this.anchor_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.size_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.imageSize_ = null;
/**
* @private
* @type {import("../size.js").Size}
*/
this.hitDetectionImageSize_ = null;
this.render();
}
/**
* Clones the style.
* @return {RegularShape} The cloned style.
* @api
*/
clone() {
const style = new RegularShape({
fill: this.getFill() ? this.getFill().clone() : undefined,
points: this.getPoints(),
radius: this.getRadius(),
radius2: this.getRadius2(),
angle: this.getAngle(),
stroke: this.getStroke() ? this.getStroke().clone() : undefined,
rotation: this.getRotation(),
rotateWithView: this.getRotateWithView(),
displacement: this.getDisplacement().slice(),
});
style.setOpacity(this.getOpacity());
style.setScale(this.getScale());
return style;
}
/**
* Get the anchor point in pixels. The anchor determines the center point for the
* symbolizer.
* @return {Array<number>} Anchor.
* @api
*/
getAnchor() {
return this.anchor_;
}
/**
* Get the angle used in generating the shape.
* @return {number} Shape's rotation in radians.
* @api
*/
getAngle() {
return this.angle_;
}
/**
* Get the fill style for the shape.
* @return {import("./Fill.js").default} Fill style.
* @api
*/
getFill() {
return this.fill_;
}
/**
* @param {number} pixelRatio Pixel ratio.
* @return {HTMLImageElement|HTMLCanvasElement} Image element.
*/
getHitDetectionImage(pixelRatio) {
return this.hitDetectionCanvas_;
}
/**
* Get the image icon.
* @param {number} pixelRatio Pixel ratio.
* @return {HTMLImageElement|HTMLCanvasElement} Image or Canvas element.
* @api
*/
getImage(pixelRatio) {
return this.canvas_;
}
/**
* @return {import("../size.js").Size} Image size.
*/
getImageSize() {
return this.imageSize_;
}
/**
* @return {import("../size.js").Size} Size of the hit-detection image.
*/
getHitDetectionImageSize() {
return this.hitDetectionImageSize_;
}
/**
* @return {import("../ImageState.js").default} Image state.
*/
getImageState() {
return ImageState.LOADED;
}
/**
* Get the origin of the symbolizer.
* @return {Array<number>} Origin.
* @api
*/
getOrigin() {
return this.origin_;
}
/**
* Get the number of points for generating the shape.
* @return {number} Number of points for stars and regular polygons.
* @api
*/
getPoints() {
return this.points_;
}
/**
* Get the (primary) radius for the shape.
* @return {number} Radius.
* @api
*/
getRadius() {
return this.radius_;
}
/**
* Get the secondary radius for the shape.
* @return {number|undefined} Radius2.
* @api
*/
getRadius2() {
return this.radius2_;
}
/**
* Get the size of the symbolizer (in pixels).
* @return {import("../size.js").Size} Size.
* @api
*/
getSize() {
return this.size_;
}
/**
* Get the stroke style for the shape.
* @return {import("./Stroke.js").default} Stroke style.
* @api
*/
getStroke() {
return this.stroke_;
}
/**
* @param {function(import("../events/Event.js").default): void} listener Listener function.
*/
listenImageChange(listener) {}
/**
* Load not yet loaded URI.
*/
load() {}
/**
* @param {function(import("../events/Event.js").default): void} listener Listener function.
*/
unlistenImageChange(listener) {}
/**
* @protected
*/
render() {
let lineCap = defaultLineCap;
let lineJoin = defaultLineJoin;
let miterLimit = 0;
let lineDash = null;
let lineDashOffset = 0;
let strokeStyle;
let strokeWidth = 0;
if (this.stroke_) {
strokeStyle = this.stroke_.getColor();
if (strokeStyle === null) {
strokeStyle = defaultStrokeStyle;
}
strokeStyle = asColorLike(strokeStyle);
strokeWidth = this.stroke_.getWidth();
if (strokeWidth === undefined) {
strokeWidth = defaultLineWidth;
}
lineDash = this.stroke_.getLineDash();
lineDashOffset = this.stroke_.getLineDashOffset();
lineJoin = this.stroke_.getLineJoin();
if (lineJoin === undefined) {
lineJoin = defaultLineJoin;
}
lineCap = this.stroke_.getLineCap();
if (lineCap === undefined) {
lineCap = defaultLineCap;
}
miterLimit = this.stroke_.getMiterLimit();
if (miterLimit === undefined) {
miterLimit = defaultMiterLimit;
}
}
let size = 2 * (this.radius_ + strokeWidth) + 1;
const renderOptions = {
strokeStyle: strokeStyle,
strokeWidth: strokeWidth,
size: size,
lineCap: lineCap,
lineDash: lineDash,
lineDashOffset: lineDashOffset,
lineJoin: lineJoin,
miterLimit: miterLimit,
};
const context = createCanvasContext2D(size, size);
this.canvas_ = context.canvas;
// canvas.width and height are rounded to the closest integer
size = this.canvas_.width;
const imageSize = size;
const displacement = this.getDisplacement();
this.draw_(renderOptions, context, 0, 0);
this.createHitDetectionCanvas_(renderOptions);
this.anchor_ = [size / 2 - displacement[0], size / 2 + displacement[1]];
this.size_ = [size, size];
this.imageSize_ = [imageSize, imageSize];
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
* @param {CanvasRenderingContext2D} context The rendering context.
* @param {number} x The origin for the symbol (x).
* @param {number} y The origin for the symbol (y).
*/
draw_(renderOptions, context, x, y) {
let i, angle0, radiusC;
// reset transform
context.setTransform(1, 0, 0, 1, 0, 0);
// then move to (x, y)
context.translate(x, y);
context.beginPath();
let points = this.points_;
if (points === Infinity) {
context.arc(
renderOptions.size / 2,
renderOptions.size / 2,
this.radius_,
0,
2 * Math.PI,
true
);
} else {
const radius2 =
this.radius2_ !== undefined ? this.radius2_ : this.radius_;
if (radius2 !== this.radius_) {
points = 2 * points;
}
for (i = 0; i <= points; i++) {
angle0 = (i * 2 * Math.PI) / points - Math.PI / 2 + this.angle_;
radiusC = i % 2 === 0 ? this.radius_ : radius2;
context.lineTo(
renderOptions.size / 2 + radiusC * Math.cos(angle0),
renderOptions.size / 2 + radiusC * Math.sin(angle0)
);
}
}
if (this.fill_) {
let color = this.fill_.getColor();
if (color === null) {
color = defaultFillStyle;
}
context.fillStyle = asColorLike(color);
context.fill();
}
if (this.stroke_) {
context.strokeStyle = renderOptions.strokeStyle;
context.lineWidth = renderOptions.strokeWidth;
if (context.setLineDash && renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
}
context.lineCap = renderOptions.lineCap;
context.lineJoin = renderOptions.lineJoin;
context.miterLimit = renderOptions.miterLimit;
context.stroke();
}
context.closePath();
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
*/
createHitDetectionCanvas_(renderOptions) {
this.hitDetectionImageSize_ = [renderOptions.size, renderOptions.size];
this.hitDetectionCanvas_ = this.canvas_;
if (this.fill_) {
let color = this.fill_.getColor();
// determine if fill is transparent (or pattern or gradient)
let opacity = 0;
if (typeof color === 'string') {
color = asArray(color);
}
if (color === null) {
opacity = 1;
} else if (Array.isArray(color)) {
opacity = color.length === 4 ? color[3] : 1;
}
if (opacity === 0) {
// if a transparent fill style is set, create an extra hit-detection image
// with a default fill style
const context = createCanvasContext2D(
renderOptions.size,
renderOptions.size
);
this.hitDetectionCanvas_ = context.canvas;
this.drawHitDetectionCanvas_(renderOptions, context, 0, 0);
}
}
}
/**
* @private
* @param {RenderOptions} renderOptions Render options.
* @param {CanvasRenderingContext2D} context The context.
* @param {number} x The origin for the symbol (x).
* @param {number} y The origin for the symbol (y).
*/
drawHitDetectionCanvas_(renderOptions, context, x, y) {
// reset transform
context.setTransform(1, 0, 0, 1, 0, 0);
// then move to (x, y)
context.translate(x, y);
context.beginPath();
let points = this.points_;
if (points === Infinity) {
context.arc(
renderOptions.size / 2,
renderOptions.size / 2,
this.radius_,
0,
2 * Math.PI,
true
);
} else {
const radius2 =
this.radius2_ !== undefined ? this.radius2_ : this.radius_;
if (radius2 !== this.radius_) {
points = 2 * points;
}
let i, radiusC, angle0;
for (i = 0; i <= points; i++) {
angle0 = (i * 2 * Math.PI) / points - Math.PI / 2 + this.angle_;
radiusC = i % 2 === 0 ? this.radius_ : radius2;
context.lineTo(
renderOptions.size / 2 + radiusC * Math.cos(angle0),
renderOptions.size / 2 + radiusC * Math.sin(angle0)
);
}
}
context.fillStyle = defaultFillStyle;
context.fill();
if (this.stroke_) {
context.strokeStyle = renderOptions.strokeStyle;
context.lineWidth = renderOptions.strokeWidth;
if (renderOptions.lineDash) {
context.setLineDash(renderOptions.lineDash);
context.lineDashOffset = renderOptions.lineDashOffset;
}
context.stroke();
}
context.closePath();
}
}
export default RegularShape;
| geekdenz/ol3 | src/ol/style/RegularShape.js | JavaScript | bsd-2-clause | 13,767 |
function AccountPage() {
var self = {};
self.SaveButton = new AccountSaveButton(function () {
var isValid = self.ValidateForm();
self.SaveButton.IsSaving(true);
if (isValid == true) {
var settings = {
AudioNotificationsEnabled: self.AudioNotificationsEnabled(),
VisualNotificationsEnabled: self.VisualNotificationsEnabled(),
Email: self.Email(),
IsChangePassword: self.IsChangePassword(),
CurrentPassword: self.CurrentPassword(),
NewPassword: self.NewPassword(),
PasswordConfirm: self.PasswordConfirm()
};
postJSONToController("/EditUserSettings", settings, function (data) {
if (data.Success == true) {
self.Errors([]);
self.IsShowErrors(false);
self.SaveButton.SetResult("Success");
self.IsChangePassword(false);
self.CurrentPassword("");
self.NewPassword("");
self.PasswordConfirm("");
} else {
var errors = Enumerable.From(data.Errors)
.Select(function (x) { return x.Description; })
.ToArray();
self.Errors(errors);
self.IsShowErrors(true);
page.SaveButton.SetResult("Error");
}
self.SaveButton.IsSaving(false);
});
} else {
self.IsShowErrors(true);
page.SaveButton.SetResult("Error");
self.SaveButton.IsSaving(false);
}
});
self.FileObject = null;
self.OnImageSelected = function (file) {
self.FileObject = file;
self.SelectedImageName(file.name);
self.IsUploadButtonEnabled(true);
};
self.RefreshImage = ko.observable(false);
self.SelectedImageName = ko.observable("");
self.UploadingImageTextDefault = "UploadImage image";
self.UploadingImageTextInProgress = "Loading...";
self.UploadingImageText = ko.observable(self.UploadingImageTextDefault);
self.IsUploadButtonEnabled = ko.observable(false);
self.UploadImageClick = function () {
if (self.IsUploadButtonEnabled() == true) {
getJSON(getUrl("/UploadAvatar"), self.FileObject, function (data) {
self.SelectedImageName("");
self.UploadingImageText(self.UploadingImageTextDefault);
self.RefreshImage(true);
notifier.RefreshImage(true);
});
self.IsUploadButtonEnabled(false);
self.UploadingImageText(self.UploadingImageTextInProgress);
}
};
self.AudioNotificationsEnabled = ko.observable(false);
self.VisualNotificationsEnabled = ko.observable(false);
self.IsChangePassword = ko.observable(false);
self.Errors = ko.observableArray([]);
self.IsShowErrors = ko.observable(false);
self.Email = ko.observable("");
self.CurrentPassword = ko.observable("");
self.NewPassword = ko.observable("");
self.PasswordConfirm = ko.observable("");
self.ValidateForm = function () {
self.Errors([]);
if (!validateEmail(self.Email())) {
self.Errors.push("Wrong email format");
}
if (self.IsChangePassword()) {
if (!self.CurrentPassword()) {
self.Errors.push("Current password cannot be empty");
}
if (!self.NewPassword() || !self.PasswordConfirm()) {
self.Errors.push("Password and password confurm fields cannot be empty");
}
if (self.NewPassword() != self.PasswordConfirm()) {
self.Errors.push("Password and confirmation not equals");
}
}
var validateResult = self.Errors().length == 0;
return validateResult;
};
self.Init = function () {
postJSONToController("/GetUserSettings", {}, function (data) {
self.AudioNotificationsEnabled(data.AudioNotificationsEnabled);
self.VisualNotificationsEnabled(data.VisualNotificationsEnabled);
self.Email(data.Email);
});
};
return self;
} | andreialex007/OnlineMessenger | application/master/OnlineMessenger.MvcServer/obj/Release/Package/PackageTmp/Content/javascript/Models/Account/AccountPage.js | JavaScript | bsd-2-clause | 4,299 |
var assert = require('chai').assert,
Reflux = require('../lib'),
sinon = require('sinon');
describe('using joins',function(){
describe('with static methods',function(){
describe('keeping trailing arguments',function(){
var action1 = Reflux.createAction(),
action2 = Reflux.createAction(),
action3 = Reflux.createAction(),
join = Reflux.joinTrailing(action1,action2,action3),
spy = sinon.spy();
Reflux.createStore().listenTo(join,spy);
action1('a');
action2('b');
action1('x');
action3('c');
it("should emit with the trailing arguments",function(){
assert.deepEqual(spy.firstCall.args,[['x'],['b'],['c']]);
});
action1('1');
action2('2');
action1('11');
action3('3');
it("should emit again after all fire a second time",function(){
assert.deepEqual(spy.secondCall.args,[['11'],['2'],['3']]);
});
action1('FOO');
action3('BAR');
it("should not emit a third time since not all fired three times",function(){
assert.equal(spy.callCount,2);
});
});
describe('keeping leading arguments',function(){
var action1 = Reflux.createAction(),
action2 = Reflux.createAction(),
action3 = Reflux.createAction(),
join = Reflux.joinLeading(action1,action2,action3),
spy = sinon.spy();
Reflux.createStore().listenTo(join,spy);
action1('a');
action2('b');
action1('x');
action3('c');
it("should emit with the leading arguments",function(){
assert.equal(spy.callCount,1);
assert.deepEqual(spy.firstCall.args,[['a'],['b'],['c']]);
});
});
describe('concatenating arguments',function(){
var action1 = Reflux.createAction(),
action2 = Reflux.createAction(),
action3 = Reflux.createAction(),
join = Reflux.joinConcat(action1,action2,action3),
spy = sinon.spy();
Reflux.createStore().listenTo(join,spy);
action1('a');
action2('b');
action1('x');
action3('c');
it("should emit with the concatenated arguments",function(){
assert.equal(spy.callCount,1);
assert.deepEqual(spy.firstCall.args,[[['a'],['x']],[['b']],[['c']]]);
});
});
describe('strictly joining arguments',function(){
var action1,
action2,
action3,
join,
spy;
beforeEach(function() {
action1 = Reflux.createAction({sync: false});
action2 = Reflux.createAction({sync: false});
action3 = Reflux.createAction({sync: false});
join = Reflux.joinStrict(action1,action2,action3);
spy = sinon.spy();
Reflux.createStore().listenTo(join, spy);
});
it("should emit with the arguments",function(done){
action1('a');
action2('b');
action3('c');
setTimeout(function() {
assert.equal(spy.callCount,1);
assert.deepEqual(spy.firstCall.args,[['a'],['b'],['c']]);
done();
}, 50);
});
it("should throw error if triggered more than once",function(){
action1.trigger('a'); // sync trigger to make sure error is correctly caught
assert.throws(function(){
action1.trigger('x');
});
});
});
});
describe('with instance methods',function(){
describe('when validation fails',function(){
var store = Reflux.createStore(),
action1 = {listen:sinon.spy()},
action2 = {listen:sinon.spy()},
action3 = {listen:sinon.spy()};
store.validateListening = sinon.stub().returns('ERROR! ERROR!');
it('should throw an error and not set any listens',function(){
assert.throws(function(){
store.joinTrailing(action1,action2,action3,function(){});
});
assert.equal(0,action1.listen.callCount);
assert.equal(0,action2.listen.callCount);
assert.equal(0,action3.listen.callCount);
});
});
describe('keeping trailing arguments',function(){
var action1 = Reflux.createAction(),
action2 = Reflux.createAction(),
action3 = Reflux.createAction(),
store = Reflux.createStore(),
callback = sinon.spy(),
validate = sinon.spy(),
result;
store.validateListening = validate;
result = store.joinTrailing(action1,action2,action3,callback);
action1('a');
action2('b');
action1('x');
action3('c');
it("should emit with the trailing arguments",function(){
assert.deepEqual(callback.firstCall.args,[['x'],['b'],['c']]);
});
action1('1');
action2('2');
action1('11');
action3('3');
it("should emit again after all fire a second time",function(){
assert.deepEqual(callback.secondCall.args,[['11'],['2'],['3']]);
});
action1('FOO');
action3('BAR');
it("should not emit a third time since not all fired three times",function(){
assert.equal(callback.callCount,2);
});
it("should return a subscription object with stop function and listenable array",function(){
assert.deepEqual([action1,action2,action3],result.listenable);
assert.isFunction(result.stop);
});
it("should add the returned subscription object to the context subscriptions array",function(){
assert.equal(1,store.subscriptions.length);
assert.equal(result,store.subscriptions[0]);
});
it("should validate each individual listenable in the join",function(){
assert.equal(3,validate.callCount);
assert.equal(action1,validate.firstCall.args[0]);
assert.equal(action2,validate.secondCall.args[0]);
assert.equal(action3,validate.thirdCall.args[0]);
});
});
describe('keeping leading arguments',function(){
var action1 = Reflux.createAction(),
action2 = Reflux.createAction(),
action3 = Reflux.createAction(),
store = Reflux.createStore(),
spy = sinon.spy();
store.joinLeading(action1,action2,action3,spy);
action1('a');
action2('b');
action1('x');
action3('c');
it("should emit with the leading arguments",function(){
assert.equal(spy.callCount,1);
assert.deepEqual(spy.firstCall.args,[['a'],['b'],['c']]);
});
});
describe('concatenating arguments',function(){
var action1 = Reflux.createAction(),
action2 = Reflux.createAction(),
action3 = Reflux.createAction(),
store = Reflux.createStore(),
spy = sinon.spy();
store.joinConcat(action1,action2,action3,spy);
action1('a');
action2('b');
action1('x');
action3('c');
it("should emit with the concatenated arguments",function(){
assert.equal(spy.callCount,1);
assert.deepEqual(spy.firstCall.args,[[['a'],['x']],[['b']],[['c']]]);
});
});
describe('strictly joining arguments',function(){
var action1,
action2,
action3,
store,
spy;
beforeEach(function () {
action1 = Reflux.createAction({sync: true});
action2 = Reflux.createAction({sync: true});
action3 = Reflux.createAction({sync: true});
store = Reflux.createStore();
spy = sinon.spy();
store.joinStrict(action1,action2,action3,spy);
});
it("should emit with the arguments",function(done){
action1('a');
action2('b');
action3('c');
setTimeout(function() {
assert.equal(spy.callCount,1);
assert.deepEqual(spy.firstCall.args,[['a'],['b'],['c']]);
done();
}, 10);
});
it("should throw error if triggered more than once",function(){
action1.trigger('a'); // sync trigger to be able to test
assert.throws(function(){
action1.trigger('x');
});
});
});
describe('with more than 1 participant in the join', function() {
it('should not throw', function() {
assert.doesNotThrow(function(){
Reflux.createStore().joinConcat(Reflux.createAction(), function(){});
});
});
});
describe('with less than 2 participants in the join',function(){
it('should fail',function(){
assert.throws(function(){
Reflux.createStore().joinConcat(function(){});
});
});
});
});
});
| ericf89/reflux-core | test/usingJoins.spec.js | JavaScript | bsd-3-clause | 10,005 |
export default function(_) {
return typeof _ === 'string';
}
| vega/vega | packages/vega-util/src/isString.js | JavaScript | bsd-3-clause | 63 |
const test = require('tape')
const ProviderEngine = require('../index.js')
const FixtureProvider = require('../subproviders/fixture.js')
const CacheProvider = require('../subproviders/cache.js')
const TestBlockProvider = require('./util/block.js')
const createPayload = require('../util/create-payload.js')
const injectMetrics = require('./util/inject-metrics')
// skip cache
cacheTest('skipCache - true', {
method: 'eth_getBalance',
skipCache: true,
}, false)
cacheTest('skipCache - false', {
method: 'eth_getBalance',
skipCache: false,
}, true)
// block tags
cacheTest('getBalance + undefined blockTag', {
method: 'eth_getBalance',
params: ['0x1234'],
}, true)
cacheTest('getBalance + latest blockTag', {
method: 'eth_getBalance',
params: ['0x1234', 'latest'],
}, true)
cacheTest('getBalance + pending blockTag', {
method: 'eth_getBalance',
params: ['0x1234', 'pending'],
}, false)
// tx by hash
cacheTest('getTransactionByHash for transaction that doesn\'t exist', {
method: 'eth_getTransactionByHash',
params: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe00'],
}, false)
cacheTest('getTransactionByHash for transaction that\'s pending', {
method: 'eth_getTransactionByHash',
params: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe01'],
}, false)
cacheTest('getTransactionByHash for mined transaction', {
method: 'eth_getTransactionByHash',
params: ['0x00000000000000000000000000000000000000000000000000deadbeefcafe02'],
}, true)
// code
cacheTest('getCode for latest block, then for earliest block, should not return cached response on second request', [{
method: 'eth_getCode',
params: ['0x1234', 'latest'],
}, {
method: 'eth_getCode',
params: ['0x1234', 'earliest'],
}], false)
cacheTest('getCode for a specific block, then for the one before it, should not return cached response on second request', [{
method: 'eth_getCode',
params: ['0x1234', '0x3'],
}, {
method: 'eth_getCode',
params: ['0x1234', '0x2'],
}], false)
cacheTest('getCode for a specific block, then the one after it, should return cached response on second request', [{
method: 'eth_getCode',
params: ['0x1234', '0x2'],
}, {
method: 'eth_getCode',
params: ['0x1234', '0x3'],
}], true)
cacheTest('getCode for an unspecified block, then for the latest, should return cached response on second request', [{
method: 'eth_getCode',
params: ['0x1234'],
}, {
method: 'eth_getCode',
params: ['0x1234', 'latest'],
}], true)
// blocks
cacheTest('getBlockForNumber for latest then block 0', [{
method: 'eth_getBlockByNumber',
params: ['latest'],
}, {
method: 'eth_getBlockByNumber',
params: ['0x0'],
}], false)
cacheTest('getBlockForNumber for latest then block 1', [{
method: 'eth_getBlockByNumber',
params: ['latest'],
}, {
method: 'eth_getBlockByNumber',
params: ['0x1'],
}], false)
cacheTest('getBlockForNumber for 0 then block 1', [{
method: 'eth_getBlockByNumber',
params: ['0x0'],
}, {
method: 'eth_getBlockByNumber',
params: ['0x1'],
}], false)
cacheTest('getBlockForNumber for block 0', [{
method: 'eth_getBlockByNumber',
params: ['0x0'],
}, {
method: 'eth_getBlockByNumber',
params: ['0x0'],
}], true)
cacheTest('getBlockForNumber for block 1', [{
method: 'eth_getBlockByNumber',
params: ['0x1'],
}, {
method: 'eth_getBlockByNumber',
params: ['0x1'],
}], true)
// test helper for caching
// 1. Sets up caching and data provider
// 2. Performs first request
// 3. Performs second request
// 4. checks if cache hit or missed
function cacheTest(label, payloads, shouldHitCacheOnSecondRequest){
if (!Array.isArray(payloads)) {
payloads = [payloads, payloads]
}
test('cache - '+label, function(t){
t.plan(12)
// cache layer
var cacheProvider = injectMetrics(new CacheProvider())
// handle balance
var dataProvider = injectMetrics(new FixtureProvider({
eth_getBalance: '0xdeadbeef',
eth_getCode: '6060604052600560005560408060156000396000f3606060405260e060020a60003504633fa4f245811460245780635524107714602c575b005b603660005481565b6004356000556022565b6060908152602090f3',
eth_getTransactionByHash: function(payload, next, end) {
// represents a pending tx
if (payload.params[0] === '0x00000000000000000000000000000000000000000000000000deadbeefcafe00') {
end(null, null)
} else if (payload.params[0] === '0x00000000000000000000000000000000000000000000000000deadbeefcafe01') {
end(null, {
hash: '0x00000000000000000000000000000000000000000000000000deadbeefcafe01',
nonce: '0xd',
blockHash: null,
blockNumber: null,
transactionIndex: null,
from: '0xb1cc05ab12928297911695b55ee78c1188f8ef91',
to: '0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98',
value: '0xddb66b2addf4800',
gas: '0x5622',
gasPrice: '0xba43b7400',
input: '0x',
})
} else {
end(null, {
hash: payload.params[0],
nonce: '0xd',
blockHash: '0x1',
blockNumber: '0x1',
transactionIndex: '0x0',
from: '0xb1cc05ab12928297911695b55ee78c1188f8ef91',
to: '0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98',
value: '0xddb66b2addf4800',
gas: '0x5622',
gasPrice: '0xba43b7400',
input: '0x',
})
}
}
}))
// handle dummy block
var blockProvider = injectMetrics(new TestBlockProvider())
var engine = new ProviderEngine()
engine.addProvider(cacheProvider)
engine.addProvider(dataProvider)
engine.addProvider(blockProvider)
// run polling until first block
engine.start()
engine.once('block', () => {
// stop polling
engine.stop()
// clear subprovider metrics
cacheProvider.clearMetrics()
dataProvider.clearMetrics()
blockProvider.clearMetrics()
// determine which provider will handle the request
const isBlockTest = (payloads[0].method === 'eth_getBlockByNumber')
const handlingProvider = isBlockTest ? blockProvider : dataProvider
// begin cache test
cacheCheck(t, engine, cacheProvider, handlingProvider, payloads, function(err, response) {
t.end()
})
})
function cacheCheck(t, engine, cacheProvider, handlingProvider, payloads, cb) {
var method = payloads[0].method
requestTwice(payloads, function(err, response){
// first request
t.ifError(err || response.error && response.error.message, 'did not error')
t.ok(response, 'has response')
t.equal(cacheProvider.getWitnessed(method).length, 1, 'cacheProvider did see "'+method+'"')
t.equal(cacheProvider.getHandled(method).length, 0, 'cacheProvider did NOT handle "'+method+'"')
t.equal(handlingProvider.getWitnessed(method).length, 1, 'handlingProvider did see "'+method+'"')
t.equal(handlingProvider.getHandled(method).length, 1, 'handlingProvider did handle "'+method+'"')
}, function(err, response){
// second request
t.ifError(err || response.error && response.error.message, 'did not error')
t.ok(response, 'has response')
if (shouldHitCacheOnSecondRequest) {
t.equal(cacheProvider.getWitnessed(method).length, 2, 'cacheProvider did see "'+method+'"')
t.equal(cacheProvider.getHandled(method).length, 1, 'cacheProvider did handle "'+method+'"')
t.equal(handlingProvider.getWitnessed(method).length, 1, 'handlingProvider did NOT see "'+method+'"')
t.equal(handlingProvider.getHandled(method).length, 1, 'handlingProvider did NOT handle "'+method+'"')
} else {
t.equal(cacheProvider.getWitnessed(method).length, 2, 'cacheProvider did see "'+method+'"')
t.equal(cacheProvider.getHandled(method).length, 0, 'cacheProvider did handle "'+method+'"')
t.equal(handlingProvider.getWitnessed(method).length, 2, 'handlingProvider did NOT see "'+method+'"')
t.equal(handlingProvider.getHandled(method).length, 2, 'handlingProvider did NOT handle "'+method+'"')
}
cb()
})
}
function requestTwice(payloads, afterFirst, afterSecond){
engine.sendAsync(createPayload(payloads[0]), function(err, result){
afterFirst(err, result)
engine.sendAsync(createPayload(payloads[1]), afterSecond)
})
}
})
}
| DigixGlobal/truffle-lightwallet-provider | node_modules/web3-provider-engine/test/cache.js | JavaScript | bsd-3-clause | 8,514 |
/*
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A test suite for forcetk.mobilesdk.js
* This file assumes that qunit.js has been previously loaded, as well as jquery.js, SFTestSuite.js.
* To display results you'll need to load qunit.css.
*/
if (typeof ForcetkTestSuite === 'undefined') {
/**
* Constructor for ForcetkTestSuite
*/
var ForcetkTestSuite = function () {
SFTestSuite.call(this, "forcetk");
this.apiVersion = "v31.0";
};
// We are sub-classing SFTestSuite
ForcetkTestSuite.prototype = new SFTestSuite();
ForcetkTestSuite.prototype.constructor = ForcetkTestSuite;
/**
* TEST computeWebAppSdkAgent for unrecognized user agents
*/
ForcetkTestSuite.prototype.testComputeWebAppSdkAgentForUnrecognizedUserAgents = function() {
console.log("In SFForcetkTestSuite.testComputeWebAppSdkAgentForUnrecognizedUserAgents");
this.tryUserAgent("Unknown", "Unknown", "Unknown", "Unrecognized agent");
this.finalizeTest();
};
/**
* TEST computeWebAppSdkAgent for iOS user agents
*/
ForcetkTestSuite.prototype.testComputeWebAppSdkAgentForIOSUserAgents = function() {
console.log("In SFForcetkTestSuite.testComputeWebAppSdkAgentForIOSUserAgents");
// User agents taken from http://www.zytrax.com/tech/web/mobile_ids.html
this.tryUserAgent("iPhone OS", "6.1.3", "iPad", "Mozilla/5.0 (iPad; CPU OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25");
this.tryUserAgent("iPhone OS", "5.1.1", "iPod", "Mozilla/5.0 (iPod; CPU iPhone OS 5_1_1 like Mac OS X; nl-nl) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/21.0.1180.80 Mobile/9B206 Safari/7534.48.3");
this.tryUserAgent("iPhone OS", "5.1", "iPhone", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3");
this.tryUserAgent("iPhone OS", "4.3.1", "iPad", "Mozilla/5.0 (iPad; U; CPU OS 4_3_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8G4 Safari/6533.18.5");
this.finalizeTest();
};
/**
* TEST computeWebAppSdkAgent for Android user agents
*/
ForcetkTestSuite.prototype.testComputeWebAppSdkAgentForAndroidUserAgents = function() {
console.log("In SFForcetkTestSuite.testComputeWebAppSdkAgentForAndroidUserAgents");
// User agents taken from http://www.zytrax.com/tech/web/mobile_ids.html
this.tryUserAgent("android mobile", "4.1.1", "Nexus_7_Build_JRO03D", "Mozilla/5.0 (Linux; U; Android 4.1.1; he-il; Nexus 7 Build/JRO03D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30");
this.tryUserAgent("android mobile", "2.1", "Nexus_One_Build_ERD62", "Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
this.finalizeTest();
};
/**
* TEST computeWebAppSdkAgent for WindowsPhone user agents
*/
ForcetkTestSuite.prototype.testComputeWebAppSdkAgentForWindowsPhoneUserAgents = function() {
console.log("In SFForcetkTestSuite.testComputeWebAppSdkAgentForWindowsPhoneUserAgents");
// User agents taken from http://www.zytrax.com/tech/web/mobile_ids.html
this.tryUserAgent("Windows Phone", "7.0", "7_Trophy", "Mozilla/4.0 (compatible: MSIE 7.0; Windows Phone OS 7.0; Trident/3.1; IEMobile/7.0; HTC; 7 Trophy)");
this.tryUserAgent("Windows Phone", "7.5", "Lumia_710", "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; NOKIA; Lumia 710)");
this.finalizeTest();
};
/**
* TEST computeWebAppSdkAgent for desktop user agents
*/
ForcetkTestSuite.prototype.testComputeWebAppSdkAgentForDesktopUserAgents = function() {
console.log("In SFForcetkTestSuite.testComputeWebAppSdkAgentForDesktopUserAgents");
// User agents taken from http://techblog.willshouse.com/2012/01/03/most-common-user-agents/
this.tryUserAgent("Mac OS", "10.8.4", "Unknown", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36");
this.tryUserAgent("Windows", "6.2", "Unknown", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36");
this.tryUserAgent("Windows", "6.1", "Unknown", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36");
this.tryUserAgent("Windows", "5.1", "Unknown", "Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0");
this.tryUserAgent("Unknown", "Unknown", "Unknown", "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36");
this.finalizeTest();
};
/**
* TEST ownedFilesList
*/
ForcetkTestSuite.prototype.testOwnedFilesList = function() {
console.log("In SFForcetkTestSuite.testOwnedFilesList");
var forcetkClient = this.getTestForcetkClientForGet();
QUnit.equals(forcetkClient.ownedFilesList(), "/" + this.apiVersion + "/chatter/users/me/files");
QUnit.equals(forcetkClient.ownedFilesList("me"), "/" + this.apiVersion + "/chatter/users/me/files");
QUnit.equals(forcetkClient.ownedFilesList("someUserId"), "/" + this.apiVersion + "/chatter/users/someUserId/files");
QUnit.equals(forcetkClient.ownedFilesList(null, 1), "/" + this.apiVersion + "/chatter/users/me/files?page=1");
QUnit.equals(forcetkClient.ownedFilesList("me", 2), "/" + this.apiVersion + "/chatter/users/me/files?page=2");
QUnit.equals(forcetkClient.ownedFilesList("someUserId", 3), "/" + this.apiVersion + "/chatter/users/someUserId/files?page=3");
this.finalizeTest();
};
/**
* TEST filesInUsersGroups
*/
ForcetkTestSuite.prototype.testFilesInUsersGroups = function() {
console.log("In SFForcetkTestSuite.testFilesInUsersGroups");
var forcetkClient = this.getTestForcetkClientForGet();
QUnit.equals(forcetkClient.filesInUsersGroups(), "/" + this.apiVersion + "/chatter/users/me/files/filter/groups");
QUnit.equals(forcetkClient.filesInUsersGroups("me"), "/" + this.apiVersion + "/chatter/users/me/files/filter/groups");
QUnit.equals(forcetkClient.filesInUsersGroups("someUserId"), "/" + this.apiVersion + "/chatter/users/someUserId/files/filter/groups");
QUnit.equals(forcetkClient.filesInUsersGroups(null, 1), "/" + this.apiVersion + "/chatter/users/me/files/filter/groups?page=1");
QUnit.equals(forcetkClient.filesInUsersGroups("me", 2), "/" + this.apiVersion + "/chatter/users/me/files/filter/groups?page=2");
QUnit.equals(forcetkClient.filesInUsersGroups("someUserId", 3), "/" + this.apiVersion + "/chatter/users/someUserId/files/filter/groups?page=3");
this.finalizeTest();
};
/**
* TEST filesSharedWithUser
*/
ForcetkTestSuite.prototype.testFilesSharedWithUser = function() {
console.log("In SFForcetkTestSuite.testFilesInUsersGroups");
var forcetkClient = this.getTestForcetkClientForGet();
QUnit.equals(forcetkClient.filesSharedWithUser(), "/" + this.apiVersion + "/chatter/users/me/files/filter/sharedwithme");
QUnit.equals(forcetkClient.filesSharedWithUser("me"), "/" + this.apiVersion + "/chatter/users/me/files/filter/sharedwithme");
QUnit.equals(forcetkClient.filesSharedWithUser("someUserId"), "/" + this.apiVersion + "/chatter/users/someUserId/files/filter/sharedwithme");
QUnit.equals(forcetkClient.filesSharedWithUser(null, 1), "/" + this.apiVersion + "/chatter/users/me/files/filter/sharedwithme?page=1");
QUnit.equals(forcetkClient.filesSharedWithUser("me", 2), "/" + this.apiVersion + "/chatter/users/me/files/filter/sharedwithme?page=2");
QUnit.equals(forcetkClient.filesSharedWithUser("someUserId", 3), "/" + this.apiVersion + "/chatter/users/someUserId/files/filter/sharedwithme?page=3");
this.finalizeTest();
};
/**
* TEST fileDetails
*/
ForcetkTestSuite.prototype.testFileDetails = function() {
console.log("In SFForcetkTestSuite.testFileDetails");
var forcetkClient = this.getTestForcetkClientForGet();
QUnit.equals(forcetkClient.fileDetails("someFileId"), "/" + this.apiVersion + "/chatter/files/someFileId");
QUnit.equals(forcetkClient.fileDetails("someFileId", "someVersionNumber"), "/" + this.apiVersion + "/chatter/files/someFileId?versionNumber=someVersionNumber");
this.finalizeTest();
};
/**
* TEST batchFileDetails
*/
ForcetkTestSuite.prototype.testBatchFileDetails = function() {
console.log("In SFForcetkTestSuite.testBatchFileDetails");
var forcetkClient = this.getTestForcetkClientForGet();
QUnit.equals(forcetkClient.batchFileDetails(["someFileId"]), "/" + this.apiVersion + "/chatter/files/batch/someFileId");
QUnit.equals(forcetkClient.batchFileDetails(["someFileId", "otherFileId"]), "/" + this.apiVersion + "/chatter/files/batch/someFileId,otherFileId");
QUnit.equals(forcetkClient.batchFileDetails(["someFileId", "otherFileId", "thirdFileId"]), "/" + this.apiVersion + "/chatter/files/batch/someFileId,otherFileId,thirdFileId");
this.finalizeTest();
};
/**
* TEST fileRenditionPath
*/
ForcetkTestSuite.prototype.testFileRenditionPath = function() {
console.log("In SFForcetkTestSuite.testFileRenditionPath");
var forcetkClient = this.getTestForcetkClientForBinary();
// only rendition type provided
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "FLASH"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "PDF"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "THUMB120BY90"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "THUMB240BY180"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "THUMB720BY480"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480");
// rendition type and version provided
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "FLASH"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH&versionNumber=someVersionNumber");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "PDF"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF&versionNumber=someVersionNumber");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "THUMB120BY90"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90&versionNumber=someVersionNumber");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "THUMB240BY180"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180&versionNumber=someVersionNumber");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "THUMB720BY480"), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480&versionNumber=someVersionNumber");
// rendition type and page number provided
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "FLASH", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "PDF", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "THUMB120BY90", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "THUMB240BY180", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", null, "THUMB720BY480", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480&page=3");
// rendition type, version and page number provided
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "FLASH", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH&versionNumber=someVersionNumber&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "PDF", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF&versionNumber=someVersionNumber&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "THUMB120BY90", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90&versionNumber=someVersionNumber&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "THUMB240BY180", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180&versionNumber=someVersionNumber&page=3");
QUnit.equals(forcetkClient.fileRenditionPath("someFileId", "someVersionNumber", "THUMB720BY480", 3), "/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480&versionNumber=someVersionNumber&page=3");
this.finalizeTest();
};
/**
* TEST fileRendition
*/
ForcetkTestSuite.prototype.testFileRendition = function() {
console.log("In SFForcetkTestSuite.testFileRendition");
var forcetkClient = this.getTestForcetkClientForBinary();
// only rendition type provided
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "FLASH"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH", "application/x-shockwave-flash"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "PDF"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF", "application/pdf"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "THUMB120BY90"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "THUMB240BY180"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "THUMB720BY480"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480", "image/jpeg"]);
// rendition type and version provided
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "FLASH"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH&versionNumber=someVersionNumber", "application/x-shockwave-flash"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "PDF"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF&versionNumber=someVersionNumber", "application/pdf"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "THUMB120BY90"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90&versionNumber=someVersionNumber", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "THUMB240BY180"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180&versionNumber=someVersionNumber", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "THUMB720BY480"), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480&versionNumber=someVersionNumber", "image/jpeg"]);
// rendition type and page number provided
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "FLASH", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH&page=3", "application/x-shockwave-flash"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "PDF", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF&page=3", "application/pdf"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "THUMB120BY90", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90&page=3", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "THUMB240BY180", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180&page=3", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", null, "THUMB720BY480", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480&page=3", "image/jpeg"]);
// rendition type, version and page number provided
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "FLASH", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=FLASH&versionNumber=someVersionNumber&page=3", "application/x-shockwave-flash"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "PDF", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=PDF&versionNumber=someVersionNumber&page=3", "application/pdf"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "THUMB120BY90", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB120BY90&versionNumber=someVersionNumber&page=3", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "THUMB240BY180", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB240BY180&versionNumber=someVersionNumber&page=3", "image/jpeg"]);
QUnit.deepEqual(forcetkClient.fileRendition("someFileId", "someVersionNumber", "THUMB720BY480", 3), ["/" + this.apiVersion + "/chatter/files/someFileId/rendition?type=THUMB720BY480&versionNumber=someVersionNumber&page=3", "image/jpeg"]);
this.finalizeTest();
};
/**
* TEST fileContentsPath
*/
ForcetkTestSuite.prototype.testFileContentsPath = function() {
console.log("In SFForcetkTestSuite.testFileContentsPath");
var forcetkClient = this.getTestForcetkClientForBinary();
QUnit.equals(forcetkClient.fileContentsPath("someFileId"), "/" + this.apiVersion + "/chatter/files/someFileId/content");
QUnit.deepEqual(forcetkClient.fileContentsPath("someFileId", "someVersionNumber"), "/" + this.apiVersion + "/chatter/files/someFileId/content?versionNumber=someVersionNumber");
this.finalizeTest();
};
/**
* TEST fileContents
*/
ForcetkTestSuite.prototype.testFileContents = function() {
console.log("In SFForcetkTestSuite.testFileContents");
var forcetkClient = this.getTestForcetkClientForBinary();
QUnit.deepEqual(forcetkClient.fileContents("someFileId"), ["/" + this.apiVersion + "/chatter/files/someFileId/content", null]);
QUnit.deepEqual(forcetkClient.fileContents("someFileId", "someVersionNumber"), ["/" + this.apiVersion + "/chatter/files/someFileId/content?versionNumber=someVersionNumber", null]);
this.finalizeTest();
};
/**
* TEST fileShares
*/
ForcetkTestSuite.prototype.testFileShares = function() {
console.log("In SFForcetkTestSuite.testFileShares");
var forcetkClient = this.getTestForcetkClientForGet();
QUnit.equals(forcetkClient.fileShares("fileId"), "/" + this.apiVersion + "/chatter/files/fileId/file-shares");
QUnit.equals(forcetkClient.fileShares("fileId", 2), "/" + this.apiVersion + "/chatter/files/fileId/file-shares?page=2");
this.finalizeTest();
};
/**
* TEST addFileShare
*/
ForcetkTestSuite.prototype.testAddFileShare = function() {
console.log("In SFForcetkTestSuite.testAddFileShare");
var forcetkClient = this.getTestForcetkClient();
QUnit.deepEqual(forcetkClient.addFileShare("fileId", "entityId", "shareType"), {path:"/" + this.apiVersion + "/sobjects/ContentDocumentLink/", method:"POST", payload:'{"ContentDocumentId":"fileId","LinkedEntityId":"entityId","ShareType":"shareType"}'});
this.finalizeTest();
};
/**
* TEST deleteFileShare
*/
ForcetkTestSuite.prototype.testDeleteFileShare = function() {
console.log("In SFForcetkTestSuite.testDeleteFileShare");
var forcetkClient = this.getTestForcetkClient();
QUnit.deepEqual(forcetkClient.deleteFileShare("shareId"), {path:"/" + this.apiVersion + "/sobjects/ContentDocumentLink/shareId", method:"DELETE", payload: undefined});
this.finalizeTest();
};
/**
* Helper function for user agent testing
*/
ForcetkTestSuite.prototype.tryUserAgent = function(expectedPlatform, expectedPlatformVersion, expectedModel, userAgent) {
var forcetkClient = new forcetk.Client();
var webAppSdkAgent = forcetkClient.computeWebAppSdkAgent(userAgent);
var match = /SalesforceMobileSDK\/3.0.0 ([^\/]*)\/([^\ ]*) \(([^\)]*)\) ([^\/]*)\/1.0 Web (.*)/.exec(webAppSdkAgent);
if (match != null && match.length == 6) {
QUnit.equals(match[1], expectedPlatform, "Wrong platform for user agent [" + userAgent + "]");
QUnit.equals(match[2], expectedPlatformVersion, "Wrong platformVersion for user agent [" + userAgent + "]");
QUnit.equals(match[3], expectedModel, "Wrong model for user agent [" + userAgent + "]");
QUnit.equals(match[4], window.location.pathname.split("/").pop(), "Wrong appName for user agent [" + userAgent + "]");
QUnit.equals(match[5], userAgent, "Wrong user agent appended for user agent [" + userAgent + "]");
}
else {
QUnit.ok(false, "Wrong user agent produced [" + webAppSdkAgent + "] for user agent [" + userAgent + "]");
}
};
/**
* Helper function to get a forcetk client that doesn't actually send requests
*/
ForcetkTestSuite.prototype.getTestForcetkClient = function() {
var forcetkClient = new forcetk.Client();
forcetkClient.apiVersion = this.apiVersion;
forcetkClient.ajax = function(path, callback, error, method, payload) { return {path:path, method:method, payload:payload}; }
return forcetkClient;
};
/**
* Helper function to get a forcetk client that doesn't actually send requests when testing get requests
*/
ForcetkTestSuite.prototype.getTestForcetkClientForGet = function() {
var forcetkClient = new forcetk.Client();
forcetkClient.apiVersion = this.apiVersion;
forcetkClient.ajax = function(path) { return path; }
return forcetkClient;
};
/**
* Helper function to get a forcetk client that doesn't actually send requests when testing requests that fetch binary
*/
ForcetkTestSuite.prototype.getTestForcetkClientForBinary = function() {
var forcetkClient = new forcetk.Client();
forcetkClient.apiVersion = this.apiVersion;
forcetkClient.getChatterFile = function(path, mimeType) { return [path, mimeType]; }
return forcetkClient;
};
}
| ForceDotComLabs/paper-sobject-editor | dependencies/mobilesdk-shared/test/SFForcetkTestSuite.js | JavaScript | bsd-3-clause | 24,225 |
/**
* Pimcore
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.pimcore.org/license
*
* @copyright Copyright (c) 2009-2013 pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license New BSD License
*/
pimcore.registerNS("pimcore.object.tags.nonownerobjects");
pimcore.object.tags.nonownerobjects = Class.create(pimcore.object.tags.objects, {
removeObject: function (index, item) {
if (pimcore.globalmanager.exists("object_" + this.getStore().getAt(index).data.id) == false) {
Ext.Ajax.request({
url: "/admin/object/get/",
params: {id: this.getStore().getAt(index).data.id},
success: function(item, index, response) {
this.data = Ext.decode(response.responseText);
if (this.data.editlock) {
var lockDate = new Date(this.data.editlock.date * 1000);
var lockDetails = "<br /><br />";
lockDetails += "<b>" + t("user") + ":</b> " + this.data.editlock.user.name + "<br />";
lockDetails += "<b>" + t("since") + ": </b>" + Ext.util.Format.date(lockDate);
lockDetails += "<br /><br />" + t("element_implicit_edit_question");
Ext.MessageBox.confirm(t("element_is_locked"), t("element_lock_message") + lockDetails,
function (lock, buttonValue) {
if (buttonValue == "yes") {
this.getStore().removeAt(index);
if (item != null) {
item.parentMenu.destroy();
}
}
}.bind(this, arguments));
} else {
Ext.Ajax.request({
url: "/admin/element/lock-element",
params: {id: this.getStore().getAt(index).data.id, type: 'object'}
});
this.getStore().removeAt(index);
if (item != null) {
item.parentMenu.destroy();
}
}
}.bind(this, item, index)
});
} else {
var lockDetails = "<br /><br />" + t("element_implicit_edit_question");
Ext.MessageBox.confirm(t("element_is_open"), t("element_open_message") + lockDetails,
function (lock, buttonValue) {
if (buttonValue == "yes") {
this.getStore().removeAt(index);
item.parentMenu.destroy();
}
}.bind(this, arguments));
}
},
actionColumnRemove: function (grid, rowIndex) {
var f = this.removeObject.bind(grid, rowIndex, null);
f();
},
getLayoutEdit: function () {
var autoHeight = false;
if (intval(this.fieldConfig.height) < 15) {
autoHeight = true;
}
var cls = 'object_field';
var classStore = pimcore.globalmanager.get("object_types_store");
var record = classStore.getAt(classStore.find('text', this.fieldConfig.ownerClassName));
// no class for nonowner is specified
if(!record) {
this.component = new Ext.Panel({
title: ts(this.fieldConfig.title),
cls: cls,
html: "There's no class specified in the field-configuration"
});
return this.component;
}
var className = record.data.text;
this.component = new Ext.grid.GridPanel({
store: this.store,
sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
colModel: new Ext.grid.ColumnModel({
defaults: {
sortable: false
},
columns: [
{header: 'ID', dataIndex: 'id', width: 50},
{id: "path", header: t("path"), dataIndex: 'path', width: 200},
{header: t("type"), dataIndex: 'type', width: 100},
{
xtype: 'actioncolumn',
width: 30,
items: [
{
tooltip: t('open'),
icon: "/pimcore/static/img/icon/pencil_go.png",
handler: function (grid, rowIndex) {
var data = grid.getStore().getAt(rowIndex);
pimcore.helpers.openObject(data.data.id, "object");
}.bind(this)
}
]
},
{
xtype: 'actioncolumn',
width: 30,
items: [
{
tooltip: t('remove'),
icon: "/pimcore/static/img/icon/cross.png",
handler: this.actionColumnRemove.bind(this)
}
]
}
]
}),
cls: cls,
autoExpandColumn: 'path',
width: this.fieldConfig.width,
height: this.fieldConfig.height,
tbar: {
items: [
{
xtype: "tbspacer",
width: 20,
height: 16,
cls: "pimcore_icon_droptarget"
},
{
xtype: "tbtext",
text: "<b>" + this.fieldConfig.title + "</b>"
},
"->",
{
xtype: "button",
iconCls: "pimcore_icon_delete",
handler: this.empty.bind(this)
},
{
xtype: "button",
iconCls: "pimcore_icon_search",
handler: this.openSearchEditor.bind(this)
},
this.getCreateControl()
],
ctCls: "pimcore_force_auto_width",
cls: "pimcore_force_auto_width"
},
bbar: {
items: [{
xtype: "tbtext",
text: ' <span class="warning">' + t('nonownerobject_warning') + " | " + t('owner_class')
+ ':<b>' + ts(className) + "</b> " + t('owner_field') + ': <b>'
+ ts(this.fieldConfig.ownerFieldName) + '</b></span>'
}],
ctCls: "pimcore_force_auto_width",
cls: "pimcore_force_auto_width"
},
autoHeight: autoHeight,
bodyCssClass: "pimcore_object_tag_objects"
});
this.component.on("rowcontextmenu", this.onRowContextmenu);
this.component.reference = this;
this.component.on("afterrender", function () {
var dropTargetEl = this.component.getEl();
var gridDropTarget = new Ext.dd.DropZone(dropTargetEl, {
ddGroup : 'element',
getTargetFromEvent: function(e) {
return this.component.getEl().dom;
//return e.getTarget(this.grid.getView().rowSelector);
}.bind(this),
onNodeOver: function (overHtmlNode, ddSource, e, data) {
if (data.node.attributes.elementType == "object" && this.dndAllowed(data)) {
return Ext.dd.DropZone.prototype.dropAllowed;
} else {
return Ext.dd.DropZone.prototype.dropNotAllowed;
}
}.bind(this),
onNodeDrop : function(target, dd, e, data) {
if (data.node.attributes.elementType != "object") {
return false;
}
if (this.dndAllowed(data)) {
var initData = {
id: data.node.attributes.id,
fullpath: data.node.attributes.path,
className: data.node.attributes.className
};
if (!this.objectAlreadyExists(initData.id) && initData.id != this.object.id) {
this.addObject(initData);
return true;
} else {
return false;
}
} else {
return false;
}
}.bind(this)
});
}.bind(this));
return this.component;
},
dndAllowed: function(data) {
// check if data is a treenode, if not allow drop because of the reordering
if (!this.sourceIsTreeNode(data)) {
return true;
}
// only allow objects not folders
if (data.node.attributes.type == "folder") {
return false;
}
//don't allow relation to myself
if (data.node.id == this.object.id) {
return false;
}
var classname = data.node.attributes.className;
var classStore = pimcore.globalmanager.get("object_types_store");
var record = classStore.getAt(classStore.find('text', classname));
var name = record.data.text;
if (this.fieldConfig.ownerClassName == name) {
return true;
} else {
return false;
}
},
openSearchEditor: function () {
var allowedClasses = [];
var classStore = pimcore.globalmanager.get("object_types_store");
var record = classStore.getAt(classStore.find('text', this.fieldConfig.ownerClassName));
allowedClasses.push(record.data.text);
pimcore.helpers.itemselector(false, this.addDataFromSelector.bind(this), {
type: ["object"],
subtype: [
{
object: ["object", "variant"]
}
],
specific: {
classes: allowedClasses
}
});
},
addObject: function(item) {
if (pimcore.globalmanager.exists("object_" + item.id) == false) {
Ext.Ajax.request({
url: "/admin/object/get/",
params: {id: item.id},
success: function(item, response) {
this.data = Ext.decode(response.responseText);
if (this.data.editlock) {
var lockDate = new Date(this.data.editlock.date * 1000);
var lockDetails = "<br /><br />";
lockDetails += "<b>" + t("user") + ":</b> " + this.data.editlock.user.name + "<br />";
lockDetails += "<b>" + t("since") + ": </b>" + Ext.util.Format.date(lockDate);
lockDetails += "<br /><br />" + t("element_implicit_edit_question");
Ext.MessageBox.confirm(t("element_is_locked"), t("element_lock_message") + lockDetails,
function (lock, buttonValue) {
if (buttonValue == "yes") {
this.store.add(new this.store.recordType({
id: item.id,
path: item.fullpath,
type: item.classname
}, this.store.getCount() + 1));
}
}.bind(this, arguments));
} else {
Ext.Ajax.request({
url: "/admin/element/lock-element",
params: {id: item.id, type: 'object'}
});
this.store.add(new this.store.recordType({
id: item.id,
path: item.fullpath,
type: item.classname
}, this.store.getCount() + 1));
}
}.bind(this, item)
});
} else {
var lockDetails = "<br /><br />" + t("element_implicit_edit_question");
Ext.MessageBox.confirm(t("element_is_open"), t("element_open_message") + lockDetails,
function (item, buttonValue) {
if (buttonValue == "yes") {
this.store.add(new this.store.recordType({
id: item.id,
path: item.fullpath,
type: item.classname
}, this.store.getCount() + 1));
}
}.bind(this, item));
}
},
addDataFromSelector: function (items) {
if (this.object.id == items.id) {
//cannot select myself!
Ext.MessageBox.show({
title:t('error'),
msg: t('nonownerobjects_self_selection'),
buttons: Ext.Msg.OK ,
icon: Ext.MessageBox.ERROR
});
} else if (!this.objectAlreadyExists(items.id)) {
this.addObject(items);
}
}
}); | PatidarWeb/pimcore | pimcore/static/js/pimcore/object/tags/nonownerobjects.js | JavaScript | bsd-3-clause | 14,021 |
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.Object}
* @implements {WebInspector.ContentProvider}
* @param {string} scriptId
* @param {string} sourceURL
* @param {number} startLine
* @param {number} startColumn
* @param {number} endLine
* @param {number} endColumn
* @param {boolean} isContentScript
* @param {string=} sourceMapURL
* @param {boolean=} hasSourceURL
*/
WebInspector.Script = function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL)
{
this.scriptId = scriptId;
this.sourceURL = sourceURL;
this.lineOffset = startLine;
this.columnOffset = startColumn;
this.endLine = endLine;
this.endColumn = endColumn;
this.isContentScript = isContentScript;
this.sourceMapURL = sourceMapURL;
this.hasSourceURL = hasSourceURL;
this._locations = new Set();
this._sourceMappings = [];
}
WebInspector.Script.Events = {
ScriptEdited: "ScriptEdited",
}
WebInspector.Script.snippetSourceURLPrefix = "snippets:///";
WebInspector.Script.prototype = {
/**
* @return {string}
*/
contentURL: function()
{
return this.sourceURL;
},
/**
* @return {WebInspector.ResourceType}
*/
contentType: function()
{
return WebInspector.resourceTypes.Script;
},
/**
* @param {function(?string,boolean,string)} callback
*/
requestContent: function(callback)
{
if (this._source) {
callback(this._source, false, "text/javascript");
return;
}
/**
* @this {WebInspector.Script}
* @param {?Protocol.Error} error
* @param {string} source
*/
function didGetScriptSource(error, source)
{
this._source = error ? "" : source;
callback(this._source, false, "text/javascript");
}
if (this.scriptId) {
// Script failed to parse.
DebuggerAgent.getScriptSource(this.scriptId, didGetScriptSource.bind(this));
} else
callback("", false, "text/javascript");
},
/**
* @param {string} query
* @param {boolean} caseSensitive
* @param {boolean} isRegex
* @param {function(Array.<PageAgent.SearchMatch>)} callback
*/
searchInContent: function(query, caseSensitive, isRegex, callback)
{
/**
* @this {WebInspector.Script}
* @param {?Protocol.Error} error
* @param {Array.<PageAgent.SearchMatch>} searchMatches
*/
function innerCallback(error, searchMatches)
{
if (error)
console.error(error);
var result = [];
for (var i = 0; i < searchMatches.length; ++i) {
var searchMatch = new WebInspector.ContentProvider.SearchMatch(searchMatches[i].lineNumber, searchMatches[i].lineContent);
result.push(searchMatch);
}
callback(result || []);
}
if (this.scriptId) {
// Script failed to parse.
DebuggerAgent.searchInContent(this.scriptId, query, caseSensitive, isRegex, innerCallback.bind(this));
} else
callback([]);
},
/**
* @param {string} newSource
* @param {function(?Protocol.Error, DebuggerAgent.SetScriptSourceError=, Array.<DebuggerAgent.CallFrame>=)} callback
*/
editSource: function(newSource, callback)
{
/**
* @this {WebInspector.Script}
* @param {?Protocol.Error} error
* @param {DebuggerAgent.SetScriptSourceError=} errorData
* @param {Array.<DebuggerAgent.CallFrame>=} callFrames
* @param {Object=} debugData
*/
function didEditScriptSource(error, errorData, callFrames, debugData)
{
// FIXME: support debugData.stack_update_needs_step_in flag by calling WebInspector.debugger_model.callStackModified
if (!error)
this._source = newSource;
callback(error, errorData, callFrames);
if (!error)
this.dispatchEventToListeners(WebInspector.Script.Events.ScriptEdited, newSource);
}
if (this.scriptId) {
// Script failed to parse.
DebuggerAgent.setScriptSource(this.scriptId, newSource, undefined, didEditScriptSource.bind(this));
} else
callback("Script failed to parse");
},
/**
* @return {boolean}
*/
isInlineScript: function()
{
var startsAtZero = !this.lineOffset && !this.columnOffset;
return !!this.sourceURL && !startsAtZero;
},
/**
* @return {boolean}
*/
isAnonymousScript: function()
{
return !this.sourceURL;
},
/**
* @return {boolean}
*/
isSnippet: function()
{
return this.sourceURL && this.sourceURL.startsWith(WebInspector.Script.snippetSourceURLPrefix);
},
/**
* @param {number} lineNumber
* @param {number=} columnNumber
* @return {WebInspector.UILocation}
*/
rawLocationToUILocation: function(lineNumber, columnNumber)
{
var uiLocation;
var rawLocation = new WebInspector.DebuggerModel.Location(this.scriptId, lineNumber, columnNumber || 0);
for (var i = this._sourceMappings.length - 1; !uiLocation && i >= 0; --i)
uiLocation = this._sourceMappings[i].rawLocationToUILocation(rawLocation);
console.assert(uiLocation, "Script raw location can not be mapped to any ui location.");
return uiLocation.uiSourceCode.overrideLocation(uiLocation);
},
/**
* @param {WebInspector.SourceMapping} sourceMapping
*/
pushSourceMapping: function(sourceMapping)
{
this._sourceMappings.push(sourceMapping);
this.updateLocations();
},
updateLocations: function()
{
var items = this._locations.items();
for (var i = 0; i < items.length; ++i)
items[i].update();
},
/**
* @param {WebInspector.DebuggerModel.Location} rawLocation
* @param {function(WebInspector.UILocation):(boolean|undefined)} updateDelegate
* @return {WebInspector.Script.Location}
*/
createLiveLocation: function(rawLocation, updateDelegate)
{
console.assert(rawLocation.scriptId === this.scriptId);
var location = new WebInspector.Script.Location(this, rawLocation, updateDelegate);
this._locations.add(location);
location.update();
return location;
},
__proto__: WebInspector.Object.prototype
}
/**
* @constructor
* @extends {WebInspector.LiveLocation}
* @param {WebInspector.Script} script
* @param {WebInspector.DebuggerModel.Location} rawLocation
* @param {function(WebInspector.UILocation):(boolean|undefined)} updateDelegate
*/
WebInspector.Script.Location = function(script, rawLocation, updateDelegate)
{
WebInspector.LiveLocation.call(this, rawLocation, updateDelegate);
this._script = script;
}
WebInspector.Script.Location.prototype = {
/**
* @return {WebInspector.UILocation}
*/
uiLocation: function()
{
var debuggerModelLocation = /** @type {WebInspector.DebuggerModel.Location} */ (this.rawLocation());
return this._script.rawLocationToUILocation(debuggerModelLocation.lineNumber, debuggerModelLocation.columnNumber);
},
dispose: function()
{
WebInspector.LiveLocation.prototype.dispose.call(this);
this._script._locations.remove(this);
},
__proto__: WebInspector.LiveLocation.prototype
}
| espadrine/opera | chromium/src/third_party/WebKit/Source/devtools/front_end/Script.js | JavaScript | bsd-3-clause | 8,934 |
Drawable.Transition = function(transition_obj, target_paper, readonly, drawings, highlight, outline, path_type, color) {
var that = this;
var paper = target_paper;
var transition_colors = ['#998', '#99f', '#9d9', '#faa'];
var transition_text_colors = ['#554', '#559', '#585', '#966'];
var transition_highlight_color = '#FC5'
var resetTransition = function() {
if (RC.Controller.isReadonly()) return;
UI.Statemachine.resetTransition(transition_obj);
}
var text_color = color;
if (outline) {
color = '#EEE';
} else if (color == undefined) {
color = highlight? transition_highlight_color : transition_colors[Math.max(0, transition_obj.getAutonomy())];
text_color = transition_text_colors[Math.max(0, transition_obj.getAutonomy())];
if (transition_obj.getFrom().getStateName() == "INIT") {
color = '#000';
}
}
from = drawings.findElement(function(element) {
return element.obj instanceof State && element.obj.getStateName() == transition_obj.getFrom().getStateName();
}).drawing;
to = transition_obj.getTo()? drawings.findElement(function(element) {
return element.obj instanceof State && element.obj.getStateName() == transition_obj.getTo().getStateName();
}).drawing : UI.Statemachine.getMousePos();
line = undefined;
var bb1 = from.getBBox(),
bb2 = to.getBBox(),
p = [{x: bb1.x + bb1.width / 2, y: bb1.y - 1},
{x: bb1.x + bb1.width / 2, y: bb1.y + bb1.height + 1},
{x: bb1.x - 1, y: bb1.y + bb1.height / 2},
{x: bb1.x + bb1.width + 1, y: bb1.y + bb1.height / 2},
{x: bb2.x + bb2.width / 2, y: bb2.y - 1},
{x: bb2.x + bb2.width / 2, y: bb2.y + bb2.height + 1},
{x: bb2.x - 1, y: bb2.y + bb2.height / 2},
{x: bb2.x + bb2.width + 1, y: bb2.y + bb2.height / 2}],
d = {}, dis = [];
for (var i = 0; i < 4; i++) {
for (var j = 4; j < 8; j++) {
var dx = Math.abs(p[i].x - p[j].x),
dy = Math.abs(p[i].y - p[j].y);
if ((i == j - 4) || (((i != 3 && j != 6) || p[i].x < p[j].x) && ((i != 2 && j != 7) || p[i].x > p[j].x) && ((i != 0 && j != 5) || p[i].y > p[j].y) && ((i != 1 && j != 4) || p[i].y < p[j].y))) {
dis.push(dx + dy);
d[dis[dis.length - 1]] = [i, j];
}
}
}
if (dis.length == 0) {
var res = [0, 4];
} else {
res = d[Math.min.apply(Math, dis)];
}
var x1 = p[res[0]].x,
y1 = p[res[0]].y,
x4 = p[res[1]].x,
y4 = p[res[1]].y;
if (to == from) x1 += 30;
dx = Math.max(Math.abs(x1 - x4) / 2, 10);
dy = Math.max(Math.abs(y1 - y4) / 2, 10);
var keep_ends = UI.Settings.isTransitionModeCentered()
|| UI.Settings.isTransitionModeCombined() && (Math.abs(x1 - x4) < 2 || Math.abs(y1 - y4) < 2);
if (!keep_ends) {
if (transition_obj.getFrom().getStateName() != "INIT") {
if (res[0] <= 1) { // vertical
x1 += (bb1.width / 2) / paper.width * (p[res[1]].x - paper.width / 2);
} else {
y1 += (bb1.height / 2) / paper.height * (p[res[1]].y - paper.height / 2);
}
}
if (res[1] <= 5) { // vertical
x4 += (bb2.width / 2) / paper.width * (p[res[0]].x - paper.width / 2);
} else {
y4 += (bb2.height / 2) / paper.height * (p[res[0]].y - paper.height / 2);
}
}
var x2 = [x1, x1, x1 - dx, x1 + dx][res[0]].toFixed(3),
y2 = [y1 - dy, y1 + dy, y1, y1][res[0]].toFixed(3),
x3 = [0, 0, 0, 0, x4, x4, x4 - dx, x4 + dx][res[1]].toFixed(3),
y3 = [0, 0, 0, 0, y1 + dy, y1 - dy, y4, y4][res[1]].toFixed(3);
var path;
if (path_type == Drawable.Transition.PATH_CURVE) {
path = ["M", x1.toFixed(3), y1.toFixed(3), "C", x2, y2, x3, y3, x4.toFixed(3), y4.toFixed(3)].join(",");
} else {
path = ["M", x1.toFixed(3), y1.toFixed(3), "L", x4.toFixed(3), y4.toFixed(3)].join(",");
}
var line = paper.path(path)
.attr({stroke: color, fill: "none", 'arrow-end': 'classic-wide-long', 'stroke-width': highlight? 4 : 2});
if (!readonly) line
.attr({'cursor': 'pointer'})
.data("transition", transition_obj)
.click(resetTransition);
if (outline) line
.toBack();
var set_obj = paper.set();
set_obj.push(line);
var text_set = paper.set();
var bbox = line.getBBox();
if (transition_obj.getOutcome() && !outline) {
var text_obj = paper.text(bbox.x + bbox.width / 2 + 10, bbox.y + bbox.height / 2, transition_obj.getOutcome())
.attr({'font-size': 10, stroke: 'none', 'font-family': 'Arial,Helvetica,sans-serif', 'font-weight': 400, fill: text_color});
if (!readonly) text_obj
.attr({'cursor': 'pointer'})
.data("transition", transition_obj)
.click(resetTransition);
var textbb = text_obj.getBBox();
var text_bg = paper.ellipse(textbb.x - 7 + (textbb.width + 14) / 2,
textbb.y - 3 + (textbb.height + 6) / 2,
(textbb.width + 14) / 2,
(textbb.height + 6) / 2)
.attr({'fill': 'rgba(100%, 100%, 100%, 80%)', 'stroke': color});
text_obj.toFront();
text_set.push(text_obj);
text_set.push(text_bg);
}
text_set.attr();
set_obj.push(text_set);
this.drawing = set_obj;
this.obj = transition_obj;
var merge_server = that;
var merge_clients = [];
this.merge = function(other) {
var target = (that.obj.getAutonomy() < other.obj.getAutonomy())? that.getMergeServer() : other.getMergeServer();
var remove = (that.obj.getAutonomy() >= other.obj.getAutonomy())? that.getMergeServer() : other.getMergeServer();
if (target == remove) return;
var remove_shift_height = remove.calcShiftHeight();
var target_shift_height = target.calcShiftHeight();
remove.drawing[0].attr({opacity: 0}).unclick();
target.drawing[1].translate(0, - remove_shift_height);
target.getMergeClients().forEach(function(c) { c.drawing[1].translate(0, - remove_shift_height); });
remove.setMergeServer(target);
var new_clients = remove.getMergeClients();
new_clients.push(remove);
new_clients.forEach(function(c) {
c.drawing[1].translate(0, target_shift_height);
if (c.drawing[1][1] != undefined) {
c.drawing[1][1].toFront();
c.drawing[1][0].toFront();
}
});
target.concatMergeClients(new_clients);
remove.resetMergeClients();
}
this.getMergeServer = function() {
return merge_server;
}
this.setMergeServer = function(new_server) {
merge_server = new_server;
}
this.getMergeClients = function() {
return merge_clients;
}
this.concatMergeClients = function(new_clients) {
merge_clients = merge_clients.concat(new_clients);
}
this.resetMergeClients = function() {
merge_clients = [];
}
this.calcShiftHeight = function() {
return (that.drawing[1].getBBox().height + merge_clients.reduce(function(h, c) {
return h + c.drawing[1].getBBox().height;
}, 0)) / 2 + 1;
}
};
Drawable.Transition.PATH_CURVE = 0;
Drawable.Transition.PATH_STRAIGHT = 1; | FlexBE/flexbe_app | src/drawable/drawable_transition.js | JavaScript | bsd-3-clause | 6,576 |
/*
Copyright (c) 2011-2012, Mozilla Foundation
Copyright (c) 2011-2012, Alan Kligman
Copyright (c) 2011-2012, Robert Richter
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Mozilla Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function( root, factory ) {
if ( typeof exports === "object" ) {
// Node
module.exports = factory();
} else if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define( factory );
} else if( !root.Gladius ) {
// Browser globals
root.Gladius = factory();
}
}( this, function() {
/**
* almond 0.0.3 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
/*jslint strict: false, plusplus: false */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var defined = {},
waiting = {},
aps = [].slice,
main, req;
if (typeof define === "function") {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
//Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
baseName = baseName.split("/");
baseName = baseName.slice(0, baseName.length - 1);
name = baseName.concat(name.split("/"));
//start trimDots
var i, part;
for (i = 0; (part = name[i]); i++) {
if (part === ".") {
name.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (name[2] === '..' || name[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join("/");
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (waiting.hasOwnProperty(name)) {
var args = waiting[name];
delete waiting[name];
main.apply(undef, args);
}
return defined[name];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
function makeMap(name, relName) {
var prefix, plugin,
index = name.indexOf('!');
if (index !== -1) {
prefix = normalize(name.slice(0, index), relName);
name = name.slice(index + 1);
plugin = callDep(prefix);
//Normalize according
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
} else {
name = normalize(name, relName);
}
} else {
name = normalize(name, relName);
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
p: plugin
};
}
main = function (name, deps, callback, relName) {
var args = [],
usingExports,
cjsModule, depName, i, ret, map;
//Use name if no relName
if (!relName) {
relName = name;
}
//Call the callback to define the module, if necessary.
if (typeof callback === 'function') {
//Default to require, exports, module if no deps if
//the factory arg has any arguments specified.
if (!deps.length && callback.length) {
deps = ['require', 'exports', 'module'];
}
//Pull out the defined dependencies and pass the ordered
//values to the callback.
for (i = 0; i < deps.length; i++) {
map = makeMap(deps[i], relName);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = makeRequire(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = defined[name] = {};
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = {
id: name,
uri: '',
exports: defined[name]
};
} else if (defined.hasOwnProperty(depName) || waiting.hasOwnProperty(depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw name + ' missing ' + depName;
}
}
ret = callback.apply(defined[name], args);
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef) {
defined[name] = cjsModule.exports;
} else if (!usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = req = function (deps, callback, relName, forceSync) {
if (typeof deps === "string") {
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
//Drop the config stuff on the ground.
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = arguments[2];
} else {
deps = [];
}
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
setTimeout(function () {
main(undef, deps, callback, relName);
}, 15);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function () {
return req;
};
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
define = function (name, deps, callback) {
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (define.unordered) {
waiting[name] = [name, deps, callback];
} else {
main(name, deps, callback);
}
};
define.amd = {
jQuery: true
};
}());
define("../tools/almond", function(){});
/**
* @license
* Copyright (c) 2011, Mozilla Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Mozilla Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (root, factory) {
if ( typeof exports === 'object' ) {
// Node
module.exports = factory();
} else if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define('_math',[],factory);
} else if ( !root._Math ) {
// Browser globals
root._Math = factory();
}
}(this, function () {
/**
* almond 0.0.3 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
/*jslint strict: false, plusplus: false */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var defined = {},
waiting = {},
aps = [].slice,
main, req;
if (typeof define === "function") {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
//Convert baseName to array, and lop off the last part,
//so that . matches that "directory" and not name of the baseName's
//module. For instance, baseName of "one/two/three", maps to
//"one/two/three.js", but we want the directory, "one/two" for
//this normalization.
baseName = baseName.split("/");
baseName = baseName.slice(0, baseName.length - 1);
name = baseName.concat(name.split("/"));
//start trimDots
var i, part;
for (i = 0; (part = name[i]); i++) {
if (part === ".") {
name.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (name[2] === '..' || name[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join("/");
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (waiting.hasOwnProperty(name)) {
var args = waiting[name];
delete waiting[name];
main.apply(undef, args);
}
return defined[name];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
function makeMap(name, relName) {
var prefix, plugin,
index = name.indexOf('!');
if (index !== -1) {
prefix = normalize(name.slice(0, index), relName);
name = name.slice(index + 1);
plugin = callDep(prefix);
//Normalize according
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
} else {
name = normalize(name, relName);
}
} else {
name = normalize(name, relName);
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
p: plugin
};
}
main = function (name, deps, callback, relName) {
var args = [],
usingExports,
cjsModule, depName, i, ret, map;
//Use name if no relName
if (!relName) {
relName = name;
}
//Call the callback to define the module, if necessary.
if (typeof callback === 'function') {
//Default to require, exports, module if no deps if
//the factory arg has any arguments specified.
if (!deps.length && callback.length) {
deps = ['require', 'exports', 'module'];
}
//Pull out the defined dependencies and pass the ordered
//values to the callback.
for (i = 0; i < deps.length; i++) {
map = makeMap(deps[i], relName);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = makeRequire(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = defined[name] = {};
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = {
id: name,
uri: '',
exports: defined[name]
};
} else if (defined.hasOwnProperty(depName) || waiting.hasOwnProperty(depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw name + ' missing ' + depName;
}
}
ret = callback.apply(defined[name], args);
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef) {
defined[name] = cjsModule.exports;
} else if (!usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = req = function (deps, callback, relName, forceSync) {
if (typeof deps === "string") {
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
//Drop the config stuff on the ground.
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = arguments[2];
} else {
deps = [];
}
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
setTimeout(function () {
main(undef, deps, callback, relName);
}, 15);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function () {
return req;
};
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
define = function (name, deps, callback) {
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (define.unordered) {
waiting[name] = [name, deps, callback];
} else {
main(name, deps, callback);
}
};
define.amd = {
jQuery: true
};
}());
define("../tools/almond", function(){});
define('constants',['require'],function ( require ) {
return {
TAU: 2 * Math.PI,
PI: Math.PI
};
});
define('equal',['require'],function ( require ) {
function equal( arg1, arg2, e ) {
e = e || 0.000001;
return Math.abs( arg1 - arg2 ) < e;
}
return equal;
});
define('vector/v',['require'],function ( require ) {
var V = function() {
};
return V;
});
define('vector/v2',['require','vector/v'],function ( require ) {
var V = require( "vector/v" );
return function( FLOAT_ARRAY_TYPE ) {
var V2 = function() {
var argc = arguments.length;
var i, j, vi = 0;
var vector = new FLOAT_ARRAY_TYPE( 2 );
for( i = 0; i < argc && vi < 2; ++ i ) {
var arg = arguments[i];
if( arg === undefined ) {
break;
} else if( arg instanceof Array ||
arg instanceof FLOAT_ARRAY_TYPE ) {
for( j = 0; j < arg.length && vi < 2; ++ j ) {
vector[vi ++] = arg[j];
}
} else {
vector[vi ++] = arg;
}
}
// Fill in missing elements with zero
for( ; vi < 2; ++ vi ) {
vector[vi] = 0;
}
return vector;
};
V2.prototype = new V();
V2.prototype.constructor = V2;
return V2;
};
});
/*!
* Lo-Dash v0.4.1 <http://lodash.com>
* Copyright 2012 John-David Dalton <http://allyoucanleet.com/>
* Based on Underscore.js 1.3.3, copyright 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
* <http://documentcloud.github.com/underscore>
* Available under MIT license <http://lodash.com/license>
*/
;(function(window, undefined) {
/**
* Used to cache the last `_.templateSettings.evaluate` delimiter to avoid
* unnecessarily assigning `reEvaluateDelimiter` a new generated regexp.
* Assigned in `_.template`.
*/
var lastEvaluateDelimiter;
/**
* Used to cache the last template `options.variable` to avoid unnecessarily
* assigning `reDoubleVariable` a new generated regexp. Assigned in `_.template`.
*/
var lastVariable;
/**
* Used to match potentially incorrect data object references, like `obj.obj`,
* in compiled templates. Assigned in `_.template`.
*/
var reDoubleVariable;
/**
* Used to match "evaluate" delimiters, including internal delimiters,
* in template text. Assigned in `_.template`.
*/
var reEvaluateDelimiter;
/** Detect free variable `exports` */
var freeExports = typeof exports == 'object' && exports &&
(typeof global == 'object' && global && global == global.global && (window = global), exports);
/** Native prototype shortcuts */
var ArrayProto = Array.prototype,
ObjectProto = Object.prototype;
/** Used to generate unique IDs */
var idCounter = 0;
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = window._;
/** Used to detect delimiter values that should be processed by `tokenizeEvaluate` */
var reComplexDelimiter = /[-+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/;
/** Used to match empty string literals in compiled template source */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to insert the data object variable into compiled template source */
var reInsertVariable = /(?:__e|__t = )\(\s*(?![\d\s"']|this\.)/g;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
(ObjectProto.valueOf + '')
.replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&')
.replace(/valueOf|for [^\]]+/g, '.+?') + '$'
);
/** Used to match tokens in template text */
var reToken = /__token__(\d+)/g;
/** Used to match unescaped characters in strings for inclusion in HTML */
var reUnescapedHtml = /[&<"']/g;
/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
/** Used to fix the JScript [[DontEnum]] bug */
var shadowed = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used to make template sourceURLs easier to identify */
var templateCounter = 0;
/** Used to replace template delimiters */
var token = '__token__';
/** Used to store tokenized template text snippets */
var tokenized = [];
/** Native method shortcuts */
var concat = ArrayProto.concat,
hasOwnProperty = ObjectProto.hasOwnProperty,
push = ArrayProto.push,
propertyIsEnumerable = ObjectProto.propertyIsEnumerable,
slice = ArrayProto.slice,
toString = ObjectProto.toString;
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind,
nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
nativeIsFinite = window.isFinite,
nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys;
/** `Object#toString` result shortcuts */
var arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
funcClass = '[object Function]',
numberClass = '[object Number]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Timer shortcuts */
var clearTimeout = window.clearTimeout,
setTimeout = window.setTimeout;
/**
* Detect the JScript [[DontEnum]] bug:
* In IE < 9 an objects own properties, shadowing non-enumerable ones, are
* made non-enumerable as well.
*/
var hasDontEnumBug = !propertyIsEnumerable.call({ 'valueOf': 0 }, 'valueOf');
/** Detect if `Array#slice` cannot be used to convert strings to arrays (e.g. Opera < 10.52) */
var noArraySliceOnStrings = slice.call('x')[0] != 'x';
/**
* Detect lack of support for accessing string characters by index:
* IE < 8 can't access characters by index and IE 8 can only access
* characters by index on string literals.
*/
var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx';
/* Detect if `Function#bind` exists and is inferred to be fast (i.e. all but V8) */
var isBindFast = nativeBind && /\n|Opera/.test(nativeBind + toString.call(window.opera));
/* Detect if `Object.keys` exists and is inferred to be fast (i.e. V8, Opera, IE) */
var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent);
/** Detect if sourceURL syntax is usable without erroring */
try {
// Adobe's and Narwhal's JS engines will error
var useSourceURL = (Function('//@')(), true);
} catch(e){ }
/**
* Used to escape characters for inclusion in HTML.
* The `>` and `/` characters don't require escaping in HTML and have no
* special meaning unless they're part of a tag or an unquoted attribute value
* http://mathiasbynens.be/notes/ambiguous-ampersands (semi-related fun fact)
*/
var htmlEscapes = {
'&': '&',
'<': '<',
'"': '"',
"'": '''
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/*--------------------------------------------------------------------------*/
/**
* The `lodash` function.
*
* @name _
* @constructor
* @param {Mixed} value The value to wrap in a `LoDash` instance.
* @returns {Object} Returns a `LoDash` instance.
*/
function lodash(value) {
// allow invoking `lodash` without the `new` operator
return new LoDash(value);
}
/**
* Creates a `LoDash` instance that wraps a value to allow chaining.
*
* @private
* @constructor
* @param {Mixed} value The value to wrap.
*/
function LoDash(value) {
// exit early if already wrapped
if (value && value._wrapped) {
return value;
}
this._wrapped = value;
}
/**
* By default, Lo-Dash uses embedded Ruby (ERB) style template delimiters,
* change the following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': /<%-([\s\S]+?)%>/g,
/**
* Used to detect code to be evaluated.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': /<%([\s\S]+?)%>/g,
/**
* Used to detect `data` property values to inject.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': /<%=([\s\S]+?)%>/g,
/**
* Used to reference the data object in the template text.
*
* @static
* @memberOf _.templateSettings
* @type String
*/
'variable': 'obj'
};
/*--------------------------------------------------------------------------*/
/**
* The template used to create iterator functions.
*
* @private
* @param {Obect} data The data object used to populate the text.
* @returns {String} Returns the interpolated text.
*/
var iteratorTemplate = template(
// assign the `result` variable an initial value
'var result<% if (init) { %> = <%= init %><% } %>;\n' +
// add code to exit early or do so if the first argument is falsey
'<%= exit %>;\n' +
// add code after the exit snippet but before the iteration branches
'<%= top %>;\n' +
'var index, iteratee = <%= iteratee %>;\n' +
// the following branch is for iterating arrays and array-like objects
'<% if (arrayBranch) { %>' +
'var length = iteratee.length; index = -1;' +
' <% if (objectBranch) { %>\nif (length === length >>> 0) {<% } %>' +
// add support for accessing string characters by index if needed
' <% if (noCharByIndex) { %>\n' +
' if (toString.call(iteratee) == stringClass) {\n' +
' iteratee = iteratee.split(\'\')\n' +
' }' +
' <% } %>\n' +
' <%= arrayBranch.beforeLoop %>;\n' +
' while (++index < length) {\n' +
' <%= arrayBranch.inLoop %>\n' +
' }' +
' <% if (objectBranch) { %>\n}<% } %>' +
'<% } %>' +
// the following branch is for iterating an object's own/inherited properties
'<% if (objectBranch) { %>' +
' <% if (arrayBranch) { %>\nelse {<% } %>' +
' <% if (!hasDontEnumBug) { %>\n' +
' var skipProto = typeof iteratee == \'function\' && \n' +
' propertyIsEnumerable.call(iteratee, \'prototype\');\n' +
' <% } %>' +
// iterate own properties using `Object.keys` if it's fast
' <% if (isKeysFast && useHas) { %>\n' +
' var props = nativeKeys(iteratee),\n' +
' propIndex = -1,\n' +
' length = props.length;\n\n' +
' <%= objectBranch.beforeLoop %>;\n' +
' while (++propIndex < length) {\n' +
' index = props[propIndex];\n' +
' if (!(skipProto && index == \'prototype\')) {\n' +
' <%= objectBranch.inLoop %>\n' +
' }\n' +
' }' +
// else using a for-in loop
' <% } else { %>\n' +
' <%= objectBranch.beforeLoop %>;\n' +
' for (index in iteratee) {' +
' <% if (hasDontEnumBug) { %>\n' +
' <% if (useHas) { %>if (hasOwnProperty.call(iteratee, index)) {\n <% } %>' +
' <%= objectBranch.inLoop %>;\n' +
' <% if (useHas) { %>}<% } %>' +
' <% } else { %>\n' +
// Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
// (if the prototype or a property on the prototype has been set)
// incorrectly sets a function's `prototype` property [[Enumerable]]
// value to `true`. Because of this Lo-Dash standardizes on skipping
// the the `prototype` property of functions regardless of its
// [[Enumerable]] value.
' if (!(skipProto && index == \'prototype\')<% if (useHas) { %> &&\n' +
' hasOwnProperty.call(iteratee, index)<% } %>) {\n' +
' <%= objectBranch.inLoop %>\n' +
' }' +
' <% } %>\n' +
' }' +
' <% } %>' +
// Because IE < 9 can't set the `[[Enumerable]]` attribute of an
// existing property and the `constructor` property of a prototype
// defaults to non-enumerable, Lo-Dash skips the `constructor`
// property when it infers it's iterating over a `prototype` object.
' <% if (hasDontEnumBug) { %>\n\n' +
' var ctor = iteratee.constructor;\n' +
' <% for (var k = 0; k < 7; k++) { %>\n' +
' index = \'<%= shadowed[k] %>\';\n' +
' if (<%' +
' if (shadowed[k] == \'constructor\') {' +
' %>!(ctor && ctor.prototype === iteratee) && <%' +
' } %>hasOwnProperty.call(iteratee, index)) {\n' +
' <%= objectBranch.inLoop %>\n' +
' }' +
' <% } %>' +
' <% } %>' +
' <% if (arrayBranch) { %>\n}<% } %>' +
'<% } %>\n' +
// add code to the bottom of the iteration function
'<%= bottom %>;\n' +
// finally, return the `result`
'return result'
);
/**
* Reusable iterator options shared by
* `every`, `filter`, `find`, `forEach`, `forIn`, `forOwn`, `groupBy`, `map`,
* `reject`, `some`, and `sortBy`.
*/
var baseIteratorOptions = {
'args': 'collection, callback, thisArg',
'init': 'collection',
'top':
'if (!callback) {\n' +
' callback = identity\n' +
'}\n' +
'else if (thisArg) {\n' +
' callback = iteratorBind(callback, thisArg)\n' +
'}',
'inLoop': 'callback(iteratee[index], index, collection)'
};
/** Reusable iterator options for `every` and `some` */
var everyIteratorOptions = {
'init': 'true',
'inLoop': 'if (!callback(iteratee[index], index, collection)) return !result'
};
/** Reusable iterator options for `defaults` and `extend` */
var extendIteratorOptions = {
'args': 'object',
'init': 'object',
'top':
'for (var source, sourceIndex = 1, length = arguments.length; sourceIndex < length; sourceIndex++) {\n' +
' source = arguments[sourceIndex];\n' +
(hasDontEnumBug ? ' if (source) {' : ''),
'iteratee': 'source',
'useHas': false,
'inLoop': 'result[index] = iteratee[index]',
'bottom': (hasDontEnumBug ? ' }\n' : '') + '}'
};
/** Reusable iterator options for `filter` and `reject` */
var filterIteratorOptions = {
'init': '[]',
'inLoop': 'callback(iteratee[index], index, collection) && result.push(iteratee[index])'
};
/** Reusable iterator options for `find`, `forEach`, `forIn`, and `forOwn` */
var forEachIteratorOptions = {
'top': 'if (thisArg) callback = iteratorBind(callback, thisArg)'
};
/** Reusable iterator options for `forIn` and `forOwn` */
var forOwnIteratorOptions = {
'inLoop': {
'object': baseIteratorOptions.inLoop
}
};
/** Reusable iterator options for `invoke`, `map`, `pluck`, and `sortBy` */
var mapIteratorOptions = {
'init': '',
'exit': 'if (!collection) return []',
'beforeLoop': {
'array': 'result = Array(length)',
'object': 'result = ' + (isKeysFast ? 'Array(length)' : '[]')
},
'inLoop': {
'array': 'result[index] = callback(iteratee[index], index, collection)',
'object': 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '(callback(iteratee[index], index, collection))'
}
};
/*--------------------------------------------------------------------------*/
/**
* Creates compiled iteration functions. The iteration function will be created
* to iterate over only objects if the first argument of `options.args` is
* "object" or `options.inLoop.array` is falsey.
*
* @private
* @param {Object} [options1, options2, ...] The compile options objects.
*
* args - A string of comma separated arguments the iteration function will
* accept.
*
* init - A string to specify the initial value of the `result` variable.
*
* exit - A string of code to use in place of the default exit-early check
* of `if (!arguments[0]) return result`.
*
* top - A string of code to execute after the exit-early check but before
* the iteration branches.
*
* beforeLoop - A string or object containing an "array" or "object" property
* of code to execute before the array or object loops.
*
* iteratee - A string or object containing an "array" or "object" property
* of the variable to be iterated in the loop expression.
*
* useHas - A boolean to specify whether or not to use `hasOwnProperty` checks
* in the object loop.
*
* inLoop - A string or object containing an "array" or "object" property
* of code to execute in the array or object loops.
*
* bottom - A string of code to execute after the iteration branches but
* before the `result` is returned.
*
* @returns {Function} Returns the compiled function.
*/
function createIterator() {
var object,
prop,
value,
index = -1,
length = arguments.length;
// merge options into a template data object
var data = {
'bottom': '',
'exit': '',
'init': '',
'top': '',
'arrayBranch': { 'beforeLoop': '' },
'objectBranch': { 'beforeLoop': '' }
};
while (++index < length) {
object = arguments[index];
for (prop in object) {
value = (value = object[prop]) == null ? '' : value;
// keep this regexp explicit for the build pre-process
if (/beforeLoop|inLoop/.test(prop)) {
if (typeof value == 'string') {
value = { 'array': value, 'object': value };
}
data.arrayBranch[prop] = value.array;
data.objectBranch[prop] = value.object;
} else {
data[prop] = value;
}
}
}
// set additional template `data` values
var args = data.args,
firstArg = /^[^,]+/.exec(args)[0],
iteratee = (data.iteratee = data.iteratee || firstArg);
data.firstArg = firstArg;
data.hasDontEnumBug = hasDontEnumBug;
data.isKeysFast = isKeysFast;
data.shadowed = shadowed;
data.useHas = data.useHas !== false;
if (!('noCharByIndex' in data)) {
data.noCharByIndex = noCharByIndex;
}
if (!data.exit) {
data.exit = 'if (!' + firstArg + ') return result';
}
if (firstArg != 'collection' || !data.arrayBranch.inLoop) {
data.arrayBranch = null;
}
// create the function factory
var factory = Function(
'arrayClass, compareAscending, funcClass, hasOwnProperty, identity, ' +
'iteratorBind, objectTypes, nativeKeys, propertyIsEnumerable, ' +
'slice, stringClass, toString',
' return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}'
);
// return the compiled function
return factory(
arrayClass, compareAscending, funcClass, hasOwnProperty, identity,
iteratorBind, objectTypes, nativeKeys, propertyIsEnumerable, slice,
stringClass, toString
);
}
/**
* Used by `sortBy` to compare transformed values of `collection`, sorting
* them in ascending order.
*
* @private
* @param {Object} a The object to compare to `b`.
* @param {Object} b The object to compare to `a`.
* @returns {Number} Returns `-1` if `a` < `b`, `0` if `a` == `b`, or `1` if `a` > `b`.
*/
function compareAscending(a, b) {
a = a.criteria;
b = b.criteria;
if (a === undefined) {
return 1;
}
if (b === undefined) {
return -1;
}
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* Used by `template` to replace tokens with their corresponding code snippets.
*
* @private
* @param {String} match The matched token.
* @param {String} index The `tokenized` index of the code snippet.
* @returns {String} Returns the code snippet.
*/
function detokenize(match, index) {
return tokenized[index];
}
/**
* Used by `template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeStringChar(match) {
return '\\' + stringEscapes[match];
}
/**
* Used by `escape` to escape characters for inclusion in HTML.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeHtmlChar(match) {
return htmlEscapes[match];
}
/**
* Creates a new function that, when called, invokes `func` with the `this`
* binding of `thisArg` and the arguments (value, index, object).
*
* @private
* @param {Function} func The function to bind.
* @param {Mixed} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new bound function.
*/
function iteratorBind(func, thisArg) {
return function(value, index, object) {
return func.call(thisArg, value, index, object);
};
}
/**
* A no-operation function.
*
* @private
*/
function noop() {
// no operation performed
}
/**
* A shim implementation of `Object.keys` that produces an array of the given
* object's own enumerable property names.
*
* @private
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names.
*/
var shimKeys = createIterator({
'args': 'object',
'exit': 'if (!(object && objectTypes[typeof object])) throw TypeError()',
'init': '[]',
'inLoop': 'result.push(index)'
});
/**
* Used by `template` to replace "escape" template delimiters with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeEscape(match, value) {
if (reComplexDelimiter.test(value)) {
return '<e%-' + value + '%>';
}
var index = tokenized.length;
tokenized[index] = "' +\n__e(" + value + ") +\n'";
return token + index;
}
/**
* Used by `template` to replace "evaluate" template delimiters, or complex
* "escape" and "interpolate" delimiters, with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @param {String} escapeValue The "escape" delimiter value.
* @param {String} interpolateValue The "interpolate" delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeEvaluate(match, value, escapeValue, interpolateValue) {
var index = tokenized.length;
if (value) {
tokenized[index] = "';\n" + value + ";\n__p += '"
} else if (escapeValue) {
tokenized[index] = "' +\n__e(" + escapeValue + ") +\n'";
} else if (interpolateValue) {
tokenized[index] = "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
return token + index;
}
/**
* Used by `template` to replace "interpolate" template delimiters with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeInterpolate(match, value) {
if (reComplexDelimiter.test(value)) {
return '<e%=' + value + '%>';
}
var index = tokenized.length;
tokenized[index] = "' +\n((__t = (" + value + ")) == null ? '' : __t) +\n'";
return token + index;
}
/*--------------------------------------------------------------------------*/
/**
* Checks if a given `target` value is present in a `collection` using strict
* equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @alias include
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Mixed} target The value to check for.
* @returns {Boolean} Returns `true` if `target` value is found, else `false`.
* @example
*
* _.contains([1, 2, 3], 3);
* // => true
*
* _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
* // => true
*
* _.contains('curly', 'ur');
* // => true
*/
var contains = createIterator({
'args': 'collection, target',
'init': 'false',
'noCharByIndex': false,
'beforeLoop': {
'array': 'if (toString.call(iteratee) == stringClass) return collection.indexOf(target) > -1'
},
'inLoop': 'if (iteratee[index] === target) return true'
});
/**
* Checks if the `callback` returns a truthy value for **all** elements of a
* `collection`. The `callback` is bound to `thisArg` and invoked with 3
* arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object).
*
* @static
* @memberOf _
* @alias all
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Boolean} Returns `true` if all values pass the callback check, else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*/
var every = createIterator(baseIteratorOptions, everyIteratorOptions);
/**
* Examines each value in a `collection`, returning an array of all values the
* `callback` returns truthy for. The `callback` is bound to `thisArg` and
* invoked with 3 arguments; for arrays they are (value, index, array) and for
* objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values that passed callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*/
var filter = createIterator(baseIteratorOptions, filterIteratorOptions);
/**
* Examines each value in a `collection`, returning the first one the `callback`
* returns truthy for. The function returns as soon as it finds an acceptable
* value, and does not iterate over the entire `collection`. The `callback` is
* bound to `thisArg` and invoked with 3 arguments; for arrays they are
* (value, index, array) and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias detect
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the value that passed the callback check, else `undefined`.
* @example
*
* var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => 2
*/
var find = createIterator(baseIteratorOptions, forEachIteratorOptions, {
'init': '',
'inLoop': 'if (callback(iteratee[index], index, collection)) return iteratee[index]'
});
/**
* Iterates over a `collection`, executing the `callback` for each value in the
* `collection`. The `callback` is bound to `thisArg` and invoked with 3
* arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object).
*
* @static
* @memberOf _
* @alias each
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array|Object} Returns the `collection`.
* @example
*
* _([1, 2, 3]).forEach(alert).join(',');
* // => alerts each number and returns '1,2,3'
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
* // => alerts each number (order is not guaranteed)
*/
var forEach = createIterator(baseIteratorOptions, forEachIteratorOptions);
/**
* Splits `collection` into sets, grouped by the result of running each value
* through `callback`. The `callback` is bound to `thisArg` and invoked with
* 3 arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object). The `callback` argument may also be the name of a
* property to group by.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|String} callback The function called per iteration or
* property name to group by.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Object} Returns an object of grouped values.
* @example
*
* _.groupBy([1.3, 2.1, 2.4], function(num) { return Math.floor(num); });
* // => { '1': [1.3], '2': [2.1, 2.4] }
*
* _.groupBy([1.3, 2.1, 2.4], function(num) { return this.floor(num); }, Math);
* // => { '1': [1.3], '2': [2.1, 2.4] }
*
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createIterator(baseIteratorOptions, {
'init': '{}',
'top':
'var prop, isFunc = typeof callback == \'function\';\n' +
'if (isFunc && thisArg) callback = iteratorBind(callback, thisArg)',
'inLoop':
'prop = isFunc\n' +
' ? callback(iteratee[index], index, collection)\n' +
' : iteratee[index][callback];\n' +
'(hasOwnProperty.call(result, prop) ? result[prop] : result[prop] = []).push(iteratee[index])'
});
/**
* Invokes the method named by `methodName` on each element in the `collection`.
* Additional arguments will be passed to each invoked method. If `methodName`
* is a function it will be invoked for, and `this` bound to, each element
* in the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|String} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
* @returns {Array} Returns a new array of values returned from each invoked method.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invoke = createIterator(mapIteratorOptions, {
'args': 'collection, methodName',
'top':
'var args = slice.call(arguments, 2),\n' +
' isFunc = typeof methodName == \'function\'',
'inLoop': {
'array':
'result[index] = (isFunc ? methodName : iteratee[index][methodName])' +
'.apply(iteratee[index], args)',
'object':
'result' + (isKeysFast ? '[propIndex] = ' : '.push') +
'((isFunc ? methodName : iteratee[index][methodName]).apply(iteratee[index], args))'
}
});
/**
* Produces a new array of values by mapping each element in the `collection`
* through a transformation `callback`. The `callback` is bound to `thisArg`
* and invoked with 3 arguments; for arrays they are (value, index, array)
* and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values returned by the callback.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (order is not guaranteed)
*/
var map = createIterator(baseIteratorOptions, mapIteratorOptions);
/**
* Retrieves the value of a specified property from all elements in
* the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {String} property The property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* _.pluck(stooges, 'name');
* // => ['moe', 'larry', 'curly']
*/
var pluck = createIterator(mapIteratorOptions, {
'args': 'collection, property',
'inLoop': {
'array': 'result[index] = iteratee[index][property]',
'object': 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '(iteratee[index][property])'
}
});
/**
* Boils down a `collection` to a single value. The initial state of the
* reduction is `accumulator` and each successive step of it should be returned
* by the `callback`. The `callback` is bound to `thisArg` and invoked with 4
* arguments; for arrays they are (accumulator, value, index, array) and for
* objects they are (accumulator, value, key, object).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; });
* // => 6
*/
var reduce = createIterator({
'args': 'collection, callback, accumulator, thisArg',
'init': 'accumulator',
'top':
'var noaccum = arguments.length < 3;\n' +
'if (thisArg) callback = iteratorBind(callback, thisArg)',
'beforeLoop': {
'array': 'if (noaccum) result = collection[++index]'
},
'inLoop': {
'array':
'result = callback(result, iteratee[index], index, collection)',
'object':
'result = noaccum\n' +
' ? (noaccum = false, iteratee[index])\n' +
' : callback(result, iteratee[index], index, collection)'
}
});
/**
* The right-associative version of `_.reduce`.
*
* @static
* @memberOf _
* @alias foldr
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var list = [[0, 1], [2, 3], [4, 5]];
* var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, callback, accumulator, thisArg) {
if (!collection) {
return accumulator;
}
var length = collection.length,
noaccum = arguments.length < 3;
if(thisArg) {
callback = iteratorBind(callback, thisArg);
}
if (length === length >>> 0) {
var iteratee = noCharByIndex && toString.call(collection) == stringClass
? collection.split('')
: collection;
if (length && noaccum) {
accumulator = iteratee[--length];
}
while (length--) {
accumulator = callback(accumulator, iteratee[length], length, collection);
}
return accumulator;
}
var prop,
props = keys(collection);
length = props.length;
if (length && noaccum) {
accumulator = collection[props[--length]];
}
while (length--) {
prop = props[length];
accumulator = callback(accumulator, collection[prop], prop, collection);
}
return accumulator;
}
/**
* The opposite of `_.filter`, this method returns the values of a `collection`
* that `callback` does **not** return truthy for.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values that did **not** pass the callback check.
* @example
*
* var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [1, 3, 5]
*/
var reject = createIterator(baseIteratorOptions, filterIteratorOptions, {
'inLoop': '!' + filterIteratorOptions.inLoop
});
/**
* Checks if the `callback` returns a truthy value for **any** element of a
* `collection`. The function returns as soon as it finds passing value, and
* does not iterate over the entire `collection`. The `callback` is bound to
* `thisArg` and invoked with 3 arguments; for arrays they are
* (value, index, array) and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Boolean} Returns `true` if any value passes the callback check, else `false`.
* @example
*
* _.some([null, 0, 'yes', false]);
* // => true
*/
var some = createIterator(baseIteratorOptions, everyIteratorOptions, {
'init': 'false',
'inLoop': everyIteratorOptions.inLoop.replace('!', '')
});
/**
* Produces a new sorted array, sorted in ascending order by the results of
* running each element of `collection` through a transformation `callback`.
* The `callback` is bound to `thisArg` and invoked with 3 arguments;
* for arrays they are (value, index, array) and for objects they are
* (value, key, object). The `callback` argument may also be the name of a
* property to sort by (e.g. 'length').
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|String} callback The function called per iteration or
* property name to sort by.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of sorted values.
* @example
*
* _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
* // => [3, 1, 2]
*
* _.sortBy(['larry', 'brendan', 'moe'], 'length');
* // => ['moe', 'larry', 'brendan']
*/
var sortBy = createIterator(baseIteratorOptions, mapIteratorOptions, {
'top':
'if (typeof callback == \'string\') {\n' +
' var prop = callback;\n' +
' callback = function(collection) { return collection[prop] }\n' +
'}\n' +
'else if (thisArg) {\n' +
' callback = iteratorBind(callback, thisArg)\n' +
'}',
'inLoop': {
'array':
'result[index] = {\n' +
' criteria: callback(iteratee[index], index, collection),\n' +
' value: iteratee[index]\n' +
'}',
'object':
'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '({\n' +
' criteria: callback(iteratee[index], index, collection),\n' +
' value: iteratee[index]\n' +
'})'
},
'bottom':
'result.sort(compareAscending);\n' +
'length = result.length;\n' +
'while (length--) {\n' +
' result[length] = result[length].value\n' +
'}'
});
/**
* Converts the `collection`, into an array. Useful for converting the
* `arguments` object.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to convert.
* @returns {Array} Returns the new converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
* // => [2, 3, 4]
*/
function toArray(collection) {
if (!collection) {
return [];
}
if (collection.toArray && toString.call(collection.toArray) == funcClass) {
return collection.toArray();
}
var length = collection.length;
if (length === length >>> 0) {
return (noArraySliceOnStrings ? toString.call(collection) == stringClass : typeof collection == 'string')
? collection.split('')
: slice.call(collection);
}
return values(collection);
}
/*--------------------------------------------------------------------------*/
/**
* Produces a new array with all falsey values of `array` removed. The values
* `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @returns {Array} Returns a new filtered array.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length;
while (++index < length) {
if (array[index]) {
result.push(array[index]);
}
}
return result;
}
/**
* Produces a new array of `array` values not present in the other arrays
* using strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {Array} [array1, array2, ...] Arrays to check.
* @returns {Array} Returns a new array of `array` values not present in the
* other arrays.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
function difference(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length,
flattened = concat.apply(result, arguments);
while (++index < length) {
if (indexOf(flattened, array[index], length) < 0) {
result.push(array[index]);
}
}
return result;
}
/**
* Gets the first value of the `array`. Pass `n` to return the first `n` values
* of the `array`.
*
* @static
* @memberOf _
* @alias head, take
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Mixed} Returns the first value or an array of the first `n` values
* of `array`.
* @example
*
* _.first([5, 4, 3, 2, 1]);
* // => 5
*/
function first(array, n, guard) {
if (array) {
return (n == null || guard) ? array[0] : slice.call(array, 0, n);
}
}
/**
* Flattens a nested array (the nesting can be to any depth). If `shallow` is
* truthy, `array` will only be flattened a single level.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @param {Boolean} shallow A flag to indicate only flattening a single level.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
*/
function flatten(array, shallow) {
var result = [];
if (!array) {
return result;
}
var value,
index = -1,
length = array.length;
while (++index < length) {
value = array[index];
if (isArray(value)) {
push.apply(result, shallow ? value : flatten(value));
} else {
result.push(value);
}
}
return result;
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`. If the `array` is already
* sorted, passing `true` for `isSorted` will run a faster binary search.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @param {Boolean|Number} [fromIndex=0] The index to start searching from or
* `true` to perform a binary search on a sorted `array`.
* @returns {Number} Returns the index of the matched value or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
if (!array) {
return -1;
}
var index = -1,
length = array.length;
if (fromIndex) {
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? Math.max(0, length + fromIndex) : fromIndex) - 1;
} else {
index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
}
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Gets all but the last value of `array`. Pass `n` to exclude the last `n`
* values from the result.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Array} Returns all but the last value or `n` values of `array`.
* @example
*
* _.initial([3, 2, 1]);
* // => [3, 2]
*/
function initial(array, n, guard) {
if (!array) {
return [];
}
return slice.call(array, 0, -((n == null || guard) ? 1 : n));
}
/**
* Computes the intersection of all the passed-in arrays.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of unique values, in order, that are
* present in **all** of the arrays.
* @example
*
* _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
* // => [1, 2]
*/
function intersection(array) {
var result = [];
if (!array) {
return result;
}
var value,
index = -1,
length = array.length,
others = slice.call(arguments, 1);
while (++index < length) {
value = array[index];
if (indexOf(result, value) < 0 &&
every(others, function(other) { return indexOf(other, value) > -1; })) {
result.push(value);
}
}
return result;
}
/**
* Gets the last value of the `array`. Pass `n` to return the lasy `n` values
* of the `array`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Mixed} Returns the last value or an array of the last `n` values
* of `array`.
* @example
*
* _.last([3, 2, 1]);
* // => 1
*/
function last(array, n, guard) {
if (array) {
var length = array.length;
return (n == null || guard) ? array[length - 1] : slice.call(array, -n || length);
}
}
/**
* Gets the index at which the last occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @param {Number} [fromIndex=array.length-1] The index to start searching from.
* @returns {Number} Returns the index of the matched value or `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
if (!array) {
return -1;
}
var index = array.length;
if (fromIndex && typeof fromIndex == 'number') {
index = (fromIndex < 0 ? Math.max(0, index + fromIndex) : Math.min(fromIndex, index - 1)) + 1;
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Retrieves the maximum value of an `array`. If `callback` is passed,
* it will be executed for each value in the `array` to generate the
* criterion by which the value is ranked. The `callback` is bound to
* `thisArg` and invoked with 3 arguments; (value, index, array).
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to iterate over.
* @param {Function} [callback] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the maximum value.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* _.max(stooges, function(stooge) { return stooge.age; });
* // => { 'name': 'curly', 'age': 60 };
*/
function max(array, callback, thisArg) {
var computed = -Infinity,
result = computed;
if (!array) {
return result;
}
var current,
index = -1,
length = array.length;
if (!callback) {
while (++index < length) {
if (array[index] > result) {
result = array[index];
}
}
return result;
}
if (thisArg) {
callback = iteratorBind(callback, thisArg);
}
while (++index < length) {
current = callback(array[index], index, array);
if (current > computed) {
computed = current;
result = array[index];
}
}
return result;
}
/**
* Retrieves the minimum value of an `array`. If `callback` is passed,
* it will be executed for each value in the `array` to generate the
* criterion by which the value is ranked. The `callback` is bound to `thisArg`
* and invoked with 3 arguments; (value, index, array).
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to iterate over.
* @param {Function} [callback] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the minimum value.
* @example
*
* _.min([10, 5, 100, 2, 1000]);
* // => 2
*/
function min(array, callback, thisArg) {
var computed = Infinity,
result = computed;
if (!array) {
return result;
}
var current,
index = -1,
length = array.length;
if (!callback) {
while (++index < length) {
if (array[index] < result) {
result = array[index];
}
}
return result;
}
if (thisArg) {
callback = iteratorBind(callback, thisArg);
}
while (++index < length) {
current = callback(array[index], index, array);
if (current < computed) {
computed = current;
result = array[index];
}
}
return result;
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to but not including `stop`. This method is a port of Python's
* `range()` function. See http://docs.python.org/library/functions.html#range.
*
* @static
* @memberOf _
* @category Arrays
* @param {Number} [start=0] The start of the range.
* @param {Number} end The end of the range.
* @param {Number} [step=1] The value to increment or descrement by.
* @returns {Array} Returns a new range array.
* @example
*
* _.range(10);
* // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
*
* _.range(1, 11);
* // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*
* _.range(0, 30, 5);
* // => [0, 5, 10, 15, 20, 25]
*
* _.range(0, -10, -1);
* // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
*
* _.range(0);
* // => []
*/
function range(start, end, step) {
step || (step = 1);
if (end == null) {
end = start || 0;
start = 0;
}
// use `Array(length)` so V8 will avoid the slower "dictionary" mode
// http://www.youtube.com/watch?v=XAqIpGU8ZZk#t=16m27s
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* The opposite of `_.initial`, this method gets all but the first value of
* `array`. Pass `n` to exclude the first `n` values from the result.
*
* @static
* @memberOf _
* @alias tail
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Array} Returns all but the first value or `n` values of `array`.
* @example
*
* _.rest([3, 2, 1]);
* // => [2, 1]
*/
function rest(array, n, guard) {
if (!array) {
return [];
}
return slice.call(array, (n == null || guard) ? 1 : n);
}
/**
* Produces a new array of shuffled `array` values, using a version of the
* Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to shuffle.
* @returns {Array} Returns a new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(array) {
if (!array) {
return [];
}
var rand,
index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
rand = Math.floor(Math.random() * (index + 1));
result[index] = result[rand];
result[rand] = array[index];
}
return result;
}
/**
* Uses a binary search to determine the smallest index at which the `value`
* should be inserted into `array` in order to maintain the sort order of the
* sorted `array`. If `callback` is passed, it will be executed for `value` and
* each element in `array` to compute their sort ranking. The `callback` is
* bound to `thisArg` and invoked with 1 argument; (value).
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to iterate over.
* @param {Mixed} value The value to evaluate.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Number} Returns the index at which the value should be inserted
* into `array`.
* @example
*
* _.sortedIndex([20, 30, 40], 35);
* // => 2
*
* var dict = {
* 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'thirty-five': 35, 'fourty': 40 }
* };
*
* _.sortedIndex(['twenty', 'thirty', 'fourty'], 'thirty-five', function(word) {
* return dict.wordToNumber[word];
* });
* // => 2
*
* _.sortedIndex(['twenty', 'thirty', 'fourty'], 'thirty-five', function(word) {
* return this.wordToNumber[word];
* }, dict);
* // => 2
*/
function sortedIndex(array, value, callback, thisArg) {
if (!array) {
return 0;
}
var mid,
low = 0,
high = array.length;
if (callback) {
if (thisArg) {
callback = bind(callback, thisArg);
}
value = callback(value);
while (low < high) {
mid = (low + high) >>> 1;
callback(array[mid]) < value ? low = mid + 1 : high = mid;
}
} else {
while (low < high) {
mid = (low + high) >>> 1;
array[mid] < value ? low = mid + 1 : high = mid;
}
}
return low;
}
/**
* Computes the union of the passed-in arrays.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of unique values, in order, that are
* present in one or more of the arrays.
* @example
*
* _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
* // => [1, 2, 3, 101, 10]
*/
function union() {
var index = -1,
result = [],
flattened = concat.apply(result, arguments),
length = flattened.length;
while (++index < length) {
if (indexOf(result, flattened[index]) < 0) {
result.push(flattened[index]);
}
}
return result;
}
/**
* Produces a duplicate-value-free version of the `array` using strict equality
* for comparisons, i.e. `===`. If the `array` is already sorted, passing `true`
* for `isSorted` will run a faster algorithm. If `callback` is passed,
* each value of `array` is passed through a transformation `callback` before
* uniqueness is computed. The `callback` is bound to `thisArg` and invoked
* with 3 arguments; (value, index, array).
*
* @static
* @memberOf _
* @alias unique
* @category Arrays
* @param {Array} array The array to process.
* @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1, 3, 1]);
* // => [1, 2, 3]
*
* _.uniq([1, 1, 2, 2, 3], true);
* // => [1, 2, 3]
*
* _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); });
* // => [1, 2, 3]
*
* _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math);
* // => [1, 2, 3]
*/
function uniq(array, isSorted, callback, thisArg) {
var result = [];
if (!array) {
return result;
}
var computed,
index = -1,
length = array.length,
seen = [];
// juggle arguments
if (typeof isSorted == 'function') {
thisArg = callback;
callback = isSorted;
isSorted = false;
}
if (!callback) {
callback = identity;
} else if (thisArg) {
callback = iteratorBind(callback, thisArg);
}
while (++index < length) {
computed = callback(array[index], index, array);
if (isSorted
? !index || seen[seen.length - 1] !== computed
: indexOf(seen, computed) < 0
) {
seen.push(computed);
result.push(array[index]);
}
}
return result;
}
/**
* Produces a new array with all occurrences of the passed values removed using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to filter.
* @param {Mixed} [value1, value2, ...] Values to remove.
* @returns {Array} Returns a new filtered array.
* @example
*
* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
* // => [2, 3, 4]
*/
function without(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length;
while (++index < length) {
if (indexOf(arguments, array[index], 1) < 0) {
result.push(array[index]);
}
}
return result;
}
/**
* Merges the elements of each array at their corresponding indexes. Useful for
* separate data sources that are coordinated through matching array indexes.
* For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix
* in a similar fashion.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of merged arrays.
* @example
*
* _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
* // => [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]]
*/
function zip(array) {
if (!array) {
return [];
}
var index = -1,
length = max(pluck(arguments, 'length')),
result = Array(length);
while (++index < length) {
result[index] = pluck(arguments, index);
}
return result;
}
/**
* Merges an array of `keys` and an array of `values` into a single object.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} keys The array of keys.
* @param {Array} [values=[]] The array of values.
* @returns {Object} Returns an object composed of the given keys and
* corresponding values.
* @example
*
* _.zipObject(['moe', 'larry', 'curly'], [30, 40, 50]);
* // => { 'moe': 30, 'larry': 40, 'curly': 50 }
*/
function zipObject(keys, values) {
if (!keys) {
return {};
}
var index = -1,
length = keys.length,
result = {};
values || (values = []);
while (++index < length) {
result[keys[index]] = values[index];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new function that is restricted to executing only after it is
* called `n` times.
*
* @static
* @memberOf _
* @category Functions
* @param {Number} n The number of times the function must be called before
* it is executed.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var renderNotes = _.after(notes.length, render);
* _.forEach(notes, function(note) {
* note.asyncSave({ 'success': renderNotes });
* });
* // `renderNotes` is run once, after all notes have saved
*/
function after(n, func) {
if (n < 1) {
return func();
}
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a new function that, when called, invokes `func` with the `this`
* binding of `thisArg` and prepends any additional `bind` arguments to those
* passed to the bound function. Lazy defined methods may be bound by passing
* the object they are bound to as `func` and the method name as `thisArg`.
*
* @static
* @memberOf _
* @category Functions
* @param {Function|Object} func The function to bind or the object the method belongs to.
* @param {Mixed} [thisArg] The `this` binding of `func` or the method name.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* // basic bind
* var func = function(greeting) {
* return greeting + ' ' + this.name;
* };
*
* func = _.bind(func, { 'name': 'moe' }, 'hi');
* func();
* // => 'hi moe'
*
* // lazy bind
* var object = {
* 'name': 'moe',
* 'greet': function(greeting) {
* return greeting + ' ' + this.name;
* }
* };
*
* var func = _.bind(object, 'greet', 'hi');
* func();
* // => 'hi moe'
*
* object.greet = function(greeting) {
* return greeting + ', ' + this.name + '!';
* };
*
* func();
* // => 'hi, moe!'
*/
function bind(func, thisArg) {
var methodName,
isFunc = toString.call(func) == funcClass;
// juggle arguments
if (!isFunc) {
methodName = thisArg;
thisArg = func;
}
// use `Function#bind` if it exists and is fast
// (in V8 `Function#bind` is slower except when partially applied)
else if (isBindFast || (nativeBind && arguments.length > 2)) {
return nativeBind.call.apply(nativeBind, arguments);
}
var partialArgs = slice.call(arguments, 2);
function bound() {
// `Function#bind` spec
// http://es5.github.com/#x15.3.4.5
var args = arguments,
thisBinding = thisArg;
if (!isFunc) {
func = thisArg[methodName];
}
if (partialArgs.length) {
args = args.length
? concat.apply(partialArgs, args)
: partialArgs;
}
if (this instanceof bound) {
// get `func` instance if `bound` is invoked in a `new` expression
noop.prototype = func.prototype;
thisBinding = new noop;
// mimic the constructor's `return` behavior
// http://es5.github.com/#x13.2.2
var result = func.apply(thisBinding, args);
return result && objectTypes[typeof result]
? result
: thisBinding
}
return func.apply(thisBinding, args);
}
return bound;
}
/**
* Binds methods on `object` to `object`, overwriting the existing method.
* If no method names are provided, all the function properties of `object`
* will be bound.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object to bind and assign the bound methods to.
* @param {String} [methodName1, methodName2, ...] Method names on the object to bind.
* @returns {Object} Returns the `object`.
* @example
*
* var buttonView = {
* 'label': 'lodash',
* 'onClick': function() { alert('clicked: ' + this.label); }
* };
*
* _.bindAll(buttonView);
* jQuery('#lodash_button').on('click', buttonView.onClick);
* // => When the button is clicked, `this.label` will have the correct value
*/
function bindAll(object) {
var funcs = arguments,
index = 1;
if (funcs.length == 1) {
index = 0;
funcs = functions(object);
}
for (var length = funcs.length; index < length; index++) {
object[funcs[index]] = bind(object[funcs[index]], object);
}
return object;
}
/**
* Creates a new function that is the composition of the passed functions,
* where each function consumes the return value of the function that follows.
* In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} [func1, func2, ...] Functions to compose.
* @returns {Function} Returns the new composed function.
* @example
*
* var greet = function(name) { return 'hi: ' + name; };
* var exclaim = function(statement) { return statement + '!'; };
* var welcome = _.compose(exclaim, greet);
* welcome('moe');
* // => 'hi: moe!'
*/
function compose() {
var funcs = arguments;
return function() {
var args = arguments,
length = funcs.length;
while (length--) {
args = [funcs[length].apply(this, args)];
}
return args[0];
};
}
/**
* Creates a new function that will delay the execution of `func` until after
* `wait` milliseconds have elapsed since the last time it was invoked. Pass
* `true` for `immediate` to cause debounce to invoke `func` on the leading,
* instead of the trailing, edge of the `wait` timeout. Subsequent calls to
* the debounced function will return the result of the last `func` call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to debounce.
* @param {Number} wait The number of milliseconds to delay.
* @param {Boolean} immediate A flag to indicate execution is on the leading
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* var lazyLayout = _.debounce(calculateLayout, 300);
* jQuery(window).on('resize', lazyLayout);
*/
function debounce(func, wait, immediate) {
var args,
result,
thisArg,
timeoutId;
function delayed() {
timeoutId = null;
if (!immediate) {
func.apply(thisArg, args);
}
}
return function() {
var isImmediate = immediate && !timeoutId;
args = arguments;
thisArg = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(delayed, wait);
if (isImmediate) {
result = func.apply(thisArg, args);
}
return result;
};
}
/**
* Executes the `func` function after `wait` milliseconds. Additional arguments
* are passed to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to delay.
* @param {Number} wait The number of milliseconds to delay execution.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
* @returns {Number} Returns the `setTimeout` timeout id.
* @example
*
* var log = _.bind(console.log, console);
* _.delay(log, 1000, 'logged later');
* // => 'logged later' (Appears after one second.)
*/
function delay(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function() { return func.apply(undefined, args); }, wait);
}
/**
* Defers executing the `func` function until the current call stack has cleared.
* Additional arguments are passed to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to defer.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
* @returns {Number} Returns the `setTimeout` timeout id.
* @example
*
* _.defer(function() { alert('deferred'); });
* // returns from the function before `alert` is called
*/
function defer(func) {
var args = slice.call(arguments, 1);
return setTimeout(function() { return func.apply(undefined, args); }, 1);
}
/**
* Creates a new function that memoizes the result of `func`. If `resolver` is
* passed, it will be used to determine the cache key for storing the result
* based on the arguments passed to the memoized function. By default, the first
* argument passed to the memoized function is used as the cache key.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] A function used to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var fibonacci = _.memoize(function(n) {
* return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
* });
*/
function memoize(func, resolver) {
var cache = {};
return function() {
var prop = resolver ? resolver.apply(this, arguments) : arguments[0];
return hasOwnProperty.call(cache, prop)
? cache[prop]
: (cache[prop] = func.apply(this, arguments));
};
}
/**
* Creates a new function that is restricted to one execution. Repeat calls to
* the function will return the value of the first call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // Application is only created once.
*/
function once(func) {
var result,
ran = false;
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
return result;
};
}
/**
* Creates a new function that, when called, invokes `func` with any additional
* `partial` arguments prepended to those passed to the partially applied
* function. This method is similar `bind`, except it does **not** alter the
* `this` binding.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) { return greeting + ': ' + name; };
* var hi = _.partial(greet, 'hi');
* hi('moe');
* // => 'hi: moe'
*/
function partial(func) {
var args = slice.call(arguments, 1),
argsLength = args.length;
return function() {
var result,
others = arguments;
if (others.length) {
args.length = argsLength;
push.apply(args, others);
}
result = args.length == 1 ? func.call(this, args[0]) : func.apply(this, args);
args.length = argsLength;
return result;
};
}
/**
* Creates a new function that, when executed, will only call the `func`
* function at most once per every `wait` milliseconds. If the throttled
* function is invoked more than once during the `wait` timeout, `func` will
* also be called on the trailing edge of the timeout. Subsequent calls to the
* throttled function will return the result of the last `func` call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to throttle.
* @param {Number} wait The number of milliseconds to throttle executions to.
* @returns {Function} Returns the new throttled function.
* @example
*
* var throttled = _.throttle(updatePosition, 100);
* jQuery(window).on('scroll', throttled);
*/
function throttle(func, wait) {
var args,
result,
thisArg,
timeoutId,
lastCalled = 0;
function trailingCall() {
lastCalled = new Date;
timeoutId = null;
func.apply(thisArg, args);
}
return function() {
var now = new Date,
remain = wait - (now - lastCalled);
args = arguments;
thisArg = this;
if (remain <= 0) {
lastCalled = now;
result = func.apply(thisArg, args);
}
else if (!timeoutId) {
timeoutId = setTimeout(trailingCall, remain);
}
return result;
};
}
/**
* Create a new function that passes the `func` function to the `wrapper`
* function as its first argument. Additional arguments are appended to those
* passed to the `wrapper` function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to wrap.
* @param {Function} wrapper The wrapper function.
* @param {Mixed} [arg1, arg2, ...] Arguments to append to those passed to the wrapper.
* @returns {Function} Returns the new function.
* @example
*
* var hello = function(name) { return 'hello: ' + name; };
* hello = _.wrap(hello, function(func) {
* return 'before, ' + func('moe') + ', after';
* });
* hello();
* // => 'before, hello: moe, after'
*/
function wrap(func, wrapper) {
return function() {
var args = [func];
if (arguments.length) {
push.apply(args, arguments);
}
return wrapper.apply(this, args);
};
}
/*--------------------------------------------------------------------------*/
/**
* Create a shallow clone of the `value`. Any nested objects or arrays will be
* assigned by reference and not cloned.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to clone.
* @returns {Mixed} Returns the cloned `value`.
* @example
*
* _.clone({ 'name': 'moe' });
* // => { 'name': 'moe' };
*/
function clone(value) {
return value && objectTypes[typeof value]
? (isArray(value) ? value.slice() : extend({}, value))
: value;
}
/**
* Assigns missing properties on `object` with default values from the defaults
* objects. Once a property is set, additional defaults of the same property
* will be ignored.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to populate.
* @param {Object} [defaults1, defaults2, ...] The defaults objects to apply to `object`.
* @returns {Object} Returns `object`.
* @example
*
* var iceCream = { 'flavor': 'chocolate' };
* _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' });
* // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' }
*/
var defaults = createIterator(extendIteratorOptions, {
'inLoop': 'if (result[index] == null) ' + extendIteratorOptions.inLoop
});
/**
* Copies enumerable properties from the source objects to the `destination` object.
* Subsequent sources will overwrite propery assignments of previous sources.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The destination object.
* @param {Object} [source1, source2, ...] The source objects.
* @returns {Object} Returns the destination object.
* @example
*
* _.extend({ 'name': 'moe' }, { 'age': 40 });
* // => { 'name': 'moe', 'age': 40 }
*/
var extend = createIterator(extendIteratorOptions);
/**
* Iterates over `object`'s own and inherited enumerable properties, executing
* the `callback` for each property. The `callback` is bound to `thisArg` and
* invoked with 3 arguments; (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Object} Returns the `object`.
* @example
*
* function Dog(name) {
* this.name = name;
* }
*
* Dog.prototype.bark = function() {
* alert('Woof, woof!');
* };
*
* _.forIn(new Dog('Dagny'), function(value, key) {
* alert(key);
* });
* // => alerts 'name' and 'bark' (order is not guaranteed)
*/
var forIn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions, {
'useHas': false
});
/**
* Iterates over `object`'s own enumerable properties, executing the `callback`
* for each property. The `callback` is bound to `thisArg` and invoked with 3
* arguments; (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Object} Returns the `object`.
* @example
*
* _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* alert(key);
* });
* // => alerts '0', '1', and 'length' (order is not guaranteed)
*/
var forOwn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions);
/**
* Produces a sorted array of the enumerable properties, own and inherited,
* of `object` that have function values.
*
* @static
* @memberOf _
* @alias methods
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names that have function values.
* @example
*
* _.functions(_);
* // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
*/
var functions = createIterator({
'args': 'object',
'init': '[]',
'useHas': false,
'inLoop': 'if (toString.call(iteratee[index]) == funcClass) result.push(index)',
'bottom': 'result.sort()'
});
/**
* Checks if the specified object `property` exists and is a direct property,
* instead of an inherited property.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to check.
* @param {String} property The property to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
* @example
*
* _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
* // => true
*/
function has(object, property) {
return hasOwnProperty.call(object, property);
}
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = function(value) {
return toString.call(value) == '[object Arguments]';
};
// fallback for browser like IE < 9 which detect `arguments` as `[object Object]`
if (!isArguments(arguments)) {
isArguments = function(value) {
return !!(value && hasOwnProperty.call(value, 'callee'));
};
}
/**
* Checks if `value` is an array.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
var isArray = nativeIsArray || function(value) {
return toString.call(value) == arrayClass;
};
/**
* Checks if `value` is a boolean (`true` or `false`) value.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a boolean value, else `false`.
* @example
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false || toString.call(value) == boolClass;
}
/**
* Checks if `value` is a date.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a date, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*/
function isDate(value) {
return toString.call(value) == dateClass;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*/
function isElement(value) {
return !!(value && value.nodeType == 1);
}
/**
* Checks if `value` is empty. Arrays or strings with a length of `0` and
* objects with no own enumerable properties are considered "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|String} value The value to inspect.
* @returns {Boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
var isEmpty = createIterator({
'args': 'value',
'init': 'true',
'top':
'var className = toString.call(value);\n' +
'if (className == arrayClass || className == stringClass) return !value.length',
'inLoop': {
'object': 'return false'
}
});
/**
* Performs a deep comparison between two values to determine if they are
* equivalent to each other.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} a The value to compare.
* @param {Mixed} b The other value to compare.
* @param {Array} [stack] Internally used to keep track of "seen" objects to
* avoid circular references.
* @returns {Boolean} Returns `true` if the values are equvalent, else `false`.
* @example
*
* var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
* var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
*
* moe == clone;
* // => false
*
* _.isEqual(moe, clone);
* // => true
*/
function isEqual(a, b, stack) {
stack || (stack = []);
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
// a strict comparison is necessary because `undefined == null`
if (a == null || b == null) {
return a === b;
}
// unwrap any wrapped objects
if (a._chain) {
a = a._wrapped;
}
if (b._chain) {
b = b._wrapped;
}
// invoke a custom `isEqual` method if one is provided
if (a.isEqual && toString.call(a.isEqual) == funcClass) {
return a.isEqual(b);
}
if (b.isEqual && toString.call(b.isEqual) == funcClass) {
return b.isEqual(a);
}
// compare [[Class]] names
var className = toString.call(a);
if (className != toString.call(b)) {
return false;
}
switch (className) {
// strings, numbers, dates, and booleans are compared by value
case stringClass:
// primitives and their corresponding object instances are equivalent;
// thus, `'5'` is quivalent to `new String('5')`
return a == String(b);
case numberClass:
// treat `NaN` vs. `NaN` as equal
return a != +a
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case boolClass:
case dateClass:
// coerce dates and booleans to numeric values, dates to milliseconds and booleans to 1 or 0;
// treat invalid dates coerced to `NaN` as not equal
return +a == +b;
// regexps are compared by their source and flags
case regexpClass:
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') {
return false;
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (stack[length] == a) {
return true;
}
}
var index = -1,
result = true,
size = 0;
// add the first collection to the stack of traversed objects
stack.push(a);
// recursively compare objects and arrays
if (className == arrayClass) {
// compare array lengths to determine if a deep comparison is necessary
size = a.length;
result = size == b.length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
if (!(result = isEqual(a[size], b[size], stack))) {
break;
}
}
}
} else {
// objects with different constructors are not equivalent
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) {
return false;
}
// deep compare objects.
for (var prop in a) {
if (hasOwnProperty.call(a, prop)) {
// count the number of properties.
size++;
// deep compare each property value.
if (!(result = hasOwnProperty.call(b, prop) && isEqual(a[prop], b[prop], stack))) {
break;
}
}
}
// ensure both objects have the same number of properties
if (result) {
for (prop in b) {
// Adobe's JS engine, embedded in applications like InDesign, has a
// bug that causes `!size--` to throw an error so it must be wrapped
// in parentheses.
// https://github.com/documentcloud/underscore/issues/355
if (hasOwnProperty.call(b, prop) && !(size--)) {
break;
}
}
result = !size;
}
// handle JScript [[DontEnum]] bug
if (result && hasDontEnumBug) {
while (++index < 7) {
prop = shadowed[index];
if (hasOwnProperty.call(a, prop)) {
if (!(result = hasOwnProperty.call(b, prop) && isEqual(a[prop], b[prop], stack))) {
break;
}
}
}
}
}
// remove the first collection from the stack of traversed objects
stack.pop();
return result;
}
/**
* Checks if `value` is a finite number.
* Note: This is not the same as native `isFinite`, which will return true for
* booleans and other values. See http://es5.github.com/#x15.1.2.5.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a finite number, else `false`.
* @example
*
* _.isFinite(-101);
* // => true
*
* _.isFinite('10');
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
function isFinite(value) {
return nativeIsFinite(value) && toString.call(value) == numberClass;
}
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a function, else `false`.
* @example
*
* _.isFunction(''.concat);
* // => true
*/
function isFunction(value) {
return toString.call(value) == funcClass;
}
/**
* Checks if `value` is the language type of Object.
* (e.g. arrays, functions, objects, regexps, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.com/#x8
return value && objectTypes[typeof value];
}
/**
* Checks if `value` is `NaN`.
* Note: This is not the same as native `isNaN`, which will return true for
* `undefined` and other values. See http://es5.github.com/#x15.1.2.4.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// `NaN` as a primitive is the only value that is not equal to itself
// (perform the [[Class]] check first to avoid errors with some host objects in IE)
return toString.call(value) == numberClass && value != +value
}
/**
* Checks if `value` is `null`.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(undefined);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is a number.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a number, else `false`.
* @example
*
* _.isNumber(8.4 * 5;
* // => true
*/
function isNumber(value) {
return toString.call(value) == numberClass;
}
/**
* Checks if `value` is a regular expression.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a regular expression, else `false`.
* @example
*
* _.isRegExp(/moe/);
* // => true
*/
function isRegExp(value) {
return toString.call(value) == regexpClass;
}
/**
* Checks if `value` is a string.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a string, else `false`.
* @example
*
* _.isString('moe');
* // => true
*/
function isString(value) {
return toString.call(value) == stringClass;
}
/**
* Checks if `value` is `undefined`.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*/
function isUndefined(value) {
return value === undefined;
}
/**
* Produces an array of object`'s own enumerable property names.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names.
* @example
*
* _.keys({ 'one': 1, 'two': 2, 'three': 3 });
* // => ['one', 'two', 'three'] (order is not guaranteed)
*/
var keys = !nativeKeys ? shimKeys : function(object) {
// avoid iterating over the `prototype` property
return typeof object == 'function' && propertyIsEnumerable.call(object, 'prototype')
? shimKeys(object)
: nativeKeys(object);
};
/**
* Creates an object composed of the specified properties. Property names may
* be specified as individual arguments or as arrays of property names.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to pluck.
* @param {Object} [prop1, prop2, ...] The properties to pick.
* @returns {Object} Returns an object composed of the picked properties.
* @example
*
* _.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age');
* // => { 'name': 'moe', 'age': 40 }
*/
function pick(object) {
var prop,
index = 0,
props = concat.apply(ArrayProto, arguments),
length = props.length,
result = {};
// start `index` at `1` to skip `object`
while (++index < length) {
prop = props[index];
if (prop in object) {
result[prop] = object[prop];
}
}
return result;
}
/**
* Gets the size of `value` by returning `value.length` if `value` is a string
* or array, or the number of own enumerable properties if `value` is an object.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|String} value The value to inspect.
* @returns {Number} Returns `value.length` if `value` is a string or array,
* or the number of own enumerable properties if `value` is an object.
* @example
*
* _.size([1, 2]);
* // => 2
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*
* _.size('curly');
* // => 5
*/
function size(value) {
if (!value) {
return 0;
}
var length = value.length;
return length === length >>> 0 ? value.length : keys(value).length;
}
/**
* Produces an array of `object`'s own enumerable property values.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3]
*/
var values = createIterator({
'args': 'object',
'init': '[]',
'inLoop': 'result.push(iteratee[index])'
});
/*--------------------------------------------------------------------------*/
/**
* Escapes a string for inclusion in HTML, replacing `&`, `<`, `"`, and `'`
* characters.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} string The string to escape.
* @returns {String} Returns the escaped string.
* @example
*
* _.escape('Curly, Larry & Moe');
* // => "Curly, Larry & Moe"
*/
function escape(string) {
return string == null ? '' : (string + '').replace(reUnescapedHtml, escapeHtmlChar);
}
/**
* This function returns the first argument passed to it.
* Note: It is used throughout Lo-Dash as a default callback.
*
* @static
* @memberOf _
* @category Utilities
* @param {Mixed} value Any value.
* @returns {Mixed} Returns `value`.
* @example
*
* var moe = { 'name': 'moe' };
* moe === _.identity(moe);
* // => true
*/
function identity(value) {
return value;
}
/**
* Adds functions properties of `object` to the `lodash` function and chainable
* wrapper.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object of function properties to add to `lodash`.
* @example
*
* _.mixin({
* 'capitalize': function(string) {
* return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
* }
* });
*
* _.capitalize('curly');
* // => 'Curly'
*
* _('larry').capitalize();
* // => 'Larry'
*/
function mixin(object) {
forEach(functions(object), function(methodName) {
var func = lodash[methodName] = object[methodName];
LoDash.prototype[methodName] = function() {
var args = [this._wrapped];
if (arguments.length) {
push.apply(args, arguments);
}
var result = func.apply(lodash, args);
if (this._chain) {
result = new LoDash(result);
result._chain = true;
}
return result;
};
});
}
/**
* Reverts the '_' variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utilities
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
window._ = oldDash;
return this;
}
/**
* Resolves the value of `property` on `object`. If `property` is a function
* it will be invoked and its result returned, else the property value is
* returned. If `object` is falsey, then `null` is returned.
*
* @deprecated
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object to inspect.
* @param {String} property The property to get the result of.
* @returns {Mixed} Returns the resolved value.
* @example
*
* var object = {
* 'cheese': 'crumpets',
* 'stuff': function() {
* return 'nonsense';
* }
* };
*
* _.result(object, 'cheese');
* // => 'crumpets'
*
* _.result(object, 'stuff');
* // => 'nonsense'
*/
function result(object, property) {
// based on Backbone's private `getValue` function
// https://github.com/documentcloud/backbone/blob/0.9.2/backbone.js#L1419-1424
if (!object) {
return null;
}
var value = object[property];
return toString.call(value) == funcClass ? object[property]() : value;
}
/**
* A micro-templating method that handles arbitrary delimiters, preserves
* whitespace, and correctly escapes quotes within interpolated code.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} text The template text.
* @param {Obect} data The data object used to populate the text.
* @param {Object} options The options object.
* @returns {Function|String} Returns a compiled function when no `data` object
* is given, else it returns the interpolated text.
* @example
*
* // using compiled template
* var compiled = _.template('hello: <%= name %>');
* compiled({ 'name': 'moe' });
* // => 'hello: moe'
*
* var list = '<% _.forEach(people, function(name) { %> <li><%= name %></li> <% }); %>';
* _.template(list, { 'people': ['moe', 'curly', 'larry'] });
* // => '<li>moe</li><li>curly</li><li>larry</li>'
*
* var template = _.template('<b><%- value %></b>');
* template({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // using `print`
* var compiled = _.template('<% print("Hello " + epithet); %>');
* compiled({ 'epithet': 'stooge' });
* // => 'Hello stooge.'
*
* // using custom template settings
* _.templateSettings = {
* 'interpolate': /\{\{(.+?)\}\}/g
* };
*
* var template = _.template('Hello {{ name }}!');
* template({ 'name': 'Mustache' });
* // => 'Hello Mustache!'
*
* // using the `variable` option
* _.template('<%= data.hasWith %>', { 'hasWith': 'no' }, { 'variable': 'data' });
* // => 'no'
*
* // using the `source` property
* <script>
* JST.project = <%= _.template(jstText).source %>;
* </script>
*/
function template(text, data, options) {
// based on John Resig's `tmpl` implementation
// http://ejohn.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
options || (options = {});
var isEvaluating,
result,
escapeDelimiter = options.escape,
evaluateDelimiter = options.evaluate,
interpolateDelimiter = options.interpolate,
settings = lodash.templateSettings,
variable = options.variable;
// use default settings if no options object is provided
if (escapeDelimiter == null) {
escapeDelimiter = settings.escape;
}
if (evaluateDelimiter == null) {
evaluateDelimiter = settings.evaluate;
}
if (interpolateDelimiter == null) {
interpolateDelimiter = settings.interpolate;
}
// tokenize delimiters to avoid escaping them
if (escapeDelimiter) {
text = text.replace(escapeDelimiter, tokenizeEscape);
}
if (interpolateDelimiter) {
text = text.replace(interpolateDelimiter, tokenizeInterpolate);
}
if (evaluateDelimiter != lastEvaluateDelimiter) {
// generate `reEvaluateDelimiter` to match `_.templateSettings.evaluate`
// and internal `<e%- %>`, `<e%= %>` delimiters
lastEvaluateDelimiter = evaluateDelimiter;
reEvaluateDelimiter = RegExp(
(evaluateDelimiter ? evaluateDelimiter.source : '($^)') +
'|<e%-([\\s\\S]+?)%>|<e%=([\\s\\S]+?)%>'
, 'g');
}
isEvaluating = tokenized.length;
text = text.replace(reEvaluateDelimiter, tokenizeEvaluate);
isEvaluating = isEvaluating != tokenized.length;
// escape characters that cannot be included in string literals and
// detokenize delimiter code snippets
text = "__p += '" + text
.replace(reUnescapedString, escapeStringChar)
.replace(reToken, detokenize) + "';\n";
// clear stored code snippets
tokenized.length = 0;
// if `options.variable` is not specified and the template contains "evaluate"
// delimiters, wrap a with-statement around the generated code to add the
// data object to the top of the scope chain
if (!variable) {
variable = settings.variable || lastVariable || 'obj';
if (isEvaluating) {
text = 'with (' + variable + ') {\n' + text + '\n}\n';
}
else {
if (variable != lastVariable) {
// generate `reDoubleVariable` to match references like `obj.obj` inside
// transformed "escape" and "interpolate" delimiters
lastVariable = variable;
reDoubleVariable = RegExp('(\\(\\s*)' + variable + '\\.' + variable + '\\b', 'g');
}
// avoid a with-statement by prepending data object references to property names
text = text
.replace(reInsertVariable, '$&' + variable + '.')
.replace(reDoubleVariable, '$1__d');
}
}
// cleanup code by stripping empty strings
text = ( isEvaluating ? text.replace(reEmptyStringLeading, '') : text)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
text = 'function(' + variable + ') {\n' +
variable + ' || (' + variable + ' = {});\n' +
'var __t, __p = \'\', __e = _.escape' +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
'function print() { __p += __j.call(arguments, \'\') }\n'
: ', __d = ' + variable + '.' + variable + ' || ' + variable + ';\n'
) +
text +
'return __p\n}';
// add a sourceURL for easier debugging
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
if (useSourceURL) {
text += '\n//@ sourceURL=/lodash/template/source[' + (templateCounter++) + ']';
}
try {
result = Function('_', 'return ' + text)(lodash);
} catch(e) {
result = function() { throw e; };
}
if (data) {
return result(data);
}
// provide the compiled function's source via its `toString` method, in
// supported environments, or the `source` property as a convenience for
// build time precompilation
result.source = text;
return result;
}
/**
* Executes the `callback` function `n` times. The `callback` is bound to
* `thisArg` and invoked with 1 argument; (index).
*
* @static
* @memberOf _
* @category Utilities
* @param {Number} n The number of times to execute the callback.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @example
*
* _.times(3, function() { genie.grantWish(); });
* // => calls `genie.grantWish()` 3 times
*
* _.times(3, function() { this.grantWish(); }, genie);
* // => also calls `genie.grantWish()` 3 times
*/
function times(n, callback, thisArg) {
var index = -1;
if (thisArg) {
while (++index < n) {
callback.call(thisArg, index);
}
} else {
while (++index < n) {
callback(index);
}
}
}
/**
* Generates a unique id. If `prefix` is passed, the id will be appended to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} [prefix] The value to prefix the id with.
* @returns {Number|String} Returns a numeric id if no prefix is passed, else
* a string id may be returned.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*/
function uniqueId(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
}
/*--------------------------------------------------------------------------*/
/**
* Wraps the value in a `lodash` wrapper object.
*
* @static
* @memberOf _
* @category Chaining
* @param {Mixed} value The value to wrap.
* @returns {Object} Returns the wrapper object.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* var youngest = _.chain(stooges)
* .sortBy(function(stooge) { return stooge.age; })
* .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
* .first()
* .value();
* // => 'moe is 40'
*/
function chain(value) {
value = new LoDash(value);
value._chain = true;
return value;
}
/**
* Invokes `interceptor` with the `value` as the first argument, and then
* returns `value`. The purpose of this method is to "tap into" a method chain,
* in order to perform operations on intermediate results within the chain.
*
* @static
* @memberOf _
* @category Chaining
* @param {Mixed} value The value to pass to `callback`.
* @param {Function} interceptor The function to invoke.
* @returns {Mixed} Returns `value`.
* @example
*
* _.chain([1,2,3,200])
* .filter(function(num) { return num % 2 == 0; })
* .tap(alert)
* .map(function(num) { return num * num })
* .value();
* // => // [2, 200] (alerted)
* // => [4, 40000]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* Enables method chaining on the wrapper object.
*
* @name chain
* @deprecated
* @memberOf _
* @category Chaining
* @returns {Mixed} Returns the wrapper object.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperChain() {
this._chain = true;
return this;
}
/**
* Extracts the wrapped value.
*
* @name value
* @memberOf _
* @category Chaining
* @returns {Mixed} Returns the wrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return this._wrapped;
}
/*--------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type String
*/
lodash.VERSION = '0.4.1';
// assign static methods
lodash.after = after;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.chain = chain;
lodash.clone = clone;
lodash.compact = compact;
lodash.compose = compose;
lodash.contains = contains;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.escape = escape;
lodash.every = every;
lodash.extend = extend;
lodash.filter = filter;
lodash.find = find;
lodash.first = first;
lodash.flatten = flatten;
lodash.forEach = forEach;
lodash.forIn = forIn;
lodash.forOwn = forOwn;
lodash.functions = functions;
lodash.groupBy = groupBy;
lodash.has = has;
lodash.identity = identity;
lodash.indexOf = indexOf;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isNaN = isNaN;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isRegExp = isRegExp;
lodash.isString = isString;
lodash.isUndefined = isUndefined;
lodash.keys = keys;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.map = map;
lodash.max = max;
lodash.memoize = memoize;
lodash.min = min;
lodash.mixin = mixin;
lodash.noConflict = noConflict;
lodash.once = once;
lodash.partial = partial;
lodash.pick = pick;
lodash.pluck = pluck;
lodash.range = range;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.reject = reject;
lodash.rest = rest;
lodash.result = result;
lodash.shuffle = shuffle;
lodash.size = size;
lodash.some = some;
lodash.sortBy = sortBy;
lodash.sortedIndex = sortedIndex;
lodash.tap = tap;
lodash.template = template;
lodash.throttle = throttle;
lodash.times = times;
lodash.toArray = toArray;
lodash.union = union;
lodash.uniq = uniq;
lodash.uniqueId = uniqueId;
lodash.values = values;
lodash.without = without;
lodash.wrap = wrap;
lodash.zip = zip;
lodash.zipObject = zipObject;
// assign aliases
lodash.all = every;
lodash.any = some;
lodash.collect = map;
lodash.detect = find;
lodash.each = forEach;
lodash.foldl = reduce;
lodash.foldr = reduceRight;
lodash.head = first;
lodash.include = contains;
lodash.inject = reduce;
lodash.methods = functions;
lodash.select = filter;
lodash.tail = rest;
lodash.take = first;
lodash.unique = uniq;
// add pseudo private properties used and removed during the build process
lodash._iteratorTemplate = iteratorTemplate;
lodash._shimKeys = shimKeys;
/*--------------------------------------------------------------------------*/
// assign private `LoDash` constructor's prototype
LoDash.prototype = lodash.prototype;
// add all static functions to `LoDash.prototype`
mixin(lodash);
// add `LoDash.prototype.chain` after calling `mixin()` to avoid overwriting
// it with the wrapped `lodash.chain`
LoDash.prototype.chain = wrapperChain;
LoDash.prototype.value = wrapperValue;
// add all mutator Array functions to the wrapper.
forEach(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = ArrayProto[methodName];
LoDash.prototype[methodName] = function() {
var value = this._wrapped;
func.apply(value, arguments);
// IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()`
// functions that fail to remove the last element, `value[0]`, of
// array-like objects even though the `length` property is set to `0`.
// The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
// is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
if (value.length === 0) {
delete value[0];
}
if (this._chain) {
value = new LoDash(value);
value._chain = true;
}
return value;
};
});
// add all accessor Array functions to the wrapper.
forEach(['concat', 'join', 'slice'], function(methodName) {
var func = ArrayProto[methodName];
LoDash.prototype[methodName] = function() {
var value = this._wrapped,
result = func.apply(value, arguments);
if (this._chain) {
result = new LoDash(result);
result._chain = true;
}
return result;
};
});
/*--------------------------------------------------------------------------*/
// expose Lo-Dash
// some AMD build optimizers, like r.js, check for specific condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lo-Dash to the global object even when an AMD loader is present in
// case Lo-Dash was injected by a third-party script and not intended to be
// loaded as a module. The global assignment can be reverted in the Lo-Dash
// module via its `noConflict()` method.
window._ = lodash;
// define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module
define('vector/../../lib/lodash',[],function() {
return lodash;
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports) {
// in Node.js or RingoJS v0.8.0+
if (typeof module == 'object' && module && module.exports == freeExports) {
(module.exports = lodash)._ = lodash;
}
// in Narwhal or RingoJS v0.7.0-
else {
freeExports._ = lodash;
}
}
else {
// in a browser or Rhino
window._ = lodash;
}
}(this));
define('common/not-implemented',['require'],function ( require ) {
return function notImplemented() {
throw new Error( "not implemented" );
};
});
define('vector/vector',['require'],function ( require ) {
var Vector = function() {
};
return Vector;
});
define('vector/vector2-api',['require','common/not-implemented','vector/v2'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var V2 = require( "vector/v2" )( FLOAT_ARRAY_TYPE );
function add( v1, v2, result ) {
result = result || new V2();
result[0] = v1[0] + v2[0];
result[1] = v1[1] + v2[1];
return result;
}
function angle( v1, v2 ) {
var normalizedV1 = new V2();
var normalizedV2 = new V2();
normalize(v1, normalizedV1);
normalize(v2, normalizedV2);
return Math.acos( dot( normalizedV1, normalizedV2 ) );
}
function clear( v ) {
v[0] = 0;
v[1] = 0;
return v;
}
function dot( v1, v2 ) {
var r = 0;
r += v1[0] * v2[0];
r += v1[1] * v2[1];
return r;
}
function equal( v1, v2, e ) {
e = e || 0.000001;
if( v1.length !== v2.length ) {
return false;
}
var d0 = Math.abs( v1[0] - v2[0] );
var d1 = Math.abs( v1[1] - v2[1] );
if( isNaN( d0 ) || d0 > e ||
isNaN( d1 ) || d1 > e ) {
return false;
}
return true;
}
function length( v ) {
var r = 0;
r += v[0] * v[0];
r += v[1] * v[1];
return Math.sqrt( r );
}
function multiply( v, s, result ) {
result = result || new V2();
result[0] = s * v[0];
result[1] = s * v[1];
return result;
}
function negate( v, result ) {
result = result || new V2();
result[0] = -1 * v[0];
result[1] = -1 * v[1];
return result;
}
function normalize( v, result ) {
result = result || new V2();
var l = length( v );
result[0] = v[0]/l;
result[1] = v[1]/l;
return result;
}
function project( v1, v2, result ) {
result = result || new V2();
var dp = v1[0]*v2[0] + v1[1]*v2[1];
var dp_over_v2_squared_length = dp / (v2[0]*v2[0] + v2[1]*v2[1]);
result[0] = dp_over_v2_squared_length * v2[0];
result[1] = dp_over_v2_squared_length * v2[1];
return result;
}
function set( v ) {
if( 2 === arguments.length ) {
v[0] = arguments[1][0];
v[1] = arguments[1][1];
} else {
v[0] = arguments[1];
v[1] = arguments[2];
}
return v;
}
function subtract( v1, v2, result ) {
result = result || new V2();
result[0] = v1[0] - v2[0];
result[1] = v1[1] - v2[1];
return result;
}
var vector2 = {
add: add,
angle: angle,
clear: clear,
distance: notImplemented,
dot: dot,
equal: equal,
length: length,
limit: notImplemented,
multiply: multiply,
negate: negate,
normalize: normalize,
project: project,
set: set,
subtract: subtract,
x: new V2( 1, 0 ),
u: new V2( 1, 0 ),
y: new V2( 0, 1 ),
v: new V2( 0, 1 ),
zero: new V2( 0, 0 ),
one: new V2( 1, 1 )
};
return vector2;
};
});
define('vector/vector2',['require','../../lib/lodash','common/not-implemented','vector/v2','vector/vector2-api','vector/vector'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var _ = require( "../../lib/lodash" );
var notImplemented = require( "common/not-implemented" );
var V2 = require( "vector/v2" )( FLOAT_ARRAY_TYPE );
var vector2 = require( "vector/vector2-api" )( FLOAT_ARRAY_TYPE );
var Vector = require( "vector/vector" );
function getValue( index ) {
return this.buffer[index];
}
function setValue( index, value ) {
this.buffer[index] = value;
this.modified = true;
}
var Vector2 = function( arg1, arg2 ) {
var argc = arguments.length;
this.buffer = new V2(
(arg1 instanceof Vector) ? arg1.buffer : arg1,
(arg2 instanceof Vector) ? arg2.buffer : arg2
);
Object.defineProperties( this, {
x: {
get: getValue.bind( this, 0 ),
set: setValue.bind( this, 0 )
},
y: {
get: getValue.bind( this, 1 ),
set: setValue.bind( this, 1 )
}
});
this.modified = true;
this.size = 2;
};
Vector2.prototype = new Vector();
Vector2.prototype.constructor = Vector2;
function add( arg, result ) {
var other;
if( arg instanceof Vector2 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector2.add( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function angle( arg ) {
var other;
if( arg instanceof Vector2 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector2.angle( this.buffer, other );
}
function clear() {
vector2.clear( this.buffer );
this.modified = true;
return this;
}
function clone() {
return new Vector2( this );
}
function dot( arg ) {
var other;
if( arg instanceof Vector2 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector2.dot( this.buffer, other );
}
function equal( arg ) {
var other;
if( arg instanceof Vector2 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector2.equal( this.buffer, other );
}
function length() {
return vector2.length( this.buffer );
}
function multiply( arg, result ) {
result = result || this;
vector2.multiply( this.buffer, arg, result.buffer );
result.modified = true;
return this;
}
function negate( result ) {
result = result || this;
vector2.negate( this.buffer, result.buffer );
result.modified = true;
return this;
}
function normalize( result ) {
result = result || this;
vector2.normalize( this.buffer, result.buffer );
result.modified = true;
return this;
}
function project( arg, result ) {
var other;
if( arg instanceof Vector2 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector2.project( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function set( arg1, arg2 ) {
var argc = arguments.length;
var buffer = this.buffer;
if( 1 === argc ) {
if( arg1 instanceof Vector2 ) {
var other = arg1.buffer;
buffer[0] = other[0];
buffer[1] = other[1];
this.modified = true;
} else {
buffer[0] = arg1[0];
buffer[1] = arg1[1];
this.modified = true;
}
} else if( 2 === argc ) {
buffer[0] = arg1;
buffer[1] = arg2;
this.modified = true;
}
return this;
}
function subtract( arg, result ) {
var other;
if( arg instanceof Vector2 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector2.subtract( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
_.extend( Vector2.prototype, {
add: add,
angle: angle,
clear: clear,
clone: clone,
distance: notImplemented,
dot: dot,
equal: equal,
length: length,
multiply: multiply,
negate: negate,
normalize: normalize,
project: project,
set: set,
subtract: subtract
});
return Vector2;
};
});
define('vector/v3',['require','vector/v'],function ( require ) {
var V = require( "vector/v" );
return function( FLOAT_ARRAY_TYPE ) {
var V3 = function() {
var argc = arguments.length;
var i, j, vi = 0;
var vector = new FLOAT_ARRAY_TYPE( 3 );
for( i = 0; i < argc && vi < 3; ++ i ) {
var arg = arguments[i];
if( arg === undefined ) {
break;
} else if( arg instanceof Array ||
arg instanceof FLOAT_ARRAY_TYPE ) {
for( j = 0; j < arg.length && vi < 3; ++ j ) {
vector[vi ++] = arg[j];
}
} else {
vector[vi ++] = arg;
}
}
// Fill in missing elements with zero
for( ; vi < 3; ++ vi ) {
vector[vi] = 0;
}
return vector;
};
V3.prototype = new V();
V3.prototype.constructor = V3;
return V3;
};
});
define('matrix/matrix',['require'],function ( require ) {
var Matrix = function() {
};
return Matrix;
});
define('vector/vector3-api',['require','common/not-implemented','vector/v3'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var V3 = require( "vector/v3" )( FLOAT_ARRAY_TYPE );
function add( v1, v2, result ) {
if( result === v1 ) {
v1[0] += v2[0];
v1[1] += v2[1];
v1[2] += v2[2];
return;
}
if( undefined === result ) {
result = new V3( v1[0] + v2[0],
v1[1] + v2[1], v1[2] + v2[2] );
return result;
} else {
result[0] = v1[0] + v2[0];
result[1] = v1[1] + v2[1];
result[2] = v1[2] + v2[2];
return;
}
}
function angle( v1, v2 ) {
return Math.acos(
(v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]) /
(Math.sqrt(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2]) *
Math.sqrt(v2[0] * v2[0] + v2[1] * v2[1] + v2[2] * v2[2]) ) );
}
function clear( v ) {
v[0] = 0;
v[1] = 0;
v[2] = 0;
return v;
}
function cross( v1, v2, result ) {
result = result || new V3();
var v1_0 = v1[0],
v1_1 = v1[1],
v1_2 = v1[2];
var v2_0 = v2[0],
v2_1 = v2[1],
v2_2 = v2[2];
result[0] = (v1_1 * v2_2) - (v2_1 * v1_2);
result[1] = (v1_2 * v2_0) - (v2_2 * v1_0);
result[2] = (v1_0 * v2_1) - (v2_0 * v1_1);
return result;
}
function dot( v1, v2 ) {
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
}
function equal( v1, v2, e ) {
e = e || 0.000001;
if( v1.length !== v2.length ) {
return false;
}
var d0 = Math.abs( v1[0] - v2[0] );
var d1 = Math.abs( v1[1] - v2[1] );
var d2 = Math.abs( v1[2] - v2[2] );
if( isNaN( d0 ) || d0 > e ||
isNaN( d1 ) || d1 > e ||
isNaN( d2 ) || d2 > e ) {
return false;
}
return true;
}
function length( v ) {
var r = 0;
r += v[0] * v[0];
r += v[1] * v[1];
r += v[2] * v[2];
return Math.sqrt( r );
}
function multiply( v, s, result ) {
result = result || new V3();
result[0] = s * v[0];
result[1] = s * v[1];
result[2] = s * v[2];
return result;
}
function negate( v, result ) {
result = result || new V3();
result[0] = -1 * v[0];
result[1] = -1 * v[1];
result[2] = -1 * v[2];
return result;
}
function normalize( v, result ) {
result = result || new V3();
var l = length( v );
result[0] = v[0]/l;
result[1] = v[1]/l;
result[2] = v[2]/l;
return result;
}
function set( v ) {
if( 2 === arguments.length ) {
v[0] = arguments[1][0];
v[1] = arguments[1][1];
v[2] = arguments[1][2];
} else {
v[0] = arguments[1];
v[1] = arguments[2];
v[2] = arguments[3];
}
return v;
}
function subtract( v1, v2, result ) {
result = result || new V3();
result[0] = v1[0] - v2[0];
result[1] = v1[1] - v2[1];
result[2] = v1[2] - v2[2];
return result;
}
//This does a matrix3 by vector3 transform, which is a matrix multiplication
//The matrix3 is on the left side of the multiplication and is multiplied by
// the vector in column form
function transform( v, m, result ) {
result = result || new V3();
var x = v[0], y = v[1], z = v[2];
result[0] = m[0] * x + m[1] * y + m[2] * z;
result[1] = m[3] * x + m[4] * y + m[5] * z;
result[2] = m[6] * x + m[7] * y + m[8] * z;
return result;
}
var vector3 = {
add: add,
angle: angle,
clear: clear,
cross: cross,
distance: notImplemented,
dot: dot,
equal: equal,
length: length,
limit: notImplemented,
multiply: multiply,
negate: negate,
normalize: normalize,
set: set,
subtract: subtract,
transform: transform,
x: new V3( 1, 0, 0 ),
y: new V3( 0, 1, 0 ),
z: new V3( 0, 0, 1 ),
zero: new V3( 0, 0, 0 ),
one: new V3( 1, 1, 1 )
};
return vector3;
};
});
define('vector/vector3',['require','../../lib/lodash','common/not-implemented','vector/v3','vector/vector3-api','matrix/matrix','vector/vector'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var _ = require( "../../lib/lodash" );
var notImplemented = require( "common/not-implemented" );
var V3 = require( "vector/v3" )( FLOAT_ARRAY_TYPE );
var vector3 = require( "vector/vector3-api" )( FLOAT_ARRAY_TYPE );
var Matrix = require( "matrix/matrix" );
var Vector = require( "vector/vector" );
function getValue( index ) {
return this.buffer[index];
}
function setValue( index, value ) {
this.buffer[index] = value;
this.modified = true;
}
var Vector3 = function( arg1, arg2, arg3 ) {
var argc = arguments.length;
this.buffer = new V3(
(arg1 instanceof Vector) ? arg1.buffer : arg1,
(arg2 instanceof Vector) ? arg2.buffer : arg2,
(arg3 instanceof Vector) ? arg3.buffer : arg3
);
Object.defineProperties( this, {
x: {
get: getValue.bind( this, 0 ),
set: setValue.bind( this, 0 )
},
y: {
get: getValue.bind( this, 1 ),
set: setValue.bind( this, 1 )
},
z: {
get: getValue.bind( this, 2 ),
set: setValue.bind( this, 2 )
}
});
this.modified = true;
this.size = 3;
};
Vector3.prototype = new Vector();
Vector3.prototype.constructor = Vector3;
function add( arg, result ) {
var other;
if( arg instanceof Vector3 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector3.add( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function angle( arg ) {
var other;
if( arg instanceof Vector3 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector3.angle( this.buffer, other );
}
function clear() {
vector3.clear( this.buffer );
this.modified = true;
return this;
}
function clone() {
return new Vector3( this );
}
function cross( arg, result ) {
var other;
if( arg instanceof Vector3 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector3.cross( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function dot( arg ) {
var other;
if( arg instanceof Vector3 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector3.dot( this.buffer, other );
}
function equal( arg ) {
var other;
if( arg instanceof Vector3 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector3.equal( this.buffer, other );
}
function length() {
return vector3.length( this.buffer );
}
function multiply( arg, result ) {
result = result || this;
vector3.multiply( this.buffer, arg, result.buffer );
result.modified = true;
return this;
}
function negate( result ) {
result = result || this;
vector3.negate( this.buffer, result.buffer );
result.modified = true;
return this;
}
function normalize( result ) {
result = result || this;
vector3.normalize( this.buffer, result.buffer );
result.modified = true;
return this;
}
function set( arg1, arg2, arg3 ) {
var argc = arguments.length;
var buffer = this.buffer;
if( 1 === argc ) {
if( arg1 instanceof Vector3 ) {
var other = arg1.buffer;
buffer[0] = other[0];
buffer[1] = other[1];
buffer[2] = other[2];
this.modified = true;
} else {
buffer[0] = arg1[0];
buffer[1] = arg1[1];
buffer[2] = arg1[2];
this.modified = true;
}
} else if( 3 === argc ) {
buffer[0] = arg1;
buffer[1] = arg2;
buffer[2] = arg3;
this.modified = true;
}
return this;
}
function subtract( arg, result ) {
var other;
if( arg instanceof Vector3 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector3.subtract( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function transform( arg, result ) {
var other;
if( arg instanceof Matrix ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector3.transform( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
_.extend( Vector3.prototype, {
add: add,
angle: angle,
clear: clear,
clone: clone,
cross: cross,
distance: notImplemented,
dot: dot,
equal: equal,
length: length,
multiply: multiply,
negate: negate,
normalize: normalize,
set: set,
subtract: subtract,
transform: transform
});
return Vector3;
};
});
define('vector/v4',['require','vector/v'],function ( require ) {
var V = require( "vector/v" );
return function( FLOAT_ARRAY_TYPE ) {
var V4 = function() {
var argc = arguments.length;
var i, j, vi = 0;
var vector = new FLOAT_ARRAY_TYPE( 4 );
for( i = 0; i < argc && vi < 4; ++ i ) {
var arg = arguments[i];
if( arg === undefined ) {
break;
} else if( arg instanceof Array ||
arg instanceof FLOAT_ARRAY_TYPE ) {
for( j = 0; j < arg.length && vi < 4; ++ j ) {
vector[vi ++] = arg[j];
}
} else {
vector[vi ++] = arg;
}
}
// Fill in missing elements with zero
for( ; vi < 4; ++ vi ) {
vector[vi] = 0;
}
return vector;
};
V4.prototype = new V();
V4.prototype.constructor = V4;
return V4;
};
});
define('vector/vector4-api',['require','common/not-implemented','vector/v4'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var V4 = require( "vector/v4" )( FLOAT_ARRAY_TYPE );
function add( v1, v2, result ) {
if( result === v1 ) {
v1[0] += v2[0];
v1[1] += v2[1];
v1[2] += v2[2];
v1[3] += v2[3];
return;
}
if( undefined === result ) {
result = new V4( v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2], v1[3] + v2[3] );
return result;
} else {
result[0] = v1[0] + v2[0];
result[1] = v1[1] + v2[1];
result[2] = v1[2] + v2[2];
result[3] = v1[3] + v2[3];
return;
}
}
function angle( v1, v2 ) {
return Math.acos(
(v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]) /
(Math.sqrt(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2] + v1[3] * v1[3]) *
Math.sqrt(v2[0] * v2[0] + v2[1] * v2[1] + v2[2] * v2[2] + v2[3] * v2[3]) ) );
}
function clear( v ) {
v[0] = 0;
v[1] = 0;
v[2] = 0;
v[3] = 0;
return v;
}
function dot( v1, v2 ) {
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2] + v1[3] * v2[3];
}
function equal( v1, v2, e ) {
e = e || 0.000001;
if( v1.length !== v2.length ) {
return false;
}
var d0 = Math.abs( v1[0] - v2[0] );
var d1 = Math.abs( v1[1] - v2[1] );
var d2 = Math.abs( v1[2] - v2[2] );
var d3 = Math.abs( v1[3] - v2[3] );
if( isNaN( d0 ) || d0 > e ||
isNaN( d1 ) || d1 > e ||
isNaN( d2 ) || d2 > e ||
isNaN( d3 ) || d3 > e ) {
return false;
}
return true;
}
function length( v ) {
var r = 0;
r += v[0] * v[0];
r += v[1] * v[1];
r += v[2] * v[2];
r += v[2] * v[2];
return Math.sqrt( r );
}
function multiply( v, s, result ) {
result = result || new V4();
result[0] = s * v[0];
result[1] = s * v[1];
result[2] = s * v[2];
result[3] = s * v[3];
return result;
}
function negate( v, result ) {
result = result || new V4();
result[0] = -1 * v[0];
result[1] = -1 * v[1];
result[2] = -1 * v[2];
result[3] = -1 * v[3];
return result;
}
function normalize( v, result ) {
result = result || new V4();
var l = length( v );
result[0] = v[0]/l;
result[1] = v[1]/l;
result[2] = v[2]/l;
result[3] = v[3]/l;
return result;
}
function set( v ) {
if( 2 === arguments.length ) {
v[0] = arguments[1][0];
v[1] = arguments[1][1];
v[2] = arguments[1][2];
v[3] = arguments[1][3];
} else {
v[0] = arguments[1];
v[1] = arguments[2];
v[2] = arguments[3];
v[3] = arguments[4];
}
return v;
}
function subtract( v1, v2, result ) {
result = result || new V4();
result[0] = v1[0] - v2[0];
result[1] = v1[1] - v2[1];
result[2] = v1[2] - v2[2];
result[3] = v1[3] - v2[3];
return result;
}
//This does a matrix4 by vector4 transform, which is a matrix multiplication
//The matrix4 is on the left side of the multiplication and is multiplied by
// the vector in column form
function transform( v, m, result ) {
result = result || new V4();
var x = v[0], y = v[1], z = v[2], w = v[3];
result[0] = m[0] * x + m[1] * y + m[2] * z + m[3] * w;
result[1] = m[4] * x + m[5] * y + m[6] * z + m[7] * w;
result[2] = m[8] * x + m[9] * y + m[10] * z + m[11] * w;
result[3] = m[12] * x + m[13] * y + m[14] * z + m[15] * w;
return result;
}
var vector4 = {
add: add,
angle: angle,
clear: clear,
distance: notImplemented,
dot: dot,
equal: equal,
length: length,
limit: notImplemented,
multiply: multiply,
negate: negate,
normalize: normalize,
set: set,
subtract: subtract,
transform: transform,
x: new V4( 1, 0, 0, 0 ),
y: new V4( 0, 1, 0, 0 ),
z: new V4( 0, 0, 1, 0 ),
w: new V4( 0, 0, 0, 1 ),
zero: new V4( 0, 0, 0, 0 ),
one: new V4( 1, 1, 1, 1 )
};
return vector4;
};
});
define('vector/vector4',['require','../../lib/lodash','common/not-implemented','vector/v4','vector/vector4-api','matrix/matrix','vector/vector'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var _ = require( "../../lib/lodash" );
var notImplemented = require( "common/not-implemented" );
var V4 = require( "vector/v4" )( FLOAT_ARRAY_TYPE );
var vector4 = require( "vector/vector4-api" )( FLOAT_ARRAY_TYPE );
var Matrix = require( "matrix/matrix" );
var Vector = require( "vector/vector" );
function getValue( index ) {
return this.buffer[index];
}
function setValue( index, value ) {
this.buffer[index] = value;
this.modified = true;
}
var Vector4 = function( arg1, arg2, arg3, arg4 ) {
var argc = arguments.length;
this.buffer = new V4(
(arg1 instanceof Vector) ? arg1.buffer : arg1,
(arg2 instanceof Vector) ? arg2.buffer : arg2,
(arg3 instanceof Vector) ? arg3.buffer : arg3,
(arg4 instanceof Vector) ? arg4.buffer : arg4
);
Object.defineProperties( this, {
x: {
get: getValue.bind( this, 0 ),
set: setValue.bind( this, 0 )
},
y: {
get: getValue.bind( this, 1 ),
set: setValue.bind( this, 1 )
},
z: {
get: getValue.bind( this, 2 ),
set: setValue.bind( this, 2 )
},
w: {
get: getValue.bind( this, 3 ),
set: setValue.bind( this, 3 )
}
});
this.modified = true;
this.size = 4;
};
Vector4.prototype = new Vector();
Vector4.prototype.constructor = Vector4;
function add( arg, result ) {
var other;
if( arg instanceof Vector4 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector4.add( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function angle( arg ) {
var other;
if( arg instanceof Vector4 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector4.angle( this.buffer, other );
}
function clear() {
vector4.clear( this.buffer );
this.modified = true;
return this;
}
function clone() {
return new Vector4( this );
}
function dot( arg ) {
var other;
if( arg instanceof Vector4 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector4.dot( this.buffer, other );
}
function equal( arg ) {
var other;
if( arg instanceof Vector4 ) {
other = arg.buffer;
} else {
other = arg;
}
return vector4.equal( this.buffer, other );
}
function length() {
return vector4.length( this.buffer );
}
function multiply( arg, result ) {
result = result || this;
vector4.multiply( this.buffer, arg, result.buffer );
result.modified = true;
return this;
}
function negate( result ) {
result = result || this;
vector4.negate( this.buffer, result.buffer );
result.modified = true;
return this;
}
function normalize( result ) {
result = result || this;
vector4.normalize( this.buffer, result.buffer );
result.modified = true;
return this;
}
function set( arg1, arg2, arg3, arg4 ) {
var argc = arguments.length;
var buffer = this.buffer;
if( 1 === argc ) {
if( arg1 instanceof Vector4 ) {
var other = arg1.buffer;
buffer[0] = other[0];
buffer[1] = other[1];
buffer[2] = other[2];
buffer[3] = other[3];
this.modified = true;
} else {
buffer[0] = arg1[0];
buffer[1] = arg1[1];
buffer[2] = arg1[2];
buffer[3] = arg1[3];
this.modified = true;
}
} else if( 4 === argc ) {
buffer[0] = arg1;
buffer[1] = arg2;
buffer[2] = arg3;
buffer[3] = arg4;
this.modified = true;
}
return this;
}
function subtract( arg, result ) {
var other;
if( arg instanceof Vector4 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector4.subtract( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function transform( arg, result ) {
var other;
if( arg instanceof Matrix ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
vector4.transform( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
_.extend( Vector4.prototype, {
add: add,
angle: angle,
clear: clear,
clone: clone,
distance: notImplemented,
dot: dot,
equal: equal,
length: length,
multiply: multiply,
negate: negate,
normalize: normalize,
set: set,
subtract: subtract,
transform: transform
});
return Vector4;
};
});
define('matrix/m',['require'],function ( require ) {
var M = function() {
};
return M;
});
define('matrix/m2',['require','matrix/m'],function ( require ) {
var M = require( "matrix/m" );
return function( FLOAT_ARRAY_TYPE ) {
var M2 = function() {
var elements = null;
var argc = arguments.length;
if( 1 === argc) {
elements = arguments[0];
} else if( 0 === argc ) {
elements = [0, 0,
0, 0];
} else {
elements = arguments;
}
var matrix = new FLOAT_ARRAY_TYPE( 4 );
for( var i = 0; i < 4; ++ i ) {
matrix[i] = elements[i];
}
return matrix;
};
M2.prototype = new M();
M2.prototype.constructor = M2;
return M2;
};
});
/*!
* Lo-Dash v0.4.1 <http://lodash.com>
* Copyright 2012 John-David Dalton <http://allyoucanleet.com/>
* Based on Underscore.js 1.3.3, copyright 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
* <http://documentcloud.github.com/underscore>
* Available under MIT license <http://lodash.com/license>
*/
;(function(window, undefined) {
/**
* Used to cache the last `_.templateSettings.evaluate` delimiter to avoid
* unnecessarily assigning `reEvaluateDelimiter` a new generated regexp.
* Assigned in `_.template`.
*/
var lastEvaluateDelimiter;
/**
* Used to cache the last template `options.variable` to avoid unnecessarily
* assigning `reDoubleVariable` a new generated regexp. Assigned in `_.template`.
*/
var lastVariable;
/**
* Used to match potentially incorrect data object references, like `obj.obj`,
* in compiled templates. Assigned in `_.template`.
*/
var reDoubleVariable;
/**
* Used to match "evaluate" delimiters, including internal delimiters,
* in template text. Assigned in `_.template`.
*/
var reEvaluateDelimiter;
/** Detect free variable `exports` */
var freeExports = typeof exports == 'object' && exports &&
(typeof global == 'object' && global && global == global.global && (window = global), exports);
/** Native prototype shortcuts */
var ArrayProto = Array.prototype,
ObjectProto = Object.prototype;
/** Used to generate unique IDs */
var idCounter = 0;
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = window._;
/** Used to detect delimiter values that should be processed by `tokenizeEvaluate` */
var reComplexDelimiter = /[-+=!~*%&^<>|{(\/]|\[\D|\b(?:delete|in|instanceof|new|typeof|void)\b/;
/** Used to match empty string literals in compiled template source */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to insert the data object variable into compiled template source */
var reInsertVariable = /(?:__e|__t = )\(\s*(?![\d\s"']|this\.)/g;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
(ObjectProto.valueOf + '')
.replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&')
.replace(/valueOf|for [^\]]+/g, '.+?') + '$'
);
/** Used to match tokens in template text */
var reToken = /__token__(\d+)/g;
/** Used to match unescaped characters in strings for inclusion in HTML */
var reUnescapedHtml = /[&<"']/g;
/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
/** Used to fix the JScript [[DontEnum]] bug */
var shadowed = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used to make template sourceURLs easier to identify */
var templateCounter = 0;
/** Used to replace template delimiters */
var token = '__token__';
/** Used to store tokenized template text snippets */
var tokenized = [];
/** Native method shortcuts */
var concat = ArrayProto.concat,
hasOwnProperty = ObjectProto.hasOwnProperty,
push = ArrayProto.push,
propertyIsEnumerable = ObjectProto.propertyIsEnumerable,
slice = ArrayProto.slice,
toString = ObjectProto.toString;
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind,
nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
nativeIsFinite = window.isFinite,
nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys;
/** `Object#toString` result shortcuts */
var arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
funcClass = '[object Function]',
numberClass = '[object Number]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Timer shortcuts */
var clearTimeout = window.clearTimeout,
setTimeout = window.setTimeout;
/**
* Detect the JScript [[DontEnum]] bug:
* In IE < 9 an objects own properties, shadowing non-enumerable ones, are
* made non-enumerable as well.
*/
var hasDontEnumBug = !propertyIsEnumerable.call({ 'valueOf': 0 }, 'valueOf');
/** Detect if `Array#slice` cannot be used to convert strings to arrays (e.g. Opera < 10.52) */
var noArraySliceOnStrings = slice.call('x')[0] != 'x';
/**
* Detect lack of support for accessing string characters by index:
* IE < 8 can't access characters by index and IE 8 can only access
* characters by index on string literals.
*/
var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx';
/* Detect if `Function#bind` exists and is inferred to be fast (i.e. all but V8) */
var isBindFast = nativeBind && /\n|Opera/.test(nativeBind + toString.call(window.opera));
/* Detect if `Object.keys` exists and is inferred to be fast (i.e. V8, Opera, IE) */
var isKeysFast = nativeKeys && /^.+$|true/.test(nativeKeys + !!window.attachEvent);
/** Detect if sourceURL syntax is usable without erroring */
try {
// Adobe's and Narwhal's JS engines will error
var useSourceURL = (Function('//@')(), true);
} catch(e){ }
/**
* Used to escape characters for inclusion in HTML.
* The `>` and `/` characters don't require escaping in HTML and have no
* special meaning unless they're part of a tag or an unquoted attribute value
* http://mathiasbynens.be/notes/ambiguous-ampersands (semi-related fun fact)
*/
var htmlEscapes = {
'&': '&',
'<': '<',
'"': '"',
"'": '''
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/*--------------------------------------------------------------------------*/
/**
* The `lodash` function.
*
* @name _
* @constructor
* @param {Mixed} value The value to wrap in a `LoDash` instance.
* @returns {Object} Returns a `LoDash` instance.
*/
function lodash(value) {
// allow invoking `lodash` without the `new` operator
return new LoDash(value);
}
/**
* Creates a `LoDash` instance that wraps a value to allow chaining.
*
* @private
* @constructor
* @param {Mixed} value The value to wrap.
*/
function LoDash(value) {
// exit early if already wrapped
if (value && value._wrapped) {
return value;
}
this._wrapped = value;
}
/**
* By default, Lo-Dash uses embedded Ruby (ERB) style template delimiters,
* change the following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': /<%-([\s\S]+?)%>/g,
/**
* Used to detect code to be evaluated.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': /<%([\s\S]+?)%>/g,
/**
* Used to detect `data` property values to inject.
*
* @static
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': /<%=([\s\S]+?)%>/g,
/**
* Used to reference the data object in the template text.
*
* @static
* @memberOf _.templateSettings
* @type String
*/
'variable': 'obj'
};
/*--------------------------------------------------------------------------*/
/**
* The template used to create iterator functions.
*
* @private
* @param {Obect} data The data object used to populate the text.
* @returns {String} Returns the interpolated text.
*/
var iteratorTemplate = template(
// assign the `result` variable an initial value
'var result<% if (init) { %> = <%= init %><% } %>;\n' +
// add code to exit early or do so if the first argument is falsey
'<%= exit %>;\n' +
// add code after the exit snippet but before the iteration branches
'<%= top %>;\n' +
'var index, iteratee = <%= iteratee %>;\n' +
// the following branch is for iterating arrays and array-like objects
'<% if (arrayBranch) { %>' +
'var length = iteratee.length; index = -1;' +
' <% if (objectBranch) { %>\nif (length === length >>> 0) {<% } %>' +
// add support for accessing string characters by index if needed
' <% if (noCharByIndex) { %>\n' +
' if (toString.call(iteratee) == stringClass) {\n' +
' iteratee = iteratee.split(\'\')\n' +
' }' +
' <% } %>\n' +
' <%= arrayBranch.beforeLoop %>;\n' +
' while (++index < length) {\n' +
' <%= arrayBranch.inLoop %>\n' +
' }' +
' <% if (objectBranch) { %>\n}<% } %>' +
'<% } %>' +
// the following branch is for iterating an object's own/inherited properties
'<% if (objectBranch) { %>' +
' <% if (arrayBranch) { %>\nelse {<% } %>' +
' <% if (!hasDontEnumBug) { %>\n' +
' var skipProto = typeof iteratee == \'function\' && \n' +
' propertyIsEnumerable.call(iteratee, \'prototype\');\n' +
' <% } %>' +
// iterate own properties using `Object.keys` if it's fast
' <% if (isKeysFast && useHas) { %>\n' +
' var props = nativeKeys(iteratee),\n' +
' propIndex = -1,\n' +
' length = props.length;\n\n' +
' <%= objectBranch.beforeLoop %>;\n' +
' while (++propIndex < length) {\n' +
' index = props[propIndex];\n' +
' if (!(skipProto && index == \'prototype\')) {\n' +
' <%= objectBranch.inLoop %>\n' +
' }\n' +
' }' +
// else using a for-in loop
' <% } else { %>\n' +
' <%= objectBranch.beforeLoop %>;\n' +
' for (index in iteratee) {' +
' <% if (hasDontEnumBug) { %>\n' +
' <% if (useHas) { %>if (hasOwnProperty.call(iteratee, index)) {\n <% } %>' +
' <%= objectBranch.inLoop %>;\n' +
' <% if (useHas) { %>}<% } %>' +
' <% } else { %>\n' +
// Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
// (if the prototype or a property on the prototype has been set)
// incorrectly sets a function's `prototype` property [[Enumerable]]
// value to `true`. Because of this Lo-Dash standardizes on skipping
// the the `prototype` property of functions regardless of its
// [[Enumerable]] value.
' if (!(skipProto && index == \'prototype\')<% if (useHas) { %> &&\n' +
' hasOwnProperty.call(iteratee, index)<% } %>) {\n' +
' <%= objectBranch.inLoop %>\n' +
' }' +
' <% } %>\n' +
' }' +
' <% } %>' +
// Because IE < 9 can't set the `[[Enumerable]]` attribute of an
// existing property and the `constructor` property of a prototype
// defaults to non-enumerable, Lo-Dash skips the `constructor`
// property when it infers it's iterating over a `prototype` object.
' <% if (hasDontEnumBug) { %>\n\n' +
' var ctor = iteratee.constructor;\n' +
' <% for (var k = 0; k < 7; k++) { %>\n' +
' index = \'<%= shadowed[k] %>\';\n' +
' if (<%' +
' if (shadowed[k] == \'constructor\') {' +
' %>!(ctor && ctor.prototype === iteratee) && <%' +
' } %>hasOwnProperty.call(iteratee, index)) {\n' +
' <%= objectBranch.inLoop %>\n' +
' }' +
' <% } %>' +
' <% } %>' +
' <% if (arrayBranch) { %>\n}<% } %>' +
'<% } %>\n' +
// add code to the bottom of the iteration function
'<%= bottom %>;\n' +
// finally, return the `result`
'return result'
);
/**
* Reusable iterator options shared by
* `every`, `filter`, `find`, `forEach`, `forIn`, `forOwn`, `groupBy`, `map`,
* `reject`, `some`, and `sortBy`.
*/
var baseIteratorOptions = {
'args': 'collection, callback, thisArg',
'init': 'collection',
'top':
'if (!callback) {\n' +
' callback = identity\n' +
'}\n' +
'else if (thisArg) {\n' +
' callback = iteratorBind(callback, thisArg)\n' +
'}',
'inLoop': 'callback(iteratee[index], index, collection)'
};
/** Reusable iterator options for `every` and `some` */
var everyIteratorOptions = {
'init': 'true',
'inLoop': 'if (!callback(iteratee[index], index, collection)) return !result'
};
/** Reusable iterator options for `defaults` and `extend` */
var extendIteratorOptions = {
'args': 'object',
'init': 'object',
'top':
'for (var source, sourceIndex = 1, length = arguments.length; sourceIndex < length; sourceIndex++) {\n' +
' source = arguments[sourceIndex];\n' +
(hasDontEnumBug ? ' if (source) {' : ''),
'iteratee': 'source',
'useHas': false,
'inLoop': 'result[index] = iteratee[index]',
'bottom': (hasDontEnumBug ? ' }\n' : '') + '}'
};
/** Reusable iterator options for `filter` and `reject` */
var filterIteratorOptions = {
'init': '[]',
'inLoop': 'callback(iteratee[index], index, collection) && result.push(iteratee[index])'
};
/** Reusable iterator options for `find`, `forEach`, `forIn`, and `forOwn` */
var forEachIteratorOptions = {
'top': 'if (thisArg) callback = iteratorBind(callback, thisArg)'
};
/** Reusable iterator options for `forIn` and `forOwn` */
var forOwnIteratorOptions = {
'inLoop': {
'object': baseIteratorOptions.inLoop
}
};
/** Reusable iterator options for `invoke`, `map`, `pluck`, and `sortBy` */
var mapIteratorOptions = {
'init': '',
'exit': 'if (!collection) return []',
'beforeLoop': {
'array': 'result = Array(length)',
'object': 'result = ' + (isKeysFast ? 'Array(length)' : '[]')
},
'inLoop': {
'array': 'result[index] = callback(iteratee[index], index, collection)',
'object': 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '(callback(iteratee[index], index, collection))'
}
};
/*--------------------------------------------------------------------------*/
/**
* Creates compiled iteration functions. The iteration function will be created
* to iterate over only objects if the first argument of `options.args` is
* "object" or `options.inLoop.array` is falsey.
*
* @private
* @param {Object} [options1, options2, ...] The compile options objects.
*
* args - A string of comma separated arguments the iteration function will
* accept.
*
* init - A string to specify the initial value of the `result` variable.
*
* exit - A string of code to use in place of the default exit-early check
* of `if (!arguments[0]) return result`.
*
* top - A string of code to execute after the exit-early check but before
* the iteration branches.
*
* beforeLoop - A string or object containing an "array" or "object" property
* of code to execute before the array or object loops.
*
* iteratee - A string or object containing an "array" or "object" property
* of the variable to be iterated in the loop expression.
*
* useHas - A boolean to specify whether or not to use `hasOwnProperty` checks
* in the object loop.
*
* inLoop - A string or object containing an "array" or "object" property
* of code to execute in the array or object loops.
*
* bottom - A string of code to execute after the iteration branches but
* before the `result` is returned.
*
* @returns {Function} Returns the compiled function.
*/
function createIterator() {
var object,
prop,
value,
index = -1,
length = arguments.length;
// merge options into a template data object
var data = {
'bottom': '',
'exit': '',
'init': '',
'top': '',
'arrayBranch': { 'beforeLoop': '' },
'objectBranch': { 'beforeLoop': '' }
};
while (++index < length) {
object = arguments[index];
for (prop in object) {
value = (value = object[prop]) == null ? '' : value;
// keep this regexp explicit for the build pre-process
if (/beforeLoop|inLoop/.test(prop)) {
if (typeof value == 'string') {
value = { 'array': value, 'object': value };
}
data.arrayBranch[prop] = value.array;
data.objectBranch[prop] = value.object;
} else {
data[prop] = value;
}
}
}
// set additional template `data` values
var args = data.args,
firstArg = /^[^,]+/.exec(args)[0],
iteratee = (data.iteratee = data.iteratee || firstArg);
data.firstArg = firstArg;
data.hasDontEnumBug = hasDontEnumBug;
data.isKeysFast = isKeysFast;
data.shadowed = shadowed;
data.useHas = data.useHas !== false;
if (!('noCharByIndex' in data)) {
data.noCharByIndex = noCharByIndex;
}
if (!data.exit) {
data.exit = 'if (!' + firstArg + ') return result';
}
if (firstArg != 'collection' || !data.arrayBranch.inLoop) {
data.arrayBranch = null;
}
// create the function factory
var factory = Function(
'arrayClass, compareAscending, funcClass, hasOwnProperty, identity, ' +
'iteratorBind, objectTypes, nativeKeys, propertyIsEnumerable, ' +
'slice, stringClass, toString',
' return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}'
);
// return the compiled function
return factory(
arrayClass, compareAscending, funcClass, hasOwnProperty, identity,
iteratorBind, objectTypes, nativeKeys, propertyIsEnumerable, slice,
stringClass, toString
);
}
/**
* Used by `sortBy` to compare transformed values of `collection`, sorting
* them in ascending order.
*
* @private
* @param {Object} a The object to compare to `b`.
* @param {Object} b The object to compare to `a`.
* @returns {Number} Returns `-1` if `a` < `b`, `0` if `a` == `b`, or `1` if `a` > `b`.
*/
function compareAscending(a, b) {
a = a.criteria;
b = b.criteria;
if (a === undefined) {
return 1;
}
if (b === undefined) {
return -1;
}
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* Used by `template` to replace tokens with their corresponding code snippets.
*
* @private
* @param {String} match The matched token.
* @param {String} index The `tokenized` index of the code snippet.
* @returns {String} Returns the code snippet.
*/
function detokenize(match, index) {
return tokenized[index];
}
/**
* Used by `template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeStringChar(match) {
return '\\' + stringEscapes[match];
}
/**
* Used by `escape` to escape characters for inclusion in HTML.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeHtmlChar(match) {
return htmlEscapes[match];
}
/**
* Creates a new function that, when called, invokes `func` with the `this`
* binding of `thisArg` and the arguments (value, index, object).
*
* @private
* @param {Function} func The function to bind.
* @param {Mixed} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new bound function.
*/
function iteratorBind(func, thisArg) {
return function(value, index, object) {
return func.call(thisArg, value, index, object);
};
}
/**
* A no-operation function.
*
* @private
*/
function noop() {
// no operation performed
}
/**
* A shim implementation of `Object.keys` that produces an array of the given
* object's own enumerable property names.
*
* @private
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names.
*/
var shimKeys = createIterator({
'args': 'object',
'exit': 'if (!(object && objectTypes[typeof object])) throw TypeError()',
'init': '[]',
'inLoop': 'result.push(index)'
});
/**
* Used by `template` to replace "escape" template delimiters with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeEscape(match, value) {
if (reComplexDelimiter.test(value)) {
return '<e%-' + value + '%>';
}
var index = tokenized.length;
tokenized[index] = "' +\n__e(" + value + ") +\n'";
return token + index;
}
/**
* Used by `template` to replace "evaluate" template delimiters, or complex
* "escape" and "interpolate" delimiters, with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @param {String} escapeValue The "escape" delimiter value.
* @param {String} interpolateValue The "interpolate" delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeEvaluate(match, value, escapeValue, interpolateValue) {
var index = tokenized.length;
if (value) {
tokenized[index] = "';\n" + value + ";\n__p += '"
} else if (escapeValue) {
tokenized[index] = "' +\n__e(" + escapeValue + ") +\n'";
} else if (interpolateValue) {
tokenized[index] = "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
return token + index;
}
/**
* Used by `template` to replace "interpolate" template delimiters with tokens.
*
* @private
* @param {String} match The matched template delimiter.
* @param {String} value The delimiter value.
* @returns {String} Returns a token.
*/
function tokenizeInterpolate(match, value) {
if (reComplexDelimiter.test(value)) {
return '<e%=' + value + '%>';
}
var index = tokenized.length;
tokenized[index] = "' +\n((__t = (" + value + ")) == null ? '' : __t) +\n'";
return token + index;
}
/*--------------------------------------------------------------------------*/
/**
* Checks if a given `target` value is present in a `collection` using strict
* equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @alias include
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Mixed} target The value to check for.
* @returns {Boolean} Returns `true` if `target` value is found, else `false`.
* @example
*
* _.contains([1, 2, 3], 3);
* // => true
*
* _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
* // => true
*
* _.contains('curly', 'ur');
* // => true
*/
var contains = createIterator({
'args': 'collection, target',
'init': 'false',
'noCharByIndex': false,
'beforeLoop': {
'array': 'if (toString.call(iteratee) == stringClass) return collection.indexOf(target) > -1'
},
'inLoop': 'if (iteratee[index] === target) return true'
});
/**
* Checks if the `callback` returns a truthy value for **all** elements of a
* `collection`. The `callback` is bound to `thisArg` and invoked with 3
* arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object).
*
* @static
* @memberOf _
* @alias all
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Boolean} Returns `true` if all values pass the callback check, else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*/
var every = createIterator(baseIteratorOptions, everyIteratorOptions);
/**
* Examines each value in a `collection`, returning an array of all values the
* `callback` returns truthy for. The `callback` is bound to `thisArg` and
* invoked with 3 arguments; for arrays they are (value, index, array) and for
* objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values that passed callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*/
var filter = createIterator(baseIteratorOptions, filterIteratorOptions);
/**
* Examines each value in a `collection`, returning the first one the `callback`
* returns truthy for. The function returns as soon as it finds an acceptable
* value, and does not iterate over the entire `collection`. The `callback` is
* bound to `thisArg` and invoked with 3 arguments; for arrays they are
* (value, index, array) and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias detect
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the value that passed the callback check, else `undefined`.
* @example
*
* var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => 2
*/
var find = createIterator(baseIteratorOptions, forEachIteratorOptions, {
'init': '',
'inLoop': 'if (callback(iteratee[index], index, collection)) return iteratee[index]'
});
/**
* Iterates over a `collection`, executing the `callback` for each value in the
* `collection`. The `callback` is bound to `thisArg` and invoked with 3
* arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object).
*
* @static
* @memberOf _
* @alias each
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array|Object} Returns the `collection`.
* @example
*
* _([1, 2, 3]).forEach(alert).join(',');
* // => alerts each number and returns '1,2,3'
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
* // => alerts each number (order is not guaranteed)
*/
var forEach = createIterator(baseIteratorOptions, forEachIteratorOptions);
/**
* Splits `collection` into sets, grouped by the result of running each value
* through `callback`. The `callback` is bound to `thisArg` and invoked with
* 3 arguments; for arrays they are (value, index, array) and for objects they
* are (value, key, object). The `callback` argument may also be the name of a
* property to group by.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|String} callback The function called per iteration or
* property name to group by.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Object} Returns an object of grouped values.
* @example
*
* _.groupBy([1.3, 2.1, 2.4], function(num) { return Math.floor(num); });
* // => { '1': [1.3], '2': [2.1, 2.4] }
*
* _.groupBy([1.3, 2.1, 2.4], function(num) { return this.floor(num); }, Math);
* // => { '1': [1.3], '2': [2.1, 2.4] }
*
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createIterator(baseIteratorOptions, {
'init': '{}',
'top':
'var prop, isFunc = typeof callback == \'function\';\n' +
'if (isFunc && thisArg) callback = iteratorBind(callback, thisArg)',
'inLoop':
'prop = isFunc\n' +
' ? callback(iteratee[index], index, collection)\n' +
' : iteratee[index][callback];\n' +
'(hasOwnProperty.call(result, prop) ? result[prop] : result[prop] = []).push(iteratee[index])'
});
/**
* Invokes the method named by `methodName` on each element in the `collection`.
* Additional arguments will be passed to each invoked method. If `methodName`
* is a function it will be invoked for, and `this` bound to, each element
* in the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|String} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
* @returns {Array} Returns a new array of values returned from each invoked method.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invoke = createIterator(mapIteratorOptions, {
'args': 'collection, methodName',
'top':
'var args = slice.call(arguments, 2),\n' +
' isFunc = typeof methodName == \'function\'',
'inLoop': {
'array':
'result[index] = (isFunc ? methodName : iteratee[index][methodName])' +
'.apply(iteratee[index], args)',
'object':
'result' + (isKeysFast ? '[propIndex] = ' : '.push') +
'((isFunc ? methodName : iteratee[index][methodName]).apply(iteratee[index], args))'
}
});
/**
* Produces a new array of values by mapping each element in the `collection`
* through a transformation `callback`. The `callback` is bound to `thisArg`
* and invoked with 3 arguments; for arrays they are (value, index, array)
* and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values returned by the callback.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (order is not guaranteed)
*/
var map = createIterator(baseIteratorOptions, mapIteratorOptions);
/**
* Retrieves the value of a specified property from all elements in
* the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {String} property The property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* _.pluck(stooges, 'name');
* // => ['moe', 'larry', 'curly']
*/
var pluck = createIterator(mapIteratorOptions, {
'args': 'collection, property',
'inLoop': {
'array': 'result[index] = iteratee[index][property]',
'object': 'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '(iteratee[index][property])'
}
});
/**
* Boils down a `collection` to a single value. The initial state of the
* reduction is `accumulator` and each successive step of it should be returned
* by the `callback`. The `callback` is bound to `thisArg` and invoked with 4
* arguments; for arrays they are (accumulator, value, index, array) and for
* objects they are (accumulator, value, key, object).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; });
* // => 6
*/
var reduce = createIterator({
'args': 'collection, callback, accumulator, thisArg',
'init': 'accumulator',
'top':
'var noaccum = arguments.length < 3;\n' +
'if (thisArg) callback = iteratorBind(callback, thisArg)',
'beforeLoop': {
'array': 'if (noaccum) result = collection[++index]'
},
'inLoop': {
'array':
'result = callback(result, iteratee[index], index, collection)',
'object':
'result = noaccum\n' +
' ? (noaccum = false, iteratee[index])\n' +
' : callback(result, iteratee[index], index, collection)'
}
});
/**
* The right-associative version of `_.reduce`.
*
* @static
* @memberOf _
* @alias foldr
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var list = [[0, 1], [2, 3], [4, 5]];
* var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, callback, accumulator, thisArg) {
if (!collection) {
return accumulator;
}
var length = collection.length,
noaccum = arguments.length < 3;
if(thisArg) {
callback = iteratorBind(callback, thisArg);
}
if (length === length >>> 0) {
var iteratee = noCharByIndex && toString.call(collection) == stringClass
? collection.split('')
: collection;
if (length && noaccum) {
accumulator = iteratee[--length];
}
while (length--) {
accumulator = callback(accumulator, iteratee[length], length, collection);
}
return accumulator;
}
var prop,
props = keys(collection);
length = props.length;
if (length && noaccum) {
accumulator = collection[props[--length]];
}
while (length--) {
prop = props[length];
accumulator = callback(accumulator, collection[prop], prop, collection);
}
return accumulator;
}
/**
* The opposite of `_.filter`, this method returns the values of a `collection`
* that `callback` does **not** return truthy for.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of values that did **not** pass the callback check.
* @example
*
* var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [1, 3, 5]
*/
var reject = createIterator(baseIteratorOptions, filterIteratorOptions, {
'inLoop': '!' + filterIteratorOptions.inLoop
});
/**
* Checks if the `callback` returns a truthy value for **any** element of a
* `collection`. The function returns as soon as it finds passing value, and
* does not iterate over the entire `collection`. The `callback` is bound to
* `thisArg` and invoked with 3 arguments; for arrays they are
* (value, index, array) and for objects they are (value, key, object).
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Boolean} Returns `true` if any value passes the callback check, else `false`.
* @example
*
* _.some([null, 0, 'yes', false]);
* // => true
*/
var some = createIterator(baseIteratorOptions, everyIteratorOptions, {
'init': 'false',
'inLoop': everyIteratorOptions.inLoop.replace('!', '')
});
/**
* Produces a new sorted array, sorted in ascending order by the results of
* running each element of `collection` through a transformation `callback`.
* The `callback` is bound to `thisArg` and invoked with 3 arguments;
* for arrays they are (value, index, array) and for objects they are
* (value, key, object). The `callback` argument may also be the name of a
* property to sort by (e.g. 'length').
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|String} callback The function called per iteration or
* property name to sort by.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a new array of sorted values.
* @example
*
* _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
* // => [3, 1, 2]
*
* _.sortBy(['larry', 'brendan', 'moe'], 'length');
* // => ['moe', 'larry', 'brendan']
*/
var sortBy = createIterator(baseIteratorOptions, mapIteratorOptions, {
'top':
'if (typeof callback == \'string\') {\n' +
' var prop = callback;\n' +
' callback = function(collection) { return collection[prop] }\n' +
'}\n' +
'else if (thisArg) {\n' +
' callback = iteratorBind(callback, thisArg)\n' +
'}',
'inLoop': {
'array':
'result[index] = {\n' +
' criteria: callback(iteratee[index], index, collection),\n' +
' value: iteratee[index]\n' +
'}',
'object':
'result' + (isKeysFast ? '[propIndex] = ' : '.push') + '({\n' +
' criteria: callback(iteratee[index], index, collection),\n' +
' value: iteratee[index]\n' +
'})'
},
'bottom':
'result.sort(compareAscending);\n' +
'length = result.length;\n' +
'while (length--) {\n' +
' result[length] = result[length].value\n' +
'}'
});
/**
* Converts the `collection`, into an array. Useful for converting the
* `arguments` object.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to convert.
* @returns {Array} Returns the new converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
* // => [2, 3, 4]
*/
function toArray(collection) {
if (!collection) {
return [];
}
if (collection.toArray && toString.call(collection.toArray) == funcClass) {
return collection.toArray();
}
var length = collection.length;
if (length === length >>> 0) {
return (noArraySliceOnStrings ? toString.call(collection) == stringClass : typeof collection == 'string')
? collection.split('')
: slice.call(collection);
}
return values(collection);
}
/*--------------------------------------------------------------------------*/
/**
* Produces a new array with all falsey values of `array` removed. The values
* `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @returns {Array} Returns a new filtered array.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length;
while (++index < length) {
if (array[index]) {
result.push(array[index]);
}
}
return result;
}
/**
* Produces a new array of `array` values not present in the other arrays
* using strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {Array} [array1, array2, ...] Arrays to check.
* @returns {Array} Returns a new array of `array` values not present in the
* other arrays.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
function difference(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length,
flattened = concat.apply(result, arguments);
while (++index < length) {
if (indexOf(flattened, array[index], length) < 0) {
result.push(array[index]);
}
}
return result;
}
/**
* Gets the first value of the `array`. Pass `n` to return the first `n` values
* of the `array`.
*
* @static
* @memberOf _
* @alias head, take
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Mixed} Returns the first value or an array of the first `n` values
* of `array`.
* @example
*
* _.first([5, 4, 3, 2, 1]);
* // => 5
*/
function first(array, n, guard) {
if (array) {
return (n == null || guard) ? array[0] : slice.call(array, 0, n);
}
}
/**
* Flattens a nested array (the nesting can be to any depth). If `shallow` is
* truthy, `array` will only be flattened a single level.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @param {Boolean} shallow A flag to indicate only flattening a single level.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
*/
function flatten(array, shallow) {
var result = [];
if (!array) {
return result;
}
var value,
index = -1,
length = array.length;
while (++index < length) {
value = array[index];
if (isArray(value)) {
push.apply(result, shallow ? value : flatten(value));
} else {
result.push(value);
}
}
return result;
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`. If the `array` is already
* sorted, passing `true` for `isSorted` will run a faster binary search.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @param {Boolean|Number} [fromIndex=0] The index to start searching from or
* `true` to perform a binary search on a sorted `array`.
* @returns {Number} Returns the index of the matched value or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
if (!array) {
return -1;
}
var index = -1,
length = array.length;
if (fromIndex) {
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? Math.max(0, length + fromIndex) : fromIndex) - 1;
} else {
index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
}
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Gets all but the last value of `array`. Pass `n` to exclude the last `n`
* values from the result.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Array} Returns all but the last value or `n` values of `array`.
* @example
*
* _.initial([3, 2, 1]);
* // => [3, 2]
*/
function initial(array, n, guard) {
if (!array) {
return [];
}
return slice.call(array, 0, -((n == null || guard) ? 1 : n));
}
/**
* Computes the intersection of all the passed-in arrays.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of unique values, in order, that are
* present in **all** of the arrays.
* @example
*
* _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
* // => [1, 2]
*/
function intersection(array) {
var result = [];
if (!array) {
return result;
}
var value,
index = -1,
length = array.length,
others = slice.call(arguments, 1);
while (++index < length) {
value = array[index];
if (indexOf(result, value) < 0 &&
every(others, function(other) { return indexOf(other, value) > -1; })) {
result.push(value);
}
}
return result;
}
/**
* Gets the last value of the `array`. Pass `n` to return the lasy `n` values
* of the `array`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Mixed} Returns the last value or an array of the last `n` values
* of `array`.
* @example
*
* _.last([3, 2, 1]);
* // => 1
*/
function last(array, n, guard) {
if (array) {
var length = array.length;
return (n == null || guard) ? array[length - 1] : slice.call(array, -n || length);
}
}
/**
* Gets the index at which the last occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @param {Number} [fromIndex=array.length-1] The index to start searching from.
* @returns {Number} Returns the index of the matched value or `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
if (!array) {
return -1;
}
var index = array.length;
if (fromIndex && typeof fromIndex == 'number') {
index = (fromIndex < 0 ? Math.max(0, index + fromIndex) : Math.min(fromIndex, index - 1)) + 1;
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Retrieves the maximum value of an `array`. If `callback` is passed,
* it will be executed for each value in the `array` to generate the
* criterion by which the value is ranked. The `callback` is bound to
* `thisArg` and invoked with 3 arguments; (value, index, array).
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to iterate over.
* @param {Function} [callback] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the maximum value.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* _.max(stooges, function(stooge) { return stooge.age; });
* // => { 'name': 'curly', 'age': 60 };
*/
function max(array, callback, thisArg) {
var computed = -Infinity,
result = computed;
if (!array) {
return result;
}
var current,
index = -1,
length = array.length;
if (!callback) {
while (++index < length) {
if (array[index] > result) {
result = array[index];
}
}
return result;
}
if (thisArg) {
callback = iteratorBind(callback, thisArg);
}
while (++index < length) {
current = callback(array[index], index, array);
if (current > computed) {
computed = current;
result = array[index];
}
}
return result;
}
/**
* Retrieves the minimum value of an `array`. If `callback` is passed,
* it will be executed for each value in the `array` to generate the
* criterion by which the value is ranked. The `callback` is bound to `thisArg`
* and invoked with 3 arguments; (value, index, array).
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to iterate over.
* @param {Function} [callback] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Mixed} Returns the minimum value.
* @example
*
* _.min([10, 5, 100, 2, 1000]);
* // => 2
*/
function min(array, callback, thisArg) {
var computed = Infinity,
result = computed;
if (!array) {
return result;
}
var current,
index = -1,
length = array.length;
if (!callback) {
while (++index < length) {
if (array[index] < result) {
result = array[index];
}
}
return result;
}
if (thisArg) {
callback = iteratorBind(callback, thisArg);
}
while (++index < length) {
current = callback(array[index], index, array);
if (current < computed) {
computed = current;
result = array[index];
}
}
return result;
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to but not including `stop`. This method is a port of Python's
* `range()` function. See http://docs.python.org/library/functions.html#range.
*
* @static
* @memberOf _
* @category Arrays
* @param {Number} [start=0] The start of the range.
* @param {Number} end The end of the range.
* @param {Number} [step=1] The value to increment or descrement by.
* @returns {Array} Returns a new range array.
* @example
*
* _.range(10);
* // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
*
* _.range(1, 11);
* // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*
* _.range(0, 30, 5);
* // => [0, 5, 10, 15, 20, 25]
*
* _.range(0, -10, -1);
* // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
*
* _.range(0);
* // => []
*/
function range(start, end, step) {
step || (step = 1);
if (end == null) {
end = start || 0;
start = 0;
}
// use `Array(length)` so V8 will avoid the slower "dictionary" mode
// http://www.youtube.com/watch?v=XAqIpGU8ZZk#t=16m27s
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* The opposite of `_.initial`, this method gets all but the first value of
* `array`. Pass `n` to exclude the first `n` values from the result.
*
* @static
* @memberOf _
* @alias tail
* @category Arrays
* @param {Array} array The array to query.
* @param {Number} [n] The number of elements to return.
* @param {Object} [guard] Internally used to allow this method to work with
* others like `_.map` without using their callback `index` argument for `n`.
* @returns {Array} Returns all but the first value or `n` values of `array`.
* @example
*
* _.rest([3, 2, 1]);
* // => [2, 1]
*/
function rest(array, n, guard) {
if (!array) {
return [];
}
return slice.call(array, (n == null || guard) ? 1 : n);
}
/**
* Produces a new array of shuffled `array` values, using a version of the
* Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to shuffle.
* @returns {Array} Returns a new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(array) {
if (!array) {
return [];
}
var rand,
index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
rand = Math.floor(Math.random() * (index + 1));
result[index] = result[rand];
result[rand] = array[index];
}
return result;
}
/**
* Uses a binary search to determine the smallest index at which the `value`
* should be inserted into `array` in order to maintain the sort order of the
* sorted `array`. If `callback` is passed, it will be executed for `value` and
* each element in `array` to compute their sort ranking. The `callback` is
* bound to `thisArg` and invoked with 1 argument; (value).
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to iterate over.
* @param {Mixed} value The value to evaluate.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Number} Returns the index at which the value should be inserted
* into `array`.
* @example
*
* _.sortedIndex([20, 30, 40], 35);
* // => 2
*
* var dict = {
* 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'thirty-five': 35, 'fourty': 40 }
* };
*
* _.sortedIndex(['twenty', 'thirty', 'fourty'], 'thirty-five', function(word) {
* return dict.wordToNumber[word];
* });
* // => 2
*
* _.sortedIndex(['twenty', 'thirty', 'fourty'], 'thirty-five', function(word) {
* return this.wordToNumber[word];
* }, dict);
* // => 2
*/
function sortedIndex(array, value, callback, thisArg) {
if (!array) {
return 0;
}
var mid,
low = 0,
high = array.length;
if (callback) {
if (thisArg) {
callback = bind(callback, thisArg);
}
value = callback(value);
while (low < high) {
mid = (low + high) >>> 1;
callback(array[mid]) < value ? low = mid + 1 : high = mid;
}
} else {
while (low < high) {
mid = (low + high) >>> 1;
array[mid] < value ? low = mid + 1 : high = mid;
}
}
return low;
}
/**
* Computes the union of the passed-in arrays.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of unique values, in order, that are
* present in one or more of the arrays.
* @example
*
* _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
* // => [1, 2, 3, 101, 10]
*/
function union() {
var index = -1,
result = [],
flattened = concat.apply(result, arguments),
length = flattened.length;
while (++index < length) {
if (indexOf(result, flattened[index]) < 0) {
result.push(flattened[index]);
}
}
return result;
}
/**
* Produces a duplicate-value-free version of the `array` using strict equality
* for comparisons, i.e. `===`. If the `array` is already sorted, passing `true`
* for `isSorted` will run a faster algorithm. If `callback` is passed,
* each value of `array` is passed through a transformation `callback` before
* uniqueness is computed. The `callback` is bound to `thisArg` and invoked
* with 3 arguments; (value, index, array).
*
* @static
* @memberOf _
* @alias unique
* @category Arrays
* @param {Array} array The array to process.
* @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Array} Returns a duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1, 3, 1]);
* // => [1, 2, 3]
*
* _.uniq([1, 1, 2, 2, 3], true);
* // => [1, 2, 3]
*
* _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); });
* // => [1, 2, 3]
*
* _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math);
* // => [1, 2, 3]
*/
function uniq(array, isSorted, callback, thisArg) {
var result = [];
if (!array) {
return result;
}
var computed,
index = -1,
length = array.length,
seen = [];
// juggle arguments
if (typeof isSorted == 'function') {
thisArg = callback;
callback = isSorted;
isSorted = false;
}
if (!callback) {
callback = identity;
} else if (thisArg) {
callback = iteratorBind(callback, thisArg);
}
while (++index < length) {
computed = callback(array[index], index, array);
if (isSorted
? !index || seen[seen.length - 1] !== computed
: indexOf(seen, computed) < 0
) {
seen.push(computed);
result.push(array[index]);
}
}
return result;
}
/**
* Produces a new array with all occurrences of the passed values removed using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to filter.
* @param {Mixed} [value1, value2, ...] Values to remove.
* @returns {Array} Returns a new filtered array.
* @example
*
* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
* // => [2, 3, 4]
*/
function without(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length;
while (++index < length) {
if (indexOf(arguments, array[index], 1) < 0) {
result.push(array[index]);
}
}
return result;
}
/**
* Merges the elements of each array at their corresponding indexes. Useful for
* separate data sources that are coordinated through matching array indexes.
* For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix
* in a similar fashion.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of merged arrays.
* @example
*
* _.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
* // => [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]]
*/
function zip(array) {
if (!array) {
return [];
}
var index = -1,
length = max(pluck(arguments, 'length')),
result = Array(length);
while (++index < length) {
result[index] = pluck(arguments, index);
}
return result;
}
/**
* Merges an array of `keys` and an array of `values` into a single object.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} keys The array of keys.
* @param {Array} [values=[]] The array of values.
* @returns {Object} Returns an object composed of the given keys and
* corresponding values.
* @example
*
* _.zipObject(['moe', 'larry', 'curly'], [30, 40, 50]);
* // => { 'moe': 30, 'larry': 40, 'curly': 50 }
*/
function zipObject(keys, values) {
if (!keys) {
return {};
}
var index = -1,
length = keys.length,
result = {};
values || (values = []);
while (++index < length) {
result[keys[index]] = values[index];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new function that is restricted to executing only after it is
* called `n` times.
*
* @static
* @memberOf _
* @category Functions
* @param {Number} n The number of times the function must be called before
* it is executed.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var renderNotes = _.after(notes.length, render);
* _.forEach(notes, function(note) {
* note.asyncSave({ 'success': renderNotes });
* });
* // `renderNotes` is run once, after all notes have saved
*/
function after(n, func) {
if (n < 1) {
return func();
}
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a new function that, when called, invokes `func` with the `this`
* binding of `thisArg` and prepends any additional `bind` arguments to those
* passed to the bound function. Lazy defined methods may be bound by passing
* the object they are bound to as `func` and the method name as `thisArg`.
*
* @static
* @memberOf _
* @category Functions
* @param {Function|Object} func The function to bind or the object the method belongs to.
* @param {Mixed} [thisArg] The `this` binding of `func` or the method name.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* // basic bind
* var func = function(greeting) {
* return greeting + ' ' + this.name;
* };
*
* func = _.bind(func, { 'name': 'moe' }, 'hi');
* func();
* // => 'hi moe'
*
* // lazy bind
* var object = {
* 'name': 'moe',
* 'greet': function(greeting) {
* return greeting + ' ' + this.name;
* }
* };
*
* var func = _.bind(object, 'greet', 'hi');
* func();
* // => 'hi moe'
*
* object.greet = function(greeting) {
* return greeting + ', ' + this.name + '!';
* };
*
* func();
* // => 'hi, moe!'
*/
function bind(func, thisArg) {
var methodName,
isFunc = toString.call(func) == funcClass;
// juggle arguments
if (!isFunc) {
methodName = thisArg;
thisArg = func;
}
// use `Function#bind` if it exists and is fast
// (in V8 `Function#bind` is slower except when partially applied)
else if (isBindFast || (nativeBind && arguments.length > 2)) {
return nativeBind.call.apply(nativeBind, arguments);
}
var partialArgs = slice.call(arguments, 2);
function bound() {
// `Function#bind` spec
// http://es5.github.com/#x15.3.4.5
var args = arguments,
thisBinding = thisArg;
if (!isFunc) {
func = thisArg[methodName];
}
if (partialArgs.length) {
args = args.length
? concat.apply(partialArgs, args)
: partialArgs;
}
if (this instanceof bound) {
// get `func` instance if `bound` is invoked in a `new` expression
noop.prototype = func.prototype;
thisBinding = new noop;
// mimic the constructor's `return` behavior
// http://es5.github.com/#x13.2.2
var result = func.apply(thisBinding, args);
return result && objectTypes[typeof result]
? result
: thisBinding
}
return func.apply(thisBinding, args);
}
return bound;
}
/**
* Binds methods on `object` to `object`, overwriting the existing method.
* If no method names are provided, all the function properties of `object`
* will be bound.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object to bind and assign the bound methods to.
* @param {String} [methodName1, methodName2, ...] Method names on the object to bind.
* @returns {Object} Returns the `object`.
* @example
*
* var buttonView = {
* 'label': 'lodash',
* 'onClick': function() { alert('clicked: ' + this.label); }
* };
*
* _.bindAll(buttonView);
* jQuery('#lodash_button').on('click', buttonView.onClick);
* // => When the button is clicked, `this.label` will have the correct value
*/
function bindAll(object) {
var funcs = arguments,
index = 1;
if (funcs.length == 1) {
index = 0;
funcs = functions(object);
}
for (var length = funcs.length; index < length; index++) {
object[funcs[index]] = bind(object[funcs[index]], object);
}
return object;
}
/**
* Creates a new function that is the composition of the passed functions,
* where each function consumes the return value of the function that follows.
* In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} [func1, func2, ...] Functions to compose.
* @returns {Function} Returns the new composed function.
* @example
*
* var greet = function(name) { return 'hi: ' + name; };
* var exclaim = function(statement) { return statement + '!'; };
* var welcome = _.compose(exclaim, greet);
* welcome('moe');
* // => 'hi: moe!'
*/
function compose() {
var funcs = arguments;
return function() {
var args = arguments,
length = funcs.length;
while (length--) {
args = [funcs[length].apply(this, args)];
}
return args[0];
};
}
/**
* Creates a new function that will delay the execution of `func` until after
* `wait` milliseconds have elapsed since the last time it was invoked. Pass
* `true` for `immediate` to cause debounce to invoke `func` on the leading,
* instead of the trailing, edge of the `wait` timeout. Subsequent calls to
* the debounced function will return the result of the last `func` call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to debounce.
* @param {Number} wait The number of milliseconds to delay.
* @param {Boolean} immediate A flag to indicate execution is on the leading
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* var lazyLayout = _.debounce(calculateLayout, 300);
* jQuery(window).on('resize', lazyLayout);
*/
function debounce(func, wait, immediate) {
var args,
result,
thisArg,
timeoutId;
function delayed() {
timeoutId = null;
if (!immediate) {
func.apply(thisArg, args);
}
}
return function() {
var isImmediate = immediate && !timeoutId;
args = arguments;
thisArg = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(delayed, wait);
if (isImmediate) {
result = func.apply(thisArg, args);
}
return result;
};
}
/**
* Executes the `func` function after `wait` milliseconds. Additional arguments
* are passed to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to delay.
* @param {Number} wait The number of milliseconds to delay execution.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
* @returns {Number} Returns the `setTimeout` timeout id.
* @example
*
* var log = _.bind(console.log, console);
* _.delay(log, 1000, 'logged later');
* // => 'logged later' (Appears after one second.)
*/
function delay(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function() { return func.apply(undefined, args); }, wait);
}
/**
* Defers executing the `func` function until the current call stack has cleared.
* Additional arguments are passed to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to defer.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
* @returns {Number} Returns the `setTimeout` timeout id.
* @example
*
* _.defer(function() { alert('deferred'); });
* // returns from the function before `alert` is called
*/
function defer(func) {
var args = slice.call(arguments, 1);
return setTimeout(function() { return func.apply(undefined, args); }, 1);
}
/**
* Creates a new function that memoizes the result of `func`. If `resolver` is
* passed, it will be used to determine the cache key for storing the result
* based on the arguments passed to the memoized function. By default, the first
* argument passed to the memoized function is used as the cache key.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] A function used to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var fibonacci = _.memoize(function(n) {
* return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
* });
*/
function memoize(func, resolver) {
var cache = {};
return function() {
var prop = resolver ? resolver.apply(this, arguments) : arguments[0];
return hasOwnProperty.call(cache, prop)
? cache[prop]
: (cache[prop] = func.apply(this, arguments));
};
}
/**
* Creates a new function that is restricted to one execution. Repeat calls to
* the function will return the value of the first call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // Application is only created once.
*/
function once(func) {
var result,
ran = false;
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
return result;
};
}
/**
* Creates a new function that, when called, invokes `func` with any additional
* `partial` arguments prepended to those passed to the partially applied
* function. This method is similar `bind`, except it does **not** alter the
* `this` binding.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) { return greeting + ': ' + name; };
* var hi = _.partial(greet, 'hi');
* hi('moe');
* // => 'hi: moe'
*/
function partial(func) {
var args = slice.call(arguments, 1),
argsLength = args.length;
return function() {
var result,
others = arguments;
if (others.length) {
args.length = argsLength;
push.apply(args, others);
}
result = args.length == 1 ? func.call(this, args[0]) : func.apply(this, args);
args.length = argsLength;
return result;
};
}
/**
* Creates a new function that, when executed, will only call the `func`
* function at most once per every `wait` milliseconds. If the throttled
* function is invoked more than once during the `wait` timeout, `func` will
* also be called on the trailing edge of the timeout. Subsequent calls to the
* throttled function will return the result of the last `func` call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to throttle.
* @param {Number} wait The number of milliseconds to throttle executions to.
* @returns {Function} Returns the new throttled function.
* @example
*
* var throttled = _.throttle(updatePosition, 100);
* jQuery(window).on('scroll', throttled);
*/
function throttle(func, wait) {
var args,
result,
thisArg,
timeoutId,
lastCalled = 0;
function trailingCall() {
lastCalled = new Date;
timeoutId = null;
func.apply(thisArg, args);
}
return function() {
var now = new Date,
remain = wait - (now - lastCalled);
args = arguments;
thisArg = this;
if (remain <= 0) {
lastCalled = now;
result = func.apply(thisArg, args);
}
else if (!timeoutId) {
timeoutId = setTimeout(trailingCall, remain);
}
return result;
};
}
/**
* Create a new function that passes the `func` function to the `wrapper`
* function as its first argument. Additional arguments are appended to those
* passed to the `wrapper` function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to wrap.
* @param {Function} wrapper The wrapper function.
* @param {Mixed} [arg1, arg2, ...] Arguments to append to those passed to the wrapper.
* @returns {Function} Returns the new function.
* @example
*
* var hello = function(name) { return 'hello: ' + name; };
* hello = _.wrap(hello, function(func) {
* return 'before, ' + func('moe') + ', after';
* });
* hello();
* // => 'before, hello: moe, after'
*/
function wrap(func, wrapper) {
return function() {
var args = [func];
if (arguments.length) {
push.apply(args, arguments);
}
return wrapper.apply(this, args);
};
}
/*--------------------------------------------------------------------------*/
/**
* Create a shallow clone of the `value`. Any nested objects or arrays will be
* assigned by reference and not cloned.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to clone.
* @returns {Mixed} Returns the cloned `value`.
* @example
*
* _.clone({ 'name': 'moe' });
* // => { 'name': 'moe' };
*/
function clone(value) {
return value && objectTypes[typeof value]
? (isArray(value) ? value.slice() : extend({}, value))
: value;
}
/**
* Assigns missing properties on `object` with default values from the defaults
* objects. Once a property is set, additional defaults of the same property
* will be ignored.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to populate.
* @param {Object} [defaults1, defaults2, ...] The defaults objects to apply to `object`.
* @returns {Object} Returns `object`.
* @example
*
* var iceCream = { 'flavor': 'chocolate' };
* _.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' });
* // => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' }
*/
var defaults = createIterator(extendIteratorOptions, {
'inLoop': 'if (result[index] == null) ' + extendIteratorOptions.inLoop
});
/**
* Copies enumerable properties from the source objects to the `destination` object.
* Subsequent sources will overwrite propery assignments of previous sources.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The destination object.
* @param {Object} [source1, source2, ...] The source objects.
* @returns {Object} Returns the destination object.
* @example
*
* _.extend({ 'name': 'moe' }, { 'age': 40 });
* // => { 'name': 'moe', 'age': 40 }
*/
var extend = createIterator(extendIteratorOptions);
/**
* Iterates over `object`'s own and inherited enumerable properties, executing
* the `callback` for each property. The `callback` is bound to `thisArg` and
* invoked with 3 arguments; (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Object} Returns the `object`.
* @example
*
* function Dog(name) {
* this.name = name;
* }
*
* Dog.prototype.bark = function() {
* alert('Woof, woof!');
* };
*
* _.forIn(new Dog('Dagny'), function(value, key) {
* alert(key);
* });
* // => alerts 'name' and 'bark' (order is not guaranteed)
*/
var forIn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions, {
'useHas': false
});
/**
* Iterates over `object`'s own enumerable properties, executing the `callback`
* for each property. The `callback` is bound to `thisArg` and invoked with 3
* arguments; (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @returns {Object} Returns the `object`.
* @example
*
* _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* alert(key);
* });
* // => alerts '0', '1', and 'length' (order is not guaranteed)
*/
var forOwn = createIterator(baseIteratorOptions, forEachIteratorOptions, forOwnIteratorOptions);
/**
* Produces a sorted array of the enumerable properties, own and inherited,
* of `object` that have function values.
*
* @static
* @memberOf _
* @alias methods
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names that have function values.
* @example
*
* _.functions(_);
* // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
*/
var functions = createIterator({
'args': 'object',
'init': '[]',
'useHas': false,
'inLoop': 'if (toString.call(iteratee[index]) == funcClass) result.push(index)',
'bottom': 'result.sort()'
});
/**
* Checks if the specified object `property` exists and is a direct property,
* instead of an inherited property.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to check.
* @param {String} property The property to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
* @example
*
* _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
* // => true
*/
function has(object, property) {
return hasOwnProperty.call(object, property);
}
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = function(value) {
return toString.call(value) == '[object Arguments]';
};
// fallback for browser like IE < 9 which detect `arguments` as `[object Object]`
if (!isArguments(arguments)) {
isArguments = function(value) {
return !!(value && hasOwnProperty.call(value, 'callee'));
};
}
/**
* Checks if `value` is an array.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
var isArray = nativeIsArray || function(value) {
return toString.call(value) == arrayClass;
};
/**
* Checks if `value` is a boolean (`true` or `false`) value.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a boolean value, else `false`.
* @example
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false || toString.call(value) == boolClass;
}
/**
* Checks if `value` is a date.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a date, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*/
function isDate(value) {
return toString.call(value) == dateClass;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*/
function isElement(value) {
return !!(value && value.nodeType == 1);
}
/**
* Checks if `value` is empty. Arrays or strings with a length of `0` and
* objects with no own enumerable properties are considered "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|String} value The value to inspect.
* @returns {Boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
var isEmpty = createIterator({
'args': 'value',
'init': 'true',
'top':
'var className = toString.call(value);\n' +
'if (className == arrayClass || className == stringClass) return !value.length',
'inLoop': {
'object': 'return false'
}
});
/**
* Performs a deep comparison between two values to determine if they are
* equivalent to each other.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} a The value to compare.
* @param {Mixed} b The other value to compare.
* @param {Array} [stack] Internally used to keep track of "seen" objects to
* avoid circular references.
* @returns {Boolean} Returns `true` if the values are equvalent, else `false`.
* @example
*
* var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
* var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] };
*
* moe == clone;
* // => false
*
* _.isEqual(moe, clone);
* // => true
*/
function isEqual(a, b, stack) {
stack || (stack = []);
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
// a strict comparison is necessary because `undefined == null`
if (a == null || b == null) {
return a === b;
}
// unwrap any wrapped objects
if (a._chain) {
a = a._wrapped;
}
if (b._chain) {
b = b._wrapped;
}
// invoke a custom `isEqual` method if one is provided
if (a.isEqual && toString.call(a.isEqual) == funcClass) {
return a.isEqual(b);
}
if (b.isEqual && toString.call(b.isEqual) == funcClass) {
return b.isEqual(a);
}
// compare [[Class]] names
var className = toString.call(a);
if (className != toString.call(b)) {
return false;
}
switch (className) {
// strings, numbers, dates, and booleans are compared by value
case stringClass:
// primitives and their corresponding object instances are equivalent;
// thus, `'5'` is quivalent to `new String('5')`
return a == String(b);
case numberClass:
// treat `NaN` vs. `NaN` as equal
return a != +a
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case boolClass:
case dateClass:
// coerce dates and booleans to numeric values, dates to milliseconds and booleans to 1 or 0;
// treat invalid dates coerced to `NaN` as not equal
return +a == +b;
// regexps are compared by their source and flags
case regexpClass:
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') {
return false;
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (stack[length] == a) {
return true;
}
}
var index = -1,
result = true,
size = 0;
// add the first collection to the stack of traversed objects
stack.push(a);
// recursively compare objects and arrays
if (className == arrayClass) {
// compare array lengths to determine if a deep comparison is necessary
size = a.length;
result = size == b.length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
if (!(result = isEqual(a[size], b[size], stack))) {
break;
}
}
}
} else {
// objects with different constructors are not equivalent
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) {
return false;
}
// deep compare objects.
for (var prop in a) {
if (hasOwnProperty.call(a, prop)) {
// count the number of properties.
size++;
// deep compare each property value.
if (!(result = hasOwnProperty.call(b, prop) && isEqual(a[prop], b[prop], stack))) {
break;
}
}
}
// ensure both objects have the same number of properties
if (result) {
for (prop in b) {
// Adobe's JS engine, embedded in applications like InDesign, has a
// bug that causes `!size--` to throw an error so it must be wrapped
// in parentheses.
// https://github.com/documentcloud/underscore/issues/355
if (hasOwnProperty.call(b, prop) && !(size--)) {
break;
}
}
result = !size;
}
// handle JScript [[DontEnum]] bug
if (result && hasDontEnumBug) {
while (++index < 7) {
prop = shadowed[index];
if (hasOwnProperty.call(a, prop)) {
if (!(result = hasOwnProperty.call(b, prop) && isEqual(a[prop], b[prop], stack))) {
break;
}
}
}
}
}
// remove the first collection from the stack of traversed objects
stack.pop();
return result;
}
/**
* Checks if `value` is a finite number.
* Note: This is not the same as native `isFinite`, which will return true for
* booleans and other values. See http://es5.github.com/#x15.1.2.5.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a finite number, else `false`.
* @example
*
* _.isFinite(-101);
* // => true
*
* _.isFinite('10');
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
function isFinite(value) {
return nativeIsFinite(value) && toString.call(value) == numberClass;
}
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a function, else `false`.
* @example
*
* _.isFunction(''.concat);
* // => true
*/
function isFunction(value) {
return toString.call(value) == funcClass;
}
/**
* Checks if `value` is the language type of Object.
* (e.g. arrays, functions, objects, regexps, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.com/#x8
return value && objectTypes[typeof value];
}
/**
* Checks if `value` is `NaN`.
* Note: This is not the same as native `isNaN`, which will return true for
* `undefined` and other values. See http://es5.github.com/#x15.1.2.4.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// `NaN` as a primitive is the only value that is not equal to itself
// (perform the [[Class]] check first to avoid errors with some host objects in IE)
return toString.call(value) == numberClass && value != +value
}
/**
* Checks if `value` is `null`.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(undefined);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is a number.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a number, else `false`.
* @example
*
* _.isNumber(8.4 * 5;
* // => true
*/
function isNumber(value) {
return toString.call(value) == numberClass;
}
/**
* Checks if `value` is a regular expression.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a regular expression, else `false`.
* @example
*
* _.isRegExp(/moe/);
* // => true
*/
function isRegExp(value) {
return toString.call(value) == regexpClass;
}
/**
* Checks if `value` is a string.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a string, else `false`.
* @example
*
* _.isString('moe');
* // => true
*/
function isString(value) {
return toString.call(value) == stringClass;
}
/**
* Checks if `value` is `undefined`.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*/
function isUndefined(value) {
return value === undefined;
}
/**
* Produces an array of object`'s own enumerable property names.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names.
* @example
*
* _.keys({ 'one': 1, 'two': 2, 'three': 3 });
* // => ['one', 'two', 'three'] (order is not guaranteed)
*/
var keys = !nativeKeys ? shimKeys : function(object) {
// avoid iterating over the `prototype` property
return typeof object == 'function' && propertyIsEnumerable.call(object, 'prototype')
? shimKeys(object)
: nativeKeys(object);
};
/**
* Creates an object composed of the specified properties. Property names may
* be specified as individual arguments or as arrays of property names.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to pluck.
* @param {Object} [prop1, prop2, ...] The properties to pick.
* @returns {Object} Returns an object composed of the picked properties.
* @example
*
* _.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age');
* // => { 'name': 'moe', 'age': 40 }
*/
function pick(object) {
var prop,
index = 0,
props = concat.apply(ArrayProto, arguments),
length = props.length,
result = {};
// start `index` at `1` to skip `object`
while (++index < length) {
prop = props[index];
if (prop in object) {
result[prop] = object[prop];
}
}
return result;
}
/**
* Gets the size of `value` by returning `value.length` if `value` is a string
* or array, or the number of own enumerable properties if `value` is an object.
*
* @deprecated
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|String} value The value to inspect.
* @returns {Number} Returns `value.length` if `value` is a string or array,
* or the number of own enumerable properties if `value` is an object.
* @example
*
* _.size([1, 2]);
* // => 2
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*
* _.size('curly');
* // => 5
*/
function size(value) {
if (!value) {
return 0;
}
var length = value.length;
return length === length >>> 0 ? value.length : keys(value).length;
}
/**
* Produces an array of `object`'s own enumerable property values.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3]
*/
var values = createIterator({
'args': 'object',
'init': '[]',
'inLoop': 'result.push(iteratee[index])'
});
/*--------------------------------------------------------------------------*/
/**
* Escapes a string for inclusion in HTML, replacing `&`, `<`, `"`, and `'`
* characters.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} string The string to escape.
* @returns {String} Returns the escaped string.
* @example
*
* _.escape('Curly, Larry & Moe');
* // => "Curly, Larry & Moe"
*/
function escape(string) {
return string == null ? '' : (string + '').replace(reUnescapedHtml, escapeHtmlChar);
}
/**
* This function returns the first argument passed to it.
* Note: It is used throughout Lo-Dash as a default callback.
*
* @static
* @memberOf _
* @category Utilities
* @param {Mixed} value Any value.
* @returns {Mixed} Returns `value`.
* @example
*
* var moe = { 'name': 'moe' };
* moe === _.identity(moe);
* // => true
*/
function identity(value) {
return value;
}
/**
* Adds functions properties of `object` to the `lodash` function and chainable
* wrapper.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object of function properties to add to `lodash`.
* @example
*
* _.mixin({
* 'capitalize': function(string) {
* return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
* }
* });
*
* _.capitalize('curly');
* // => 'Curly'
*
* _('larry').capitalize();
* // => 'Larry'
*/
function mixin(object) {
forEach(functions(object), function(methodName) {
var func = lodash[methodName] = object[methodName];
LoDash.prototype[methodName] = function() {
var args = [this._wrapped];
if (arguments.length) {
push.apply(args, arguments);
}
var result = func.apply(lodash, args);
if (this._chain) {
result = new LoDash(result);
result._chain = true;
}
return result;
};
});
}
/**
* Reverts the '_' variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utilities
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
window._ = oldDash;
return this;
}
/**
* Resolves the value of `property` on `object`. If `property` is a function
* it will be invoked and its result returned, else the property value is
* returned. If `object` is falsey, then `null` is returned.
*
* @deprecated
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object to inspect.
* @param {String} property The property to get the result of.
* @returns {Mixed} Returns the resolved value.
* @example
*
* var object = {
* 'cheese': 'crumpets',
* 'stuff': function() {
* return 'nonsense';
* }
* };
*
* _.result(object, 'cheese');
* // => 'crumpets'
*
* _.result(object, 'stuff');
* // => 'nonsense'
*/
function result(object, property) {
// based on Backbone's private `getValue` function
// https://github.com/documentcloud/backbone/blob/0.9.2/backbone.js#L1419-1424
if (!object) {
return null;
}
var value = object[property];
return toString.call(value) == funcClass ? object[property]() : value;
}
/**
* A micro-templating method that handles arbitrary delimiters, preserves
* whitespace, and correctly escapes quotes within interpolated code.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} text The template text.
* @param {Obect} data The data object used to populate the text.
* @param {Object} options The options object.
* @returns {Function|String} Returns a compiled function when no `data` object
* is given, else it returns the interpolated text.
* @example
*
* // using compiled template
* var compiled = _.template('hello: <%= name %>');
* compiled({ 'name': 'moe' });
* // => 'hello: moe'
*
* var list = '<% _.forEach(people, function(name) { %> <li><%= name %></li> <% }); %>';
* _.template(list, { 'people': ['moe', 'curly', 'larry'] });
* // => '<li>moe</li><li>curly</li><li>larry</li>'
*
* var template = _.template('<b><%- value %></b>');
* template({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // using `print`
* var compiled = _.template('<% print("Hello " + epithet); %>');
* compiled({ 'epithet': 'stooge' });
* // => 'Hello stooge.'
*
* // using custom template settings
* _.templateSettings = {
* 'interpolate': /\{\{(.+?)\}\}/g
* };
*
* var template = _.template('Hello {{ name }}!');
* template({ 'name': 'Mustache' });
* // => 'Hello Mustache!'
*
* // using the `variable` option
* _.template('<%= data.hasWith %>', { 'hasWith': 'no' }, { 'variable': 'data' });
* // => 'no'
*
* // using the `source` property
* <script>
* JST.project = <%= _.template(jstText).source %>;
* </script>
*/
function template(text, data, options) {
// based on John Resig's `tmpl` implementation
// http://ejohn.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
options || (options = {});
var isEvaluating,
result,
escapeDelimiter = options.escape,
evaluateDelimiter = options.evaluate,
interpolateDelimiter = options.interpolate,
settings = lodash.templateSettings,
variable = options.variable;
// use default settings if no options object is provided
if (escapeDelimiter == null) {
escapeDelimiter = settings.escape;
}
if (evaluateDelimiter == null) {
evaluateDelimiter = settings.evaluate;
}
if (interpolateDelimiter == null) {
interpolateDelimiter = settings.interpolate;
}
// tokenize delimiters to avoid escaping them
if (escapeDelimiter) {
text = text.replace(escapeDelimiter, tokenizeEscape);
}
if (interpolateDelimiter) {
text = text.replace(interpolateDelimiter, tokenizeInterpolate);
}
if (evaluateDelimiter != lastEvaluateDelimiter) {
// generate `reEvaluateDelimiter` to match `_.templateSettings.evaluate`
// and internal `<e%- %>`, `<e%= %>` delimiters
lastEvaluateDelimiter = evaluateDelimiter;
reEvaluateDelimiter = RegExp(
(evaluateDelimiter ? evaluateDelimiter.source : '($^)') +
'|<e%-([\\s\\S]+?)%>|<e%=([\\s\\S]+?)%>'
, 'g');
}
isEvaluating = tokenized.length;
text = text.replace(reEvaluateDelimiter, tokenizeEvaluate);
isEvaluating = isEvaluating != tokenized.length;
// escape characters that cannot be included in string literals and
// detokenize delimiter code snippets
text = "__p += '" + text
.replace(reUnescapedString, escapeStringChar)
.replace(reToken, detokenize) + "';\n";
// clear stored code snippets
tokenized.length = 0;
// if `options.variable` is not specified and the template contains "evaluate"
// delimiters, wrap a with-statement around the generated code to add the
// data object to the top of the scope chain
if (!variable) {
variable = settings.variable || lastVariable || 'obj';
if (isEvaluating) {
text = 'with (' + variable + ') {\n' + text + '\n}\n';
}
else {
if (variable != lastVariable) {
// generate `reDoubleVariable` to match references like `obj.obj` inside
// transformed "escape" and "interpolate" delimiters
lastVariable = variable;
reDoubleVariable = RegExp('(\\(\\s*)' + variable + '\\.' + variable + '\\b', 'g');
}
// avoid a with-statement by prepending data object references to property names
text = text
.replace(reInsertVariable, '$&' + variable + '.')
.replace(reDoubleVariable, '$1__d');
}
}
// cleanup code by stripping empty strings
text = ( isEvaluating ? text.replace(reEmptyStringLeading, '') : text)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
text = 'function(' + variable + ') {\n' +
variable + ' || (' + variable + ' = {});\n' +
'var __t, __p = \'\', __e = _.escape' +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
'function print() { __p += __j.call(arguments, \'\') }\n'
: ', __d = ' + variable + '.' + variable + ' || ' + variable + ';\n'
) +
text +
'return __p\n}';
// add a sourceURL for easier debugging
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
if (useSourceURL) {
text += '\n//@ sourceURL=/lodash/template/source[' + (templateCounter++) + ']';
}
try {
result = Function('_', 'return ' + text)(lodash);
} catch(e) {
result = function() { throw e; };
}
if (data) {
return result(data);
}
// provide the compiled function's source via its `toString` method, in
// supported environments, or the `source` property as a convenience for
// build time precompilation
result.source = text;
return result;
}
/**
* Executes the `callback` function `n` times. The `callback` is bound to
* `thisArg` and invoked with 1 argument; (index).
*
* @static
* @memberOf _
* @category Utilities
* @param {Number} n The number of times to execute the callback.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding for the callback.
* @example
*
* _.times(3, function() { genie.grantWish(); });
* // => calls `genie.grantWish()` 3 times
*
* _.times(3, function() { this.grantWish(); }, genie);
* // => also calls `genie.grantWish()` 3 times
*/
function times(n, callback, thisArg) {
var index = -1;
if (thisArg) {
while (++index < n) {
callback.call(thisArg, index);
}
} else {
while (++index < n) {
callback(index);
}
}
}
/**
* Generates a unique id. If `prefix` is passed, the id will be appended to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} [prefix] The value to prefix the id with.
* @returns {Number|String} Returns a numeric id if no prefix is passed, else
* a string id may be returned.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*/
function uniqueId(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
}
/*--------------------------------------------------------------------------*/
/**
* Wraps the value in a `lodash` wrapper object.
*
* @static
* @memberOf _
* @category Chaining
* @param {Mixed} value The value to wrap.
* @returns {Object} Returns the wrapper object.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 },
* { 'name': 'curly', 'age': 60 }
* ];
*
* var youngest = _.chain(stooges)
* .sortBy(function(stooge) { return stooge.age; })
* .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })
* .first()
* .value();
* // => 'moe is 40'
*/
function chain(value) {
value = new LoDash(value);
value._chain = true;
return value;
}
/**
* Invokes `interceptor` with the `value` as the first argument, and then
* returns `value`. The purpose of this method is to "tap into" a method chain,
* in order to perform operations on intermediate results within the chain.
*
* @static
* @memberOf _
* @category Chaining
* @param {Mixed} value The value to pass to `callback`.
* @param {Function} interceptor The function to invoke.
* @returns {Mixed} Returns `value`.
* @example
*
* _.chain([1,2,3,200])
* .filter(function(num) { return num % 2 == 0; })
* .tap(alert)
* .map(function(num) { return num * num })
* .value();
* // => // [2, 200] (alerted)
* // => [4, 40000]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* Enables method chaining on the wrapper object.
*
* @name chain
* @deprecated
* @memberOf _
* @category Chaining
* @returns {Mixed} Returns the wrapper object.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperChain() {
this._chain = true;
return this;
}
/**
* Extracts the wrapped value.
*
* @name value
* @memberOf _
* @category Chaining
* @returns {Mixed} Returns the wrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return this._wrapped;
}
/*--------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type String
*/
lodash.VERSION = '0.4.1';
// assign static methods
lodash.after = after;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.chain = chain;
lodash.clone = clone;
lodash.compact = compact;
lodash.compose = compose;
lodash.contains = contains;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.escape = escape;
lodash.every = every;
lodash.extend = extend;
lodash.filter = filter;
lodash.find = find;
lodash.first = first;
lodash.flatten = flatten;
lodash.forEach = forEach;
lodash.forIn = forIn;
lodash.forOwn = forOwn;
lodash.functions = functions;
lodash.groupBy = groupBy;
lodash.has = has;
lodash.identity = identity;
lodash.indexOf = indexOf;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isNaN = isNaN;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isRegExp = isRegExp;
lodash.isString = isString;
lodash.isUndefined = isUndefined;
lodash.keys = keys;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.map = map;
lodash.max = max;
lodash.memoize = memoize;
lodash.min = min;
lodash.mixin = mixin;
lodash.noConflict = noConflict;
lodash.once = once;
lodash.partial = partial;
lodash.pick = pick;
lodash.pluck = pluck;
lodash.range = range;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.reject = reject;
lodash.rest = rest;
lodash.result = result;
lodash.shuffle = shuffle;
lodash.size = size;
lodash.some = some;
lodash.sortBy = sortBy;
lodash.sortedIndex = sortedIndex;
lodash.tap = tap;
lodash.template = template;
lodash.throttle = throttle;
lodash.times = times;
lodash.toArray = toArray;
lodash.union = union;
lodash.uniq = uniq;
lodash.uniqueId = uniqueId;
lodash.values = values;
lodash.without = without;
lodash.wrap = wrap;
lodash.zip = zip;
lodash.zipObject = zipObject;
// assign aliases
lodash.all = every;
lodash.any = some;
lodash.collect = map;
lodash.detect = find;
lodash.each = forEach;
lodash.foldl = reduce;
lodash.foldr = reduceRight;
lodash.head = first;
lodash.include = contains;
lodash.inject = reduce;
lodash.methods = functions;
lodash.select = filter;
lodash.tail = rest;
lodash.take = first;
lodash.unique = uniq;
// add pseudo private properties used and removed during the build process
lodash._iteratorTemplate = iteratorTemplate;
lodash._shimKeys = shimKeys;
/*--------------------------------------------------------------------------*/
// assign private `LoDash` constructor's prototype
LoDash.prototype = lodash.prototype;
// add all static functions to `LoDash.prototype`
mixin(lodash);
// add `LoDash.prototype.chain` after calling `mixin()` to avoid overwriting
// it with the wrapped `lodash.chain`
LoDash.prototype.chain = wrapperChain;
LoDash.prototype.value = wrapperValue;
// add all mutator Array functions to the wrapper.
forEach(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = ArrayProto[methodName];
LoDash.prototype[methodName] = function() {
var value = this._wrapped;
func.apply(value, arguments);
// IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()`
// functions that fail to remove the last element, `value[0]`, of
// array-like objects even though the `length` property is set to `0`.
// The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
// is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
if (value.length === 0) {
delete value[0];
}
if (this._chain) {
value = new LoDash(value);
value._chain = true;
}
return value;
};
});
// add all accessor Array functions to the wrapper.
forEach(['concat', 'join', 'slice'], function(methodName) {
var func = ArrayProto[methodName];
LoDash.prototype[methodName] = function() {
var value = this._wrapped,
result = func.apply(value, arguments);
if (this._chain) {
result = new LoDash(result);
result._chain = true;
}
return result;
};
});
/*--------------------------------------------------------------------------*/
// expose Lo-Dash
// some AMD build optimizers, like r.js, check for specific condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lo-Dash to the global object even when an AMD loader is present in
// case Lo-Dash was injected by a third-party script and not intended to be
// loaded as a module. The global assignment can be reverted in the Lo-Dash
// module via its `noConflict()` method.
window._ = lodash;
// define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module
define('matrix/../../lib/lodash',[],function() {
return lodash;
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports) {
// in Node.js or RingoJS v0.8.0+
if (typeof module == 'object' && module && module.exports == freeExports) {
(module.exports = lodash)._ = lodash;
}
// in Narwhal or RingoJS v0.7.0-
else {
freeExports._ = lodash;
}
}
else {
// in a browser or Rhino
window._ = lodash;
}
}(this));
define('matrix/matrix2-api',['require','common/not-implemented','matrix/m2'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var M2 = require( "matrix/m2" )( FLOAT_ARRAY_TYPE );
function add( m1, m2, result ) {
result = result || new M2();
result[0] = m1[0] + m2[0];
result[1] = m1[1] + m2[1];
result[2] = m1[2] + m2[2];
result[3] = m1[3] + m2[3];
return result;
}
function clear( m ) {
m[0] = m[1] = 0;
m[2] = m[3] = 0;
return m;
}
function determinant( m ) {
var a00 = m[0], a01 = m[1],
a10 = m[2], a11 = m[3];
return a00 * a11 - a01 * a10;
}
function equal( m1, m2, e ) {
e = e || 0.000001;
if( m1.length !== m2.length ) {
return false;
}
var d0 = Math.abs( m1[0] - m2[0] );
var d1 = Math.abs( m1[1] - m2[1] );
var d2 = Math.abs( m1[2] - m2[2] );
var d3 = Math.abs( m1[3] - m2[3] );
if( isNaN( d0 ) || d0 > e ||
isNaN( d1 ) || d1 > e ||
isNaN( d2 ) || d2 > e ||
isNaN( d3 ) || d3 > e ) {
return false;
}
return true;
}
function inverse( m, result ) {
result = result || new M2();
var a00 = m[0], a01 = m[1],
a10 = m[2], a11 = m[3],
determinant = a00 * a11 - a01 * a10,
inverseDeterminant;
if( !determinant ) { return null; }
inverseDeterminant = 1 / determinant;
result[0] = a11 * inverseDeterminant;
result[1] = -a01 * inverseDeterminant;
result[2] = -a10 * inverseDeterminant;
result[3] = a00 * inverseDeterminant;
return result;
}
function multiply( m1, m2, result ) {
result = result || new M2();
var a00 = m1[0], a01 = m1[1], a10 = m1[2], a11 = m1[3];
var b00 = m2[0], b01 = m2[1], b10 = m2[2], b11 = m2[3];
result[0] = a00 * b00 + a01 * b10;
result[1] = a00 * b01 + a01 * b11;
result[2] = a10 * b00 + a11 * b10;
result[3] = a10 * b01 + a11 * b11;
return result;
}
function set( m ) {
if( 2 === arguments.length ) {
var values = arguments[1];
m[0] = values[0];
m[1] = values[1];
m[2] = values[2];
m[3] = values[3];
} else {
m[0] = arguments[1];
m[1] = arguments[2];
m[2] = arguments[3];
m[3] = arguments[4];
}
return m;
}
function subtract( m1, m2, result ) {
result = result || new M2();
result[0] = m1[0] - m2[0];
result[1] = m1[1] - m2[1];
result[2] = m1[2] - m2[2];
result[3] = m1[3] - m2[3];
return result;
}
function transpose( m, result ) {
if( m && m === result ) {
var a01 = m[1];
result[1] = m[2];
result[2] = a01;
return result;
}
result = result || new M2();
result[0] = m[0];
result[1] = m[2];
result[2] = m[1];
result[3] = m[3];
return result;
}
var matrix2 = {
add: add,
clear: clear,
determinant: determinant,
equal: equal,
inverse: inverse,
multiply: multiply,
set: set,
subtract: subtract,
transpose: transpose,
zero: new M2( 0, 0,
0, 0 ),
one: new M2( 1, 1,
1, 1 ),
identity: new M2( 1, 0,
0, 1 )
};
return matrix2;
};
});
define('matrix/matrix2',['require','../../lib/lodash','common/not-implemented','matrix/m2','matrix/matrix2-api','matrix/matrix'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var _ = require( "../../lib/lodash" );
var notImplemented = require( "common/not-implemented" );
var M2 = require( "matrix/m2" )( FLOAT_ARRAY_TYPE );
var matrix2 = require( "matrix/matrix2-api" )( FLOAT_ARRAY_TYPE );
var Matrix = require( "matrix/matrix" );
function getView( index ) {
return this._views[index];
}
function getValue( index ) {
return this.buffer[index];
}
function setValue( index, value ) {
this.buffer[index] = value;
this.matrix.modified = true;
}
function updateViews() {
var i;
for( i = 0; i < 2; ++ i ) {
this._views[i] = new Matrix2View( this, this.buffer,
i*2, (i+1)*2 );
}
}
var Matrix2View = function( matrix, buffer, start, end ) {
this.matrix = matrix;
this.buffer = buffer.subarray( start, end );
Object.defineProperties( this, {
"0": {
get: getValue.bind( this, 0 ),
set: setValue.bind( this, 0 )
},
"1": {
get: getValue.bind( this, 1 ),
set: setValue.bind( this, 1 )
}
});
};
var Matrix2 = function( arg1, arg2,
arg3, arg4 ) {
var argc = arguments.length;
if( 1 === argc ) {
if( arg1 instanceof Matrix2 ) {
this.buffer = new M2( arg1.buffer );
} else {
this.buffer = new M2( arg1 );
}
} else if( 4 === argc ) {
this.buffer = new M2( arg1, arg2,
arg3, arg4 );
} else {
this.buffer = new M2();
}
Object.defineProperties( this, {
"0": {
get: getView.bind( this, 0 )
},
"1": {
get: getView.bind( this, 1 )
}
});
this._views = [];
updateViews.call( this );
this.modified = true;
};
Matrix2.prototype = new Matrix();
Matrix2.prototype.constructor = Matrix2;
function add( arg, result ) {
var other;
if( arg instanceof Matrix2 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix2.add( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function clear() {
matrix2.clear( this.buffer );
this.modified = true;
return this;
}
function clone() {
return new Matrix2( this );
}
function determinant() {
return matrix2.determinant( this.buffer );
}
function equal( arg ) {
var other;
if( arg instanceof Matrix2 ) {
other = arg.buffer;
} else {
other = arg;
}
return matrix2.equal( this.buffer, other );
}
function inverse( result ) {
result = result || this;
if( !matrix2.determinant( this.buffer ) ) {
throw new Error( "matrix is singular" );
}
matrix2.inverse( this.buffer, result.buffer );
result.modified = true;
return this;
}
function multiply( arg, result ) {
var other;
if( arg instanceof Matrix2 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix2.multiply( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function set( arg1, arg2, arg3, arg4,
arg5, arg6, arg7, arg8,
arg9, arg10, arg11, arg12,
arg13, arg14, arg15, arg16 ) {
var argc = arguments.length;
var buffer = this.buffer;
var other;
if( 1 === argc ) {
if( arg1 instanceof Matrix2 ) {
other = arg1.buffer;
} else {
other = arg1;
}
buffer[0] = other[0];
buffer[1] = other[1];
buffer[2] = other[2];
buffer[3] = other[3];
buffer[4] = other[4];
buffer[5] = other[5];
buffer[6] = other[6];
buffer[7] = other[7];
buffer[8] = other[8];
buffer[9] = other[9];
buffer[10] = other[10];
buffer[11] = other[11];
buffer[12] = other[12];
buffer[13] = other[13];
buffer[14] = other[14];
buffer[15] = other[15];
this.modified = true;
} else if( 16 === argc ) {
buffer[0] = arg1;
buffer[1] = arg2;
buffer[2] = arg3;
buffer[3] = arg4;
buffer[4] = arg5;
buffer[5] = arg6;
buffer[6] = arg7;
buffer[7] = arg8;
buffer[8] = arg9;
buffer[9] = arg10;
buffer[10] = arg11;
buffer[11] = arg12;
buffer[12] = arg13;
buffer[13] = arg14;
buffer[14] = arg15;
buffer[15] = arg16;
this.modified = true;
}
return this;
}
function subtract( arg, result ) {
var other;
if( arg instanceof Matrix2 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix2.subtract( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function transpose( result ) {
result = result || this;
matrix2.transpose( this.buffer, result.buffer );
result.modified = true;
return this;
}
_.extend( Matrix2.prototype, {
add: add,
clear: clear,
clone: clone,
determinant: determinant,
equal: equal,
inverse: inverse,
multiply: multiply,
set: set,
subtract: subtract,
transpose: transpose
});
return Matrix2;
};
});
define('matrix/m3',['require','matrix/m'],function ( require ) {
var M = require( "matrix/m" );
return function( FLOAT_ARRAY_TYPE ) {
var M3 = function() {
var elements = null;
var argc = arguments.length;
if( 1 === argc) {
elements = arguments[0];
} else if( 0 === argc ) {
elements = [0, 0, 0,
0, 0, 0,
0, 0, 0];
} else {
elements = arguments;
}
var matrix = new FLOAT_ARRAY_TYPE( 9 );
for( var i = 0; i < 9; ++ i ) {
matrix[i] = elements[i];
}
return matrix;
};
M3.prototype = new M();
M3.prototype.constructor = M3;
return M3;
};
});
define('matrix/matrix3-api',['require','common/not-implemented','matrix/m3'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var M3 = require( "matrix/m3" )( FLOAT_ARRAY_TYPE );
function add( m1, m2, result ) {
result = result || new M3();
result[0] = m1[0] + m2[0];
result[1] = m1[1] + m2[1];
result[2] = m1[2] + m2[2];
result[3] = m1[3] + m2[3];
result[4] = m1[4] + m2[4];
result[5] = m1[5] + m2[5];
result[6] = m1[6] + m2[6];
result[7] = m1[7] + m2[7];
result[8] = m1[8] + m2[8];
return result;
}
function clear( m ) {
m[0] = m[1] = m[2] = 0;
m[3] = m[4] = m[5] = 0;
m[6] = m[7] = m[8] = 0;
return m;
}
function determinant( m ) {
var a00 = m[0], a01 = m[1], a02 = m[2],
a10 = m[3], a11 = m[4], a12 = m[5],
a20 = m[6], a21 = m[7], a22 = m[8];
return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
}
function equal( m1, m2, e ) {
e = e || 0.000001;
if( m1.length !== m2.length ) {
return false;
}
var d0 = Math.abs( m1[0] - m2[0] );
var d1 = Math.abs( m1[1] - m2[1] );
var d2 = Math.abs( m1[2] - m2[2] );
var d3 = Math.abs( m1[3] - m2[3] );
var d4 = Math.abs( m1[4] - m2[4] );
var d5 = Math.abs( m1[5] - m2[5] );
var d6 = Math.abs( m1[6] - m2[6] );
var d7 = Math.abs( m1[7] - m2[7] );
var d8 = Math.abs( m1[8] - m2[8] );
if( isNaN( d0 ) || d0 > e ||
isNaN( d1 ) || d1 > e ||
isNaN( d2 ) || d2 > e ||
isNaN( d3 ) || d3 > e ||
isNaN( d4 ) || d4 > e ||
isNaN( d5 ) || d5 > e ||
isNaN( d6 ) || d6 > e ||
isNaN( d7 ) || d7 > e ||
isNaN( d8 ) || d8 > e ) {
return false;
}
return true;
}
function inverse( m, result ) {
result = result || new M3();
var a00 = m[0], a01 = m[1], a02 = m[2],
a10 = m[3], a11 = m[4], a12 = m[5],
a20 = m[6], a21 = m[7], a22 = m[8],
b01 = a22 * a11 - a12 * a21,
b11 = -a22 * a10 + a12 * a20,
b21 = a21 * a10 - a11 * a20,
determinant = a00 * b01 + a01 * b11 + a02 * b21,
inverseDeterminant;
if( !determinant ) { return null; }
inverseDeterminant = 1 / determinant;
result[0] = b01 * inverseDeterminant;
result[1] = (-a22 * a01 + a02 * a21) * inverseDeterminant;
result[2] = (a12 * a01 - a02 * a11) * inverseDeterminant;
result[3] = b11 * inverseDeterminant;
result[4] = (a22 * a00 - a02 * a20) * inverseDeterminant;
result[5] = (-a12 * a00 + a02 * a10) * inverseDeterminant;
result[6] = b21 * inverseDeterminant;
result[7] = (-a21 * a00 + a01 * a20) * inverseDeterminant;
result[8] = (a11 * a00 - a01 * a10) * inverseDeterminant;
return result;
}
// https://github.com/toji/gl-matrix/blob/8d6179c15aa938159feb2cb617d8a3af3fa2c7f3/gl-matrix.js#L682
function multiply( m1, m2, result ) {
result = result || new M3();
// Cache the matrix values (makes for huge speed increases!)
var a00 = m1[0], a01 = m1[1], a02 = m1[2],
a10 = m1[3], a11 = m1[4], a12 = m1[5],
a20 = m1[6], a21 = m1[7], a22 = m1[8],
b00 = m2[0], b01 = m2[1], b02 = m2[2],
b10 = m2[3], b11 = m2[4], b12 = m2[5],
b20 = m2[6], b21 = m2[7], b22 = m2[8];
result[0] = a00 * b00 + a01 * b10 + a02 * b20;
result[1] = a00 * b01 + a01 * b11 + a02 * b21;
result[2] = a00 * b02 + a01 * b12 + a02 * b22;
result[3] = a10 * b00 + a11 * b10 + a12 * b20;
result[4] = a10 * b01 + a11 * b11 + a12 * b21;
result[5] = a10 * b02 + a11 * b12 + a12 * b22;
result[6] = a20 * b00 + a21 * b10 + a22 * b20;
result[7] = a20 * b01 + a21 * b11 + a22 * b21;
result[8] = a20 * b02 + a21 * b12 + a22 * a22;
return result;
}
function set( m ) {
if( 2 === arguments.length ) {
var values = arguments[1];
m[0] = values[0];
m[1] = values[1];
m[2] = values[2];
m[3] = values[3];
m[4] = values[4];
m[5] = values[5];
m[6] = values[6];
m[7] = values[7];
m[8] = values[8];
} else {
m[0] = arguments[1];
m[1] = arguments[2];
m[2] = arguments[3];
m[3] = arguments[4];
m[4] = arguments[5];
m[5] = arguments[6];
m[6] = arguments[7];
m[7] = arguments[8];
m[8] = arguments[9];
}
return m;
}
function subtract( m1, m2, result ) {
result = result || new M3();
result[0] = m1[0] - m2[0];
result[1] = m1[1] - m2[1];
result[2] = m1[2] - m2[2];
result[3] = m1[3] - m2[3];
result[4] = m1[4] - m2[4];
result[5] = m1[5] - m2[5];
result[6] = m1[6] - m2[6];
result[7] = m1[7] - m2[7];
result[8] = m1[8] - m2[8];
return result;
}
function transpose( m, result ) {
if( m && m === result ) {
var a01 = m[1], a02 = m[2],
a12 = m[5];
result[1] = m[3];
result[2] = m[6];
result[3] = a01;
result[5] = m[7];
result[6] = a02;
result[7] = a12;
return result;
}
result = result || new M3();
result[0] = m[0];
result[1] = m[3];
result[2] = m[6];
result[3] = m[1];
result[4] = m[4];
result[5] = m[7];
result[6] = m[2];
result[7] = m[5];
result[8] = m[8];
return result;
}
var matrix3 = {
add: add,
clear: clear,
determinant: determinant,
equal: equal,
inverse: inverse,
multiply: multiply,
multiplyV3: notImplemented,
set: set,
subtract: subtract,
transpose: transpose,
zero: new M3( 0, 0, 0,
0, 0, 0,
0, 0, 0 ),
one: new M3( 1, 1, 1,
1, 1, 1,
1, 1, 1 ),
identity: new M3( 1, 0, 0,
0, 1, 0,
0, 0, 1 )
};
return matrix3;
};
});
define('matrix/matrix3',['require','../../lib/lodash','common/not-implemented','matrix/m3','matrix/matrix3-api','matrix/matrix'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var _ = require( "../../lib/lodash" );
var notImplemented = require( "common/not-implemented" );
var M3 = require( "matrix/m3" )( FLOAT_ARRAY_TYPE );
var matrix3 = require( "matrix/matrix3-api" )( FLOAT_ARRAY_TYPE );
var Matrix = require( "matrix/matrix" );
function getView( index ) {
return this._views[index];
}
function getValue( index ) {
return this.buffer[index];
}
function setValue( index, value ) {
this.buffer[index] = value;
this.matrix.modified = true;
}
function updateViews() {
var i;
for( i = 0; i < 3; ++ i ) {
this._views[i] = new Matrix3View( this, this.buffer,
i*3, (i+1)*3 );
}
}
var Matrix3View = function( matrix, buffer, start, end ) {
this.matrix = matrix;
this.buffer = buffer.subarray( start, end );
Object.defineProperties( this, {
"0": {
get: getValue.bind( this, 0 ),
set: setValue.bind( this, 0 )
},
"1": {
get: getValue.bind( this, 1 ),
set: setValue.bind( this, 1 )
},
"2": {
get: getValue.bind( this, 2 ),
set: setValue.bind( this, 2 )
}
});
};
var Matrix3 = function( arg1, arg2, arg3,
arg4, arg5, arg6,
arg7, arg8, arg9 ) {
var argc = arguments.length;
if( 1 === argc ) {
if( arg1 instanceof Matrix3 ) {
this.buffer = new M3( arg1.buffer );
} else {
this.buffer = new M3( arg1 );
}
} else if( 9 === argc ) {
this.buffer = new M3( arg1, arg2, arg3,
arg4, arg5, arg6,
arg7, arg8, arg9 );
} else {
this.buffer = new M3();
}
Object.defineProperties( this, {
"0": {
get: getView.bind( this, 0 )
},
"1": {
get: getView.bind( this, 1 )
},
"2": {
get: getView.bind( this, 2 )
}
});
this._views = [];
updateViews.call( this );
this.modified = true;
};
Matrix3.prototype = new Matrix();
Matrix3.prototype.constructor = Matrix3;
function add( arg, result ) {
var other;
if( arg instanceof Matrix3 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix3.add( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function clear() {
matrix3.clear( this.buffer );
this.modified = true;
return this;
}
function clone() {
return new Matrix3( this );
}
function determinant() {
return matrix3.determinant( this.buffer );
}
function equal( arg ) {
var other;
if( arg instanceof Matrix3 ) {
other = arg.buffer;
} else {
other = arg;
}
return matrix3.equal( this.buffer, other );
}
function inverse( result ) {
result = result || this;
if( !matrix3.determinant( this.buffer ) ) {
throw new Error( "matrix is singular" );
}
matrix3.inverse( this.buffer, result.buffer );
result.modified = true;
return this;
}
function multiply( arg, result ) {
var other;
if( arg instanceof Matrix3 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix3.multiply( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function set( arg1, arg2, arg3, arg4,
arg5, arg6, arg7, arg8,
arg9, arg10, arg11, arg12,
arg13, arg14, arg15, arg16 ) {
var argc = arguments.length;
var buffer = this.buffer;
var other;
if( 1 === argc ) {
if( arg1 instanceof Matrix3 ) {
other = arg1.buffer;
} else {
other = arg1;
}
buffer[0] = other[0];
buffer[1] = other[1];
buffer[2] = other[2];
buffer[3] = other[3];
buffer[4] = other[4];
buffer[5] = other[5];
buffer[6] = other[6];
buffer[7] = other[7];
buffer[8] = other[8];
buffer[9] = other[9];
buffer[10] = other[10];
buffer[11] = other[11];
buffer[12] = other[12];
buffer[13] = other[13];
buffer[14] = other[14];
buffer[15] = other[15];
this.modified = true;
} else if( 16 === argc ) {
buffer[0] = arg1;
buffer[1] = arg2;
buffer[2] = arg3;
buffer[3] = arg4;
buffer[4] = arg5;
buffer[5] = arg6;
buffer[6] = arg7;
buffer[7] = arg8;
buffer[8] = arg9;
buffer[9] = arg10;
buffer[10] = arg11;
buffer[11] = arg12;
buffer[12] = arg13;
buffer[13] = arg14;
buffer[14] = arg15;
buffer[15] = arg16;
this.modified = true;
}
return this;
}
function subtract( arg, result ) {
var other;
if( arg instanceof Matrix3 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix3.subtract( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function transpose( result ) {
result = result || this;
matrix3.transpose( this.buffer, result.buffer );
result.modified = true;
return this;
}
_.extend( Matrix3.prototype, {
add: add,
clear: clear,
clone: clone,
determinant: determinant,
equal: equal,
inverse: inverse,
multiply: multiply,
set: set,
subtract: subtract,
transpose: transpose
});
return Matrix3;
};
});
define('matrix/m4',['require','matrix/m'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var M = require( "matrix/m" );
var M4 = function() {
var elements = null;
var argc = arguments.length;
if( 1 === argc) {
elements = arguments[0];
} else if( 0 === argc ) {
elements = [0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0];
} else {
elements = arguments;
}
var matrix = new FLOAT_ARRAY_TYPE( 16 );
for( var i = 0; i < 16; ++ i ) {
matrix[i] = elements[i];
}
return matrix;
};
M4.prototype = new M();
M4.prototype.constructor = M4;
return M4;
};
});
define('matrix/matrix4-api',['require','common/not-implemented','matrix/m4','vector/v3'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var M4 = require( "matrix/m4" )( FLOAT_ARRAY_TYPE );
var V3 = require( "vector/v3" )( FLOAT_ARRAY_TYPE );
function add( m1, m2, result ) {
result = result || new M4();
result[0] = m1[0] + m2[0];
result[1] = m1[1] + m2[1];
result[2] = m1[2] + m2[2];
result[3] = m1[3] + m2[3];
result[4] = m1[4] + m2[4];
result[5] = m1[5] + m2[5];
result[6] = m1[6] + m2[6];
result[7] = m1[7] + m2[7];
result[8] = m1[8] + m2[8];
result[9] = m1[9] + m2[9];
result[10] = m1[10] + m2[10];
result[11] = m1[11] + m2[11];
result[12] = m1[12] + m2[12];
result[13] = m1[13] + m2[13];
result[14] = m1[14] + m2[14];
result[15] = m1[15] + m2[15];
return result;
}
function clear( m ) {
m[0] = m[1] = m[2] = m[3] = 0;
m[4] = m[5] = m[6] = m[7] = 0;
m[8] = m[9] = m[10] = m[11] = 0;
m[12] = m[13] = m[14] = m[15] = 0;
return m;
}
function determinant( m ) {
var a0 = m[0] * m[5] - m[1] * m[4];
var a1 = m[0] * m[6] - m[2] * m[4];
var a2 = m[0] * m[7] - m[3] * m[4];
var a3 = m[1] * m[6] - m[2] * m[5];
var a4 = m[1] * m[7] - m[3] * m[5];
var a5 = m[2] * m[7] - m[3] * m[6];
var b0 = m[8] * m[13] - m[9] * m[12];
var b1 = m[8] * m[14] - m[10] * m[12];
var b2 = m[8] * m[15] - m[11] * m[12];
var b3 = m[9] * m[14] - m[10] * m[13];
var b4 = m[9] * m[15] - m[11] * m[13];
var b5 = m[10] * m[15] - m[11] * m[14];
return a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
}
function equal( m1, m2, e ) {
e = e || 0.000001;
if( m1.length !== m2.length ) {
return false;
}
var d0 = Math.abs( m1[0] - m2[0] );
var d1 = Math.abs( m1[1] - m2[1] );
var d2 = Math.abs( m1[2] - m2[2] );
var d3 = Math.abs( m1[3] - m2[3] );
var d4 = Math.abs( m1[4] - m2[4] );
var d5 = Math.abs( m1[5] - m2[5] );
var d6 = Math.abs( m1[6] - m2[6] );
var d7 = Math.abs( m1[7] - m2[7] );
var d8 = Math.abs( m1[8] - m2[8] );
var d9 = Math.abs( m1[9] - m2[9] );
var d10 = Math.abs( m1[10] - m2[10] );
var d11 = Math.abs( m1[11] - m2[11] );
var d12 = Math.abs( m1[12] - m2[12] );
var d13 = Math.abs( m1[13] - m2[13] );
var d14 = Math.abs( m1[14] - m2[14] );
var d15 = Math.abs( m1[15] - m2[15] );
if( isNaN( d0 ) || d0 > e ||
isNaN( d1 ) || d1 > e ||
isNaN( d2 ) || d2 > e ||
isNaN( d3 ) || d3 > e ||
isNaN( d4 ) || d4 > e ||
isNaN( d5 ) || d5 > e ||
isNaN( d6 ) || d6 > e ||
isNaN( d7 ) || d7 > e ||
isNaN( d8 ) || d8 > e ||
isNaN( d9 ) || d9 > e ||
isNaN( d10 ) || d10 > e ||
isNaN( d11 ) || d11 > e ||
isNaN( d12 ) || d12 > e ||
isNaN( d13 ) || d13 > e ||
isNaN( d14 ) || d14 > e ||
isNaN( d15 ) || d15 > e ) {
return false;
}
return true;
}
function inverse( m, result ) {
result = result || new M4();
var a00 = m[0], a01 = m[1], a02 = m[2], a03 = m[3],
a10 = m[4], a11 = m[5], a12 = m[6], a13 = m[7],
a20 = m[8], a21 = m[9], a22 = m[10], a23 = m[11],
a30 = m[12], a31 = m[13], a32 = m[14], a33 = m[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32,
determinant = (b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06),
inverseDeterminant;
// Determinant, throw exception if singular
if( !determinant ) {
return undefined;
}
inverseDeterminant = 1 / determinant;
result[0] = (a11 * b11 - a12 * b10 + a13 * b09) * inverseDeterminant;
result[1] = (-a01 * b11 + a02 * b10 - a03 * b09) * inverseDeterminant;
result[2] = (a31 * b05 - a32 * b04 + a33 * b03) * inverseDeterminant;
result[3] = (-a21 * b05 + a22 * b04 - a23 * b03) * inverseDeterminant;
result[4] = (-a10 * b11 + a12 * b08 - a13 * b07) * inverseDeterminant;
result[5] = (a00 * b11 - a02 * b08 + a03 * b07) * inverseDeterminant;
result[6] = (-a30 * b05 + a32 * b02 - a33 * b01) * inverseDeterminant;
result[7] = (a20 * b05 - a22 * b02 + a23 * b01) * inverseDeterminant;
result[8] = (a10 * b10 - a11 * b08 + a13 * b06) * inverseDeterminant;
result[9] = (-a00 * b10 + a01 * b08 - a03 * b06) * inverseDeterminant;
result[10] = (a30 * b04 - a31 * b02 + a33 * b00) * inverseDeterminant;
result[11] = (-a20 * b04 + a21 * b02 - a23 * b00) * inverseDeterminant;
result[12] = (-a10 * b09 + a11 * b07 - a12 * b06) * inverseDeterminant;
result[13] = (a00 * b09 - a01 * b07 + a02 * b06) * inverseDeterminant;
result[14] = (-a30 * b03 + a31 * b01 - a32 * b00) * inverseDeterminant;
result[15] = (a20 * b03 - a21 * b01 + a22 * b00) * inverseDeterminant;
return result;
}
// https://github.com/toji/gl-matrix/blob/8d6179c15aa938159feb2cb617d8a3af3fa2c7f3/gl-matrix.js#L1295
function multiply( m1, m2, result ) {
result = result || new M4();
var a00 = m1[0], a01 = m1[1], a02 = m1[2], a03 = m1[3],
a10 = m1[4], a11 = m1[5], a12 = m1[6], a13 = m1[7],
a20 = m1[8], a21 = m1[9], a22 = m1[10], a23 = m1[11],
a30 = m1[12], a31 = m1[13], a32 = m1[14], a33 = m1[15],
b00 = m2[0], b01 = m2[1], b02 = m2[2], b03 = m2[3],
b10 = m2[4], b11 = m2[5], b12 = m2[6], b13 = m2[7],
b20 = m2[8], b21 = m2[9], b22 = m2[10], b23 = m2[11],
b30 = m2[12], b31 = m2[13], b32 = m2[14], b33 = m2[15];
result[0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;
result[1] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;
result[2] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;
result[3] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;
result[4] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;
result[5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;
result[6] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;
result[7] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;
result[8] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;
result[9] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;
result[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;
result[11] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;
result[12] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;
result[13] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;
result[14] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;
result[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;
return result;
}
function multiplyV3( m, v, result ) {
result = result || new V3();
var x = v[0], y = v[1], z = v[2];
result[0] = m[0] * x + m[4] * y + m[8] * z + m[12];
result[1] = m[1] * x + m[5] * y + m[9] * z + m[13];
result[2] = m[2] * x + m[6] * y + m[10] * z + m[14];
return result;
}
function set( m ) {
if( 2 === arguments.length ) {
var values = arguments[1];
m[0] = values[0];
m[1] = values[1];
m[2] = values[2];
m[3] = values[3];
m[4] = values[4];
m[5] = values[5];
m[6] = values[6];
m[7] = values[7];
m[8] = values[8];
m[9] = values[9];
m[10] = values[10];
m[11] = values[11];
m[12] = values[12];
m[13] = values[13];
m[14] = values[14];
m[15] = values[15];
} else {
m[0] = arguments[1];
m[1] = arguments[2];
m[2] = arguments[3];
m[3] = arguments[4];
m[4] = arguments[5];
m[5] = arguments[6];
m[6] = arguments[7];
m[7] = arguments[8];
m[8] = arguments[9];
m[9] = arguments[10];
m[10] = arguments[11];
m[11] = arguments[12];
m[12] = arguments[13];
m[13] = arguments[14];
m[14] = arguments[15];
m[15] = arguments[16];
}
return m;
}
function subtract( m1, m2, result ) {
result = result || new M4();
result[0] = m1[0] - m2[0];
result[1] = m1[1] - m2[1];
result[2] = m1[2] - m2[2];
result[3] = m1[3] - m2[3];
result[4] = m1[4] - m2[4];
result[5] = m1[5] - m2[5];
result[6] = m1[6] - m2[6];
result[7] = m1[7] - m2[7];
result[8] = m1[8] - m2[8];
result[9] = m1[9] - m2[9];
result[10] = m1[10] - m2[10];
result[11] = m1[11] - m2[11];
result[12] = m1[12] - m2[12];
result[13] = m1[13] - m2[13];
result[14] = m1[14] - m2[14];
result[15] = m1[15] - m2[15];
return result;
}
function transpose( m, result ) {
if( m && m === result ) {
var a01 = m[1], a02 = m[2], a03 = m[3],
a12 = m[6], a13 = m[7],
a23 = m[11];
result[1] = m[4];
result[2] = m[8];
result[3] = m[12];
result[4] = a01;
result[6] = m[9];
result[7] = m[13];
result[8] = a02;
result[9] = a12;
result[11] = m[14];
result[12] = a03;
result[13] = a13;
result[14] = a23;
return result;
}
result = result || new M4();
result[0] = m[0];
result[1] = m[4];
result[2] = m[8];
result[3] = m[12];
result[4] = m[1];
result[5] = m[5];
result[6] = m[9];
result[7] = m[13];
result[8] = m[2];
result[9] = m[6];
result[10] = m[10];
result[11] = m[14];
result[12] = m[3];
result[13] = m[7];
result[14] = m[11];
result[15] = m[15];
return result;
}
var matrix4 = {
add: add,
clear: clear,
determinant: determinant,
equal: equal,
inverse: inverse,
multiply: multiply,
multiplyV3: notImplemented,
set: set,
subtract: subtract,
transpose: transpose,
zero: new M4( 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0 ),
one: new M4( 1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1,
1, 1, 1, 1 ),
identity: new M4( 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 )
};
return matrix4;
};
});
define('matrix/matrix4',['require','../../lib/lodash','common/not-implemented','matrix/m4','matrix/matrix4-api','matrix/matrix'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var _ = require( "../../lib/lodash" );
var notImplemented = require( "common/not-implemented" );
var M4 = require( "matrix/m4" )( FLOAT_ARRAY_TYPE );
var matrix4 = require( "matrix/matrix4-api" )( FLOAT_ARRAY_TYPE );
var Matrix = require( "matrix/matrix" );
function getView( index ) {
return this._views[index];
}
function getValue( index ) {
return this.buffer[index];
}
function setValue( index, value ) {
this.buffer[index] = value;
this.matrix.modified = true;
}
function updateViews() {
var i;
for( i = 0; i < 4; ++ i ) {
this._views[i] = new Matrix4View( this, this.buffer,
i*4, (i+1)*4 );
}
}
var Matrix4View = function( matrix, buffer, start, end ) {
this.matrix = matrix;
this.buffer = buffer.subarray( start, end );
Object.defineProperties( this, {
"0": {
get: getValue.bind( this, 0 ),
set: setValue.bind( this, 0 )
},
"1": {
get: getValue.bind( this, 1 ),
set: setValue.bind( this, 1 )
},
"2": {
get: getValue.bind( this, 2 ),
set: setValue.bind( this, 2 )
},
"3": {
get: getValue.bind( this, 3 ),
set: setValue.bind( this, 3 )
}
});
};
var Matrix4 = function( arg1, arg2, arg3, arg4,
arg5, arg6, arg7, arg8,
arg9, arg10, arg11, arg12,
arg13, arg14, arg15, arg16 ) {
var argc = arguments.length;
if( 1 === argc ) {
if( arg1 instanceof Matrix4 ) {
this.buffer = new M4( arg1.buffer );
} else {
this.buffer = new M4( arg1 );
}
} else if( 16 === argc ) {
this.buffer = new M4( arg1, arg2, arg3, arg4,
arg5, arg6, arg7, arg8,
arg9, arg10, arg11, arg12,
arg13, arg14, arg15, arg16 );
} else {
this.buffer = new M4();
}
Object.defineProperties( this, {
"0": {
get: getView.bind( this, 0 )
},
"1": {
get: getView.bind( this, 1 )
},
"2": {
get: getView.bind( this, 2 )
},
"3": {
get: getView.bind( this, 3 )
}
});
this._views = [];
updateViews.call( this );
this.modified = true;
};
Matrix4.prototype = new Matrix();
Matrix4.prototype.constructor = Matrix4;
function add( arg, result ) {
var other;
if( arg instanceof Matrix4 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix4.add( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function clear() {
matrix4.clear( this.buffer );
this.modified = true;
return this;
}
function clone() {
return new Matrix4( this );
}
function determinant() {
return matrix4.determinant( this.buffer );
}
function equal( arg ) {
var other;
if( arg instanceof Matrix4 ) {
other = arg.buffer;
} else {
other = arg;
}
return matrix4.equal( this.buffer, other );
}
function inverse( result ) {
result = result || this;
if( !matrix4.determinant( this.buffer ) ) {
throw new Error( "matrix is singular" );
}
matrix4.inverse( this.buffer, result.buffer );
result.modified = true;
return this;
}
function multiply( arg, result ) {
var other;
if( arg instanceof Matrix4 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix4.multiply( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function set( arg1, arg2, arg3, arg4,
arg5, arg6, arg7, arg8,
arg9, arg10, arg11, arg12,
arg13, arg14, arg15, arg16 ) {
var argc = arguments.length;
var buffer = this.buffer;
var other;
if( 1 === argc ) {
if( arg1 instanceof Matrix4 ) {
other = arg1.buffer;
} else {
other = arg1;
}
buffer[0] = other[0];
buffer[1] = other[1];
buffer[2] = other[2];
buffer[3] = other[3];
buffer[4] = other[4];
buffer[5] = other[5];
buffer[6] = other[6];
buffer[7] = other[7];
buffer[8] = other[8];
buffer[9] = other[9];
buffer[10] = other[10];
buffer[11] = other[11];
buffer[12] = other[12];
buffer[13] = other[13];
buffer[14] = other[14];
buffer[15] = other[15];
this.modified = true;
} else if( 16 === argc ) {
buffer[0] = arg1;
buffer[1] = arg2;
buffer[2] = arg3;
buffer[3] = arg4;
buffer[4] = arg5;
buffer[5] = arg6;
buffer[6] = arg7;
buffer[7] = arg8;
buffer[8] = arg9;
buffer[9] = arg10;
buffer[10] = arg11;
buffer[11] = arg12;
buffer[12] = arg13;
buffer[13] = arg14;
buffer[14] = arg15;
buffer[15] = arg16;
this.modified = true;
}
return this;
}
function subtract( arg, result ) {
var other;
if( arg instanceof Matrix4 ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix4.subtract( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function transpose( result ) {
result = result || this;
matrix4.transpose( this.buffer, result.buffer );
result.modified = true;
return this;
}
_.extend( Matrix4.prototype, {
add: add,
clear: clear,
clone: clone,
determinant: determinant,
equal: equal,
inverse: inverse,
multiply: multiply,
set: set,
subtract: subtract,
transpose: transpose
});
return Matrix4;
};
});
define('matrix/transform-api',['require','common/not-implemented','matrix/m4','matrix/matrix4-api'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var M4 = require( "matrix/m4" )( FLOAT_ARRAY_TYPE );
var matrix4 = require( "matrix/matrix4-api" )( FLOAT_ARRAY_TYPE );
function compound( transform, t, r, s ) {
transform = transform || new M4(matrix4.identity);
if( t ) {
translate( t, transform );
}
if( r ) {
rotate( r, transform );
}
if( s ) {
scale( s, transform );
}
return transform;
}
function set(transform, t, r, s){
if (transform){
matrix4.set(transform, matrix4.identity);
}
return compound(transform, t, r, s);
}
function rotate( v, result ) {
result = result || new M4( matrix4.identity );
var sinA,
cosA;
var rotation;
if( 0 !== v[2] ) {
sinA = Math.sin( v[2] );
cosA = Math.cos( v[2] );
rotation = [ cosA, -sinA, 0, 0,
sinA, cosA, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 ];
matrix4.multiply( result, rotation, result );
}
if( 0 !== v[1] ) {
sinA = Math.sin( v[1] );
cosA = Math.cos( v[1] );
rotation = [ cosA, 0, sinA, 0,
0, 1, 0, 0,
-sinA, 0, cosA, 0,
0, 0, 0, 1 ];
matrix4.multiply( result, rotation, result );
}
if( 0 !== v[0] ) {
sinA = Math.sin( v[0] );
cosA = Math.cos( v[0] );
rotation = [ 1, 0, 0, 0,
0, cosA, -sinA, 0,
0, sinA, cosA, 0,
0, 0, 0, 1 ];
matrix4.multiply( result, rotation, result );
}
return result;
}
function scale( v, result ) {
result = result || new M4( matrix4.identity );
matrix4.multiply( result, [v[0], 0, 0, 0,
0, v[1], 0, 0,
0, 0, v[2], 0,
0, 0, 0, 1], result );
return result;
}
function translate( v, result ) {
result = result || new M4( matrix4.identity );
matrix4.multiply( result, [1, 0, 0, v[0],
0, 1, 0, v[1],
0, 0, 1, v[2],
0, 0, 0, 1], result );
return result;
}
var transform = {
compound: compound,
set: set,
rotate: rotate,
scale: scale,
translate: translate
};
return transform;
};
});
define('matrix/t',['require','matrix/m','matrix/m4','matrix/transform-api'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var M = require( "matrix/m" );
var M4 = require( "matrix/m4" )( FLOAT_ARRAY_TYPE );
var transform = require("matrix/transform-api")( FLOAT_ARRAY_TYPE );
var T = function(t, r, s) {
var matrix = new M4();
return transform.set(matrix, t, r, s);
};
T.prototype = new M();
T.prototype.constructor = T;
return T;
};
});
define('matrix/transform',['require','common/not-implemented','matrix/m4','matrix/transform-api','matrix/matrix4-api','matrix/matrix4'],function ( require ) {
return function( FLOAT_ARRAY_TYPE ) {
var notImplemented = require( "common/not-implemented" );
var M4 = require( "matrix/m4" )( FLOAT_ARRAY_TYPE );
var transform = require( "matrix/transform-api" )( FLOAT_ARRAY_TYPE );
var matrix4 = require( "matrix/matrix4-api" )( FLOAT_ARRAY_TYPE );
var Matrix4 = require( "matrix/matrix4" )( FLOAT_ARRAY_TYPE );
function getView( index ) {
return this._views[index];
}
function getValue( index ) {
return this.buffer[index];
}
function setValue( index, value ) {
this.buffer[index] = value;
this.matrix.modified = true;
}
function updateViews() {
var i;
for( i = 0; i < 4; ++ i ) {
this._views[i] = new TransformView( this, this.buffer,
i*4, (i+1)*4 );
}
}
var TransformView = function( matrix, buffer, start, end ) {
this.matrix = matrix;
this.buffer = buffer.subarray( start, end );
Object.defineProperties( this, {
"0": {
get: getValue.bind( this, 0 ),
set: setValue.bind( this, 0 )
},
"1": {
get: getValue.bind( this, 1 ),
set: setValue.bind( this, 1 )
},
"2": {
get: getValue.bind( this, 2 ),
set: setValue.bind( this, 2 )
},
"3": {
get: getValue.bind( this, 3 ),
set: setValue.bind( this, 3 )
}
});
};
var Transform = function( arg1, arg2, arg3 ) {
var argc = arguments.length;
if( 0 === argc ) {
this.buffer = new M4(matrix4.identity);
}else if( 1 === argc ) {
if( arg1 instanceof Transform ||
arg1 instanceof Matrix4 ) {
this.buffer = new M4( arg1.buffer );
} else if( arg1 instanceof M4 ) {
this.buffer = new M4( arg1 );
} else {
this.buffer = new M4(matrix4.identity);
transform.compound( this.buffer, arg1, arg2, arg3 );
}
} else {
this.buffer = new M4(matrix4.identity);
transform.compound(this.buffer, arg1, arg2, arg3 );
}
Object.defineProperties( this, {
"0": {
get: getView.bind( this, 0 )
},
"1": {
get: getView.bind( this, 1 )
},
"2": {
get: getView.bind( this, 2 )
},
"3": {
get: getView.bind( this, 3 )
}
});
this._views = [];
updateViews.call( this );
this.modified = true;
};
function clone() {
return new Transform( this );
}
function equal( arg ) {
var other;
if( arg instanceof Matrix4 ||
arg instanceof Transform ) {
other = arg.buffer;
} else {
other = arg;
}
return matrix4.equal( this.buffer, other );
}
function multiply( arg, result ) {
var other;
if( arg instanceof Matrix4 ||
arg instanceof Transform ) {
other = arg.buffer;
} else {
other = arg;
}
result = result || this;
matrix4.multiply( this.buffer, other, result.buffer );
result.modified = true;
return this;
}
function rotate( v, result ) {
var rotation = transform.rotate( v );
result = result || this;
matrix4.multiply( this.buffer, rotation, result.buffer );
result.modified = true;
return this;
}
function scale( v, result ) {
var scaled = transform.scale( v );
result = result || this;
matrix4.multiply( this.buffer, scaled, result.buffer );
result.modified = true;
return this;
}
function set( t, r, s ) {
transform.set( this.buffer, t, r, s );
this.modified = true;
}
function transformDirection( v, result ) {
}
function transformPoint( v, result ) {
}
function translate( v, result ) {
var translation = transform.translate( v );
result = result || this;
matrix4.multiply( this.buffer, translation, result.buffer );
result.modified = true;
return this;
}
Transform.prototype = {
clone: clone,
equal: equal,
inverseTransformDirection: notImplemented,
inverseTransformPoint: notImplemented,
multiply: multiply,
rotate: rotate,
scale: scale,
set: set,
transformDirection: notImplemented,
transformPoint: notImplemented,
translate: translate
};
return Transform;
};
});
define('_math',['require','constants','equal','vector/v2','vector/vector2','vector/vector2-api','vector/v3','vector/vector3','vector/vector3-api','vector/v4','vector/vector4','vector/vector4-api','matrix/m2','matrix/matrix2','matrix/matrix2-api','matrix/m3','matrix/matrix3','matrix/matrix3-api','matrix/m4','matrix/matrix4','matrix/matrix4-api','matrix/t','matrix/transform','matrix/transform-api'],function ( require ) {
var constants = require( "constants" );
var equal = require( "equal" );
var V2 = require( "vector/v2" );
var Vector2 = require( "vector/vector2" );
var vector2 = require( "vector/vector2-api" );
var V3 = require( "vector/v3" );
var Vector3 = require( "vector/vector3" );
var vector3 = require( "vector/vector3-api" );
var V4 = require( "vector/v4" );
var Vector4 = require( "vector/vector4" );
var vector4 = require( "vector/vector4-api" );
var M2 = require( "matrix/m2" );
var Matrix2 = require( "matrix/matrix2" );
var matrix2 = require( "matrix/matrix2-api" );
var M3 = require( "matrix/m3" );
var Matrix3 = require( "matrix/matrix3" );
var matrix3 = require( "matrix/matrix3-api" );
var M4 = require( "matrix/m4" );
var Matrix4 = require( "matrix/matrix4" );
var matrix4 = require( "matrix/matrix4-api" );
var T = require( "matrix/t" );
var Transform = require( "matrix/transform" );
var transform = require( "matrix/transform-api" );
function extend( object, extra ) {
for ( var prop in extra ) {
if ( !object.hasOwnProperty( prop ) && extra.hasOwnProperty( prop ) ) {
object[prop] = extra[prop];
}
}
}
var _Math = function( options ) {
var FLOAT_ARRAY_ENUM = {
Float32: Float32Array,
Float64: Float64Array
};
this.FLOAT_ARRAY_ENUM = FLOAT_ARRAY_ENUM;
var ARRAY_TYPE = this.ARRAY_TYPE = FLOAT_ARRAY_ENUM.Float32;
extend( this, constants );
this.equal = equal;
extend( this, {
V2: V2( ARRAY_TYPE ),
Vector2: Vector2( ARRAY_TYPE ),
vector2: vector2( ARRAY_TYPE )
});
extend( this, {
V3: V3( ARRAY_TYPE ),
Vector3: Vector3( ARRAY_TYPE ),
vector3: vector3( ARRAY_TYPE )
});
extend( this, {
V4: V4( ARRAY_TYPE ),
Vector4: Vector4( ARRAY_TYPE ),
vector4: vector4( ARRAY_TYPE )
});
extend( this, {
M2: M2( ARRAY_TYPE ),
Matrix2: Matrix2( ARRAY_TYPE ),
matrix2: matrix2( ARRAY_TYPE )
});
extend( this, {
M3: M3( ARRAY_TYPE ),
Matrix3: Matrix3( ARRAY_TYPE ),
matrix3: matrix3( ARRAY_TYPE )
});
extend( this, {
M4: M4( ARRAY_TYPE ),
Matrix4: Matrix4( ARRAY_TYPE ),
matrix4: matrix4( ARRAY_TYPE )
});
extend( this, {
T: T( ARRAY_TYPE ),
Transform: Transform( ARRAY_TYPE ),
transform: transform( ARRAY_TYPE )
});
};
return new _Math();
});
return require('_math');
}));
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('common/guid',['require'],function ( require ) {
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
}).toUpperCase();
}
return guid;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('common/multicast-delegate',['require','common/guid'],function( require ) {
var guid = require( "common/guid" );
function subscribe( callback ) {
if( !callback.hasOwnProperty( "_id" ) ) {
callback._id = guid();
}
if( !this._callbacks.hasOwnProperty( callback._id ) ) {
this._callbacks[callback._id] = callback;
++ this.size;
}
}
function unsubscribe( callback ) {
if( callback.hasOwnProperty( "_id" ) ) {
if( this._callbacks.hasOwnProperty( callback._id ) ) {
delete this._callbacks[callback._id];
-- this.size;
}
}
}
var Delegate = function() {
var callbacks = {};
function dispatcher( data ) {
var i, l;
var count = 0;
var callbackIds = Object.keys( callbacks );
for( i = 0, l = callbackIds.length; i < l; ++ i ) {
var callbackId = callbackIds[i];
var callback = callbacks[callbackId];
callback( data );
++ count;
}
return count;
}
dispatcher._callbacks = callbacks;
dispatcher.subscribe = subscribe;
dispatcher.unsubscribe = unsubscribe;
dispatcher.size = 0;
return dispatcher;
};
return Delegate;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/loop',['require'],function( require ) {
var Loop = function( callback, context ) {
this.L_STARTED = 0;
this.L_PAUSED = 1;
this.L_CANCELLED = 2;
this.L_FINISHED = 3;
this.R_RUNNING = 0;
this.R_IDLE = 1;
this._loopState = this.L_PAUSED;
this._runState = this.R_IDLE;
this.callback = callback;
this.context = context || this;
};
function _run() {
this._runState = this.R_RUNNING;
if( this.callback ) {
this.callback.call( this.context );
if( this.L_STARTED === this._loopState ) {
this._pump();
} else {
this.suspend();
}
}
this._runState = this.R_IDLE;
}
function _pump() {
throw new Error( "not implemented for base prototype" );
}
function suspend() {
this._loopState = this.L_PAUSED;
}
function resume() {
if( !this.callback ) {
throw new Error( "callback not defined" );
}
this._loopState = this.L_STARTED;
if( this._runState === this.R_IDLE ) {
this._pump();
}
}
function isStarted() {
return this._loopState === this.L_STARTED;
}
Loop.prototype = {
suspend: suspend,
resume: resume,
_pump: _pump,
_run: _run,
isStarted: isStarted
};
return Loop;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/request-animation-frame-loop',['require','core/loop'],function( require ) {
if( !window.requestAnimationFrame ) {
window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback, element ) {
window.setTimeout( callback, 1000/60 );
};
}
var Loop = require( "core/loop" );
var RequestAnimationFrameLoop = function( callback, context ) {
Loop.call( this, callback, context );
};
function _pump() {
requestAnimationFrame( this._run.bind( this ) );
}
RequestAnimationFrameLoop.prototype = new Loop();
RequestAnimationFrameLoop.prototype._pump = _pump;
RequestAnimationFrameLoop.prototype.constructor = RequestAnimationFrameLoop;
return RequestAnimationFrameLoop;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/clock',['require','common/multicast-delegate'],function( require ) {
var MulticastDelegate = require( "common/multicast-delegate" );
var C_STARTED = 0,
C_PAUSED = 1;
var Clock = function( delegate ) {
this.time = 0;
this.delta = 0;
this._timeScale = 1.0;
this._idealFrameInterval = 1.0/30.0;
this._clockState = undefined;
this.signal = new MulticastDelegate();
this._delegate = delegate || null;
this._delegateHandler = this.update.bind( this );
if( this._delegate ) {
this._delegate.subscribe( this._delegateHandler );
}
this._stepCount = 0;
this.start();
};
function pause() {
this._clockState = C_PAUSED;
}
function start() {
this._clockState = C_STARTED;
}
function update( delta ) {
if( C_PAUSED !== this._clockState ) {
this.delta = delta * this._timeScale;
} else {
this.delta = this._stepCount * this._idealFrameInterval * this._timeScale;
this._stepCount = 0;
}
this.time += this.delta;
this.signal( this.delta ); // Dispatch time signal
}
function step( count ) {
if( C_PAUSED === this._clockState ) {
this._stepCount += (undefined === count) ? 1 : count;
}
}
function isStarted() {
return this._clockState === C_STARTED;
}
function reset( delegate ) {
if( delegate && delegate != this._delegate ) {
this._delegate.unsubscribe( this._delegateHandler );
this._delegate = delegate || null;
this._delegate.subscribe( this._delegateHandler );
}
this.time = 0;
this.delta = 0;
}
function setTimeScale( scale ) {
this._timeScale = scale;
}
function setIdealFrameInterval( interval ) {
this._idealFrameInterval = interval;
}
Clock.prototype = {
pause: pause,
start: start,
update: update,
isStarted: isStarted,
step: step,
reset: reset,
setTimeScale: setTimeScale,
setIdealFrameInterval: setIdealFrameInterval
};
return Clock;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('common/graph',['require'],function( require ) {
/* Graph
*
* Stores a set of nodes and a set of directed edges connecting them.
* Supports inserting, removing, linking and unlinking nodes. Nodes are
* assumed to be strings.
*
*/
var Graph = function() {
this._nodes = {}; // Nodes in the graph
this._adjacencies = {}; // Adjacency list; Sink maps to sources
this._descendants = {}; // Number of descendants for each node
this._roots = {}; // List of nodes that have no ancestors
this._cachedSort = null; // Cached copy of the sorted nodes
this._cachedSize = 0; // Cached size of the graph
};
function link( source, sink ) {
if( !this._nodes[source] ) {
this._nodes[source] = true;
this._descendants[source] = 0;
}
if( !this._nodes[sink] ) {
this._nodes[sink] = true;
this._descendants[sink] = 0;
this._roots[sink] = true;
}
if( !this._adjacencies[sink] ) {
this._adjacencies[sink] = {};
}
this._adjacencies[sink][source] = true;
++ this._descendants[source];
if( this._roots[source] ) {
delete this._roots[source];
}
this._cachedSort = null;
return this;
}
function unlink( source, sink ) {
if( this._adjacencies[sink] && this._adjacencies[sink][source] ) {
delete this._adjacencies[sink][source];
-- this._descendants[source];
if( !Object.keys( this._adjacencies[sink] ).length ) {
delete this._adjacencies[sink];
}
if( !this._descendants[source] ) {
this._roots[source] = true;
}
} else {
throw new Error( "no such link: ", source, "->", sink );
}
this._cachedSort = null;
return this;
}
function insert( node ) {
if( !this._nodes[node] ) {
this._nodes[node] = true;
this._descendants[node] = 0;
this._roots[node] = true;
++ this._cachedSize;
this._cachedSort = null;
}
return this;
}
function remove( node ) {
var edges = this._adjacencies[node] || {};
if( this._nodes[node] ) {
for( var source in edges ) {
this.unlink( source, node );
}
delete this._nodes[node];
delete this._descendants[node];
-- this._cachedSize;
this._cachedSort = null;
} else {
throw new Error( "no such node: ", node );
}
return this;
}
function size() {
return this._cachedSize;
}
function clear() {
this._nodes = {};
this._adjacencies = {};
this._descendants = {};
this._roots = {};
this._cachedSort = null;
this._cachedSize = 0;
return this;
}
function sort() {
var graph = this;
var sorted = [],
roots = Object.keys( this._roots ),
visited = [];
function visit( sink, visitedStack ) {
if( -1 !== visitedStack.indexOf( sink ) ) {
throw new Error( "directed cycle detected" );
}
visitedStack.push( sink );
if( -1 === visited.indexOf( sink ) ) {
visited.push( sink );
var edges = graph._adjacencies[sink];
for( var source in edges ) {
if( !graph._nodes[source] ) { // This might be a dangling edge
delete edges[source];
} else {
visit( source, visitedStack );
}
}
sorted.push( sink );
}
visitedStack.pop();
}
if( null === this._cachedSort ) {
for( var i = 0, l = roots.length; i < l; ++ i ) {
visit( roots[i], [] );
}
if( sorted.length < Object.keys( this._nodes ).length ) {
throw new Error( "directed cycle detected" );
}
this._cachedSort = sorted;
}
return this._cachedSort.slice();
}
function hasNode( node ) {
return this._nodes.hasOwnProperty( node );
}
function hasLink( source, sink ) {
if( !this.hasNode( source ) ) { // This might be a dangling edge
this.unlink( source, sink );
return false;
}
return this._adjacencies.hasOwnProperty( sink ) &&
this._adjacencies[sink].hasOwnProperty( source );
}
Graph.prototype = {
link: link,
unlink: unlink,
insert: insert,
remove: remove,
size: size,
clear: clear,
sort: sort,
hasNode: hasNode,
hasLink: hasLink
};
return Graph;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/dependency-scheduler',['require','common/graph'],function ( require ) {
var Graph = require( "common/graph" );
var defaultPhases = [
"@input",
"@update",
"@render"
];
var DependencyScheduler = function( phases ) {
this.current = null;
this._tasks = {};
this._graph = new Graph();
this._schedule = null;
this._phases = phases || defaultPhases;
this.clear();
};
function update() {
var i, l;
var sortedGraph = this._graph.sort();
this._schedule = [];
for( i = 0, l = sortedGraph.length; i < l; ++ i ) {
if( this._tasks.hasOwnProperty( sortedGraph[i] ) ) {
this._schedule.push( sortedGraph[i] );
}
}
return this;
}
function next() {
if( !this._schedule ) {
return undefined;
}
var taskId = this._schedule.shift();
var task = this._tasks[taskId];
this.remove( taskId );
return task;
}
function hasNext() {
return this._schedule && this._schedule.length > 0;
}
function insert( task, taskId, schedule ) {
var i, l;
this._tasks[taskId] = task;
this._graph.insert( taskId );
if( schedule ) {
if( schedule.tags ) {
var tags = schedule.tags;
for( i = 0, l = schedule.tags.length; i < l; ++ i ) {
var tag = tags[i];
if( tag[0] === '@' ) {
this._graph.link( task.id, tag );
} else {
this._graph.link( tag, task.id );
}
}
}
if( schedule.dependsOn ) {
var dependsOn = schedule.dependsOn;
for( i = 0, l = dependsOn.length; i < l; ++ i ) {
this._graph.link( task.id, dependsOn[i] );
}
}
}
return this;
}
function remove( taskId ) {
if( !this._graph.hasNode( taskId ) ) {
throw new Error( "task is not scheduled to run" );
}
this._graph.remove( taskId );
delete this._tasks[taskId];
return this;
}
function size() {
return this._graph.size();
}
function clear() {
this._schedule = null;
this._graph.clear();
// Set up scheduler phases
var i;
for( i = 0; i < this._phases.length; ++ i ) {
this._graph.insert( this._phases[i] );
if( i > 0 ) {
this._graph.link( this._phases[i-1], this._phases[i] );
}
}
}
DependencyScheduler.prototype = {
next: next,
insert: insert,
remove: remove,
size: size,
hasNext: hasNext,
update: update,
clear: clear
};
return DependencyScheduler;
} );
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* when
* A lightweight CommonJS Promises/A and when() implementation
*
* when is part of the cujo.js family of libraries (http://cujojs.com/)
*
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* @version 1.0.4
*/
(function(define) {
define('when',[],function() {
var freeze, reduceArray, undef;
/**
* No-Op function used in method replacement
* @private
*/
function noop() {}
/**
* Allocate a new Array of size n
* @private
* @param n {number} size of new Array
* @returns {Array}
*/
function allocateArray(n) {
return new Array(n);
}
/**
* Use freeze if it exists
* @function
* @private
*/
freeze = Object.freeze || function(o) { return o; };
// ES5 reduce implementation if native not available
// See: http://es5.github.com/#x15.4.4.21 as there are many
// specifics and edge cases.
reduceArray = [].reduce ||
function(reduceFunc /*, initialValue */) {
// ES5 dictates that reduce.length === 1
// This implementation deviates from ES5 spec in the following ways:
// 1. It does not check if reduceFunc is a Callable
var arr, args, reduced, len, i;
i = 0;
arr = Object(this);
len = arr.length >>> 0;
args = arguments;
// If no initialValue, use first item of array (we know length !== 0 here)
// and adjust i to start at second item
if(args.length <= 1) {
// Skip to the first real element in the array
for(;;) {
if(i in arr) {
reduced = arr[i++];
break;
}
// If we reached the end of the array without finding any real
// elements, it's a TypeError
if(++i >= len) {
throw new TypeError();
}
}
} else {
// If initialValue provided, use it
reduced = args[1];
}
// Do the actual reduce
for(;i < len; ++i) {
// Skip holes
if(i in arr)
reduced = reduceFunc(reduced, arr[i], i, arr);
}
return reduced;
};
/**
* Trusted Promise constructor. A Promise created from this constructor is
* a trusted when.js promise. Any other duck-typed promise is considered
* untrusted.
*/
function Promise() {}
/**
* Create an already-resolved promise for the supplied value
* @private
*
* @param value anything
* @return {Promise}
*/
function resolved(value) {
var p = new Promise();
p.then = function(callback) {
checkCallbacks(arguments);
var nextValue;
try {
if(callback) nextValue = callback(value);
return promise(nextValue === undef ? value : nextValue);
} catch(e) {
return rejected(e);
}
};
return freeze(p);
}
/**
* Create an already-rejected {@link Promise} with the supplied
* rejection reason.
* @private
*
* @param reason rejection reason
* @return {Promise}
*/
function rejected(reason) {
var p = new Promise();
p.then = function(callback, errback) {
checkCallbacks(arguments);
var nextValue;
try {
if(errback) {
nextValue = errback(reason);
return promise(nextValue === undef ? reason : nextValue)
}
return rejected(reason);
} catch(e) {
return rejected(e);
}
};
return freeze(p);
}
/**
* Helper that checks arrayOfCallbacks to ensure that each element is either
* a function, or null or undefined.
*
* @param arrayOfCallbacks {Array} array to check
* @throws {Error} if any element of arrayOfCallbacks is something other than
* a Functions, null, or undefined.
*/
function checkCallbacks(arrayOfCallbacks) {
var arg, i = arrayOfCallbacks.length;
while(i) {
arg = arrayOfCallbacks[--i];
if (arg != null && typeof arg != 'function') throw new Error('callback is not a function');
}
}
/**
* Creates a new, CommonJS compliant, Deferred with fully isolated
* resolver and promise parts, either or both of which may be given out
* safely to consumers.
* The Deferred itself has the full API: resolve, reject, progress, and
* then. The resolver has resolve, reject, and progress. The promise
* only has then.
*
* @memberOf when
* @function
*
* @returns {Deferred}
*/
function defer() {
var deferred, promise, listeners, progressHandlers, _then, _progress, complete;
listeners = [];
progressHandlers = [];
/**
* Pre-resolution then() that adds the supplied callback, errback, and progback
* functions to the registered listeners
*
* @private
*
* @param [callback] {Function} resolution handler
* @param [errback] {Function} rejection handler
* @param [progback] {Function} progress handler
*
* @throws {Error} if any argument is not null, undefined, or a Function
*/
_then = function unresolvedThen(callback, errback, progback) {
// Check parameters and fail immediately if any supplied parameter
// is not null/undefined and is also not a function.
// That is, any non-null/undefined parameter must be a function.
checkCallbacks(arguments);
var deferred = defer();
listeners.push(function(promise) {
promise.then(callback, errback)
.then(deferred.resolve, deferred.reject, deferred.progress);
});
progback && progressHandlers.push(progback);
return deferred.promise;
};
/**
* Registers a handler for this {@link Deferred}'s {@link Promise}. Even though all arguments
* are optional, each argument that *is* supplied must be null, undefined, or a Function.
* Any other value will cause an Error to be thrown.
*
* @memberOf Promise
*
* @param [callback] {Function} resolution handler
* @param [errback] {Function} rejection handler
* @param [progback] {Function} progress handler
*
* @throws {Error} if any argument is not null, undefined, or a Function
*/
function then(callback, errback, progback) {
return _then(callback, errback, progback);
}
/**
* Resolves this {@link Deferred}'s {@link Promise} with val as the
* resolution value.
*
* @memberOf Resolver
*
* @param val anything
*/
function resolve(val) {
complete(resolved(val));
}
/**
* Rejects this {@link Deferred}'s {@link Promise} with err as the
* reason.
*
* @memberOf Resolver
*
* @param err anything
*/
function reject(err) {
complete(rejected(err));
}
/**
* @private
* @param update
*/
_progress = function(update) {
var progress, i = 0;
while (progress = progressHandlers[i++]) progress(update);
};
/**
* Emits a progress update to all progress observers registered with
* this {@link Deferred}'s {@link Promise}
*
* @memberOf Resolver
*
* @param update anything
*/
function progress(update) {
_progress(update);
}
/**
* Transition from pre-resolution state to post-resolution state, notifying
* all listeners of the resolution or rejection
*
* @private
*
* @param completed {Promise} the completed value of this deferred
*/
complete = function(completed) {
var listener, i = 0;
// Replace _then with one that directly notifies with the result.
_then = completed.then;
// Replace complete so that this Deferred can only be completed
// once. Also Replace _progress, so that subsequent attempts to issue
// progress throw.
complete = _progress = function alreadyCompleted() {
// TODO: Consider silently returning here so that parties who
// have a reference to the resolver cannot tell that the promise
// has been resolved using try/catch
throw new Error("already completed");
};
// Free progressHandlers array since we'll never issue progress events
// for this promise again now that it's completed
progressHandlers = undef;
// Notify listeners
// Traverse all listeners registered directly with this Deferred
while (listener = listeners[i++]) {
listener(completed);
}
listeners = [];
};
/**
* The full Deferred object, with both {@link Promise} and {@link Resolver}
* parts
* @class Deferred
* @name Deferred
* @augments Resolver
* @augments Promise
*/
deferred = {};
// Promise and Resolver parts
// Freeze Promise and Resolver APIs
/**
* The Promise API
* @namespace Promise
* @name Promise
*/
promise = new Promise();
promise.then = deferred.then = then;
/**
* The {@link Promise} for this {@link Deferred}
* @memberOf Deferred
* @name promise
* @type {Promise}
*/
deferred.promise = freeze(promise);
/**
* The {@link Resolver} for this {@link Deferred}
* @namespace Resolver
* @name Resolver
* @memberOf Deferred
* @name resolver
* @type {Resolver}
*/
deferred.resolver = freeze({
resolve: (deferred.resolve = resolve),
reject: (deferred.reject = reject),
progress: (deferred.progress = progress)
});
return deferred;
}
/**
* Determines if promiseOrValue is a promise or not. Uses the feature
* test from http://wiki.commonjs.org/wiki/Promises/A to determine if
* promiseOrValue is a promise.
*
* @param promiseOrValue anything
*
* @returns {Boolean} true if promiseOrValue is a {@link Promise}
*/
function isPromise(promiseOrValue) {
return promiseOrValue && typeof promiseOrValue.then === 'function';
}
/**
* Register an observer for a promise or immediate value.
*
* @function
* @name when
* @namespace
*
* @param promiseOrValue anything
* @param {Function} [callback] callback to be called when promiseOrValue is
* successfully resolved. If promiseOrValue is an immediate value, callback
* will be invoked immediately.
* @param {Function} [errback] callback to be called when promiseOrValue is
* rejected.
* @param {Function} [progressHandler] callback to be called when progress updates
* are issued for promiseOrValue.
*
* @returns {Promise} a new {@link Promise} that will complete with the return
* value of callback or errback or the completion value of promiseOrValue if
* callback and/or errback is not supplied.
*/
function when(promiseOrValue, callback, errback, progressHandler) {
// Get a promise for the input promiseOrValue
// See promise()
var trustedPromise = promise(promiseOrValue);
// Register promise handlers
return trustedPromise.then(callback, errback, progressHandler);
}
/**
* Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
* promiseOrValue is a foreign promise, or a new, already-resolved {@link Promise}
* whose resolution value is promiseOrValue if promiseOrValue is an immediate value.
*
* Note that this function is not safe to export since it will return its
* input when promiseOrValue is a {@link Promise}
*
* @private
*
* @param promiseOrValue anything
*
* @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
* returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
* whose resolution value is:
* * the resolution value of promiseOrValue if it's a foreign promise, or
* * promiseOrValue if it's a value
*/
function promise(promiseOrValue) {
var promise, deferred;
if(promiseOrValue instanceof Promise) {
// It's a when.js promise, so we trust it
promise = promiseOrValue;
} else {
// It's not a when.js promise. Check to see if it's a foreign promise
// or a value.
deferred = defer();
if(isPromise(promiseOrValue)) {
// It's a compliant promise, but we don't know where it came from,
// so we don't trust its implementation entirely. Introduce a trusted
// middleman when.js promise
// IMPORTANT: This is the only place when.js should ever call .then() on
// an untrusted promise.
promiseOrValue.then(deferred.resolve, deferred.reject, deferred.progress);
promise = deferred.promise;
} else {
// It's a value, not a promise. Create an already-resolved promise
// for it.
deferred.resolve(promiseOrValue);
promise = deferred.promise;
}
}
return promise;
}
/**
* Return a promise that will resolve when howMany of the supplied promisesOrValues
* have resolved. The resolution value of the returned promise will be an array of
* length howMany containing the resolutions values of the triggering promisesOrValues.
*
* @memberOf when
*
* @param promisesOrValues {Array} array of anything, may contain a mix
* of {@link Promise}s and values
* @param howMany
* @param [callback]
* @param [errback]
* @param [progressHandler]
*
* @returns {Promise}
*/
function some(promisesOrValues, howMany, callback, errback, progressHandler) {
var toResolve, results, ret, deferred, resolver, rejecter, handleProgress, len, i;
len = promisesOrValues.length >>> 0;
toResolve = Math.max(0, Math.min(howMany, len));
results = [];
deferred = defer();
ret = when(deferred, callback, errback, progressHandler);
// Wrapper so that resolver can be replaced
function resolve(val) {
resolver(val);
}
// Wrapper so that rejecter can be replaced
function reject(err) {
rejecter(err);
}
// Wrapper so that progress can be replaced
function progress(update) {
handleProgress(update);
}
function complete() {
resolver = rejecter = handleProgress = noop;
}
// No items in the input, resolve immediately
if (!toResolve) {
deferred.resolve(results);
} else {
// Resolver for promises. Captures the value and resolves
// the returned promise when toResolve reaches zero.
// Overwrites resolver var with a noop once promise has
// be resolved to cover case where n < promises.length
resolver = function(val) {
// This orders the values based on promise resolution order
// Another strategy would be to use the original position of
// the corresponding promise.
results.push(val);
if (!--toResolve) {
complete();
deferred.resolve(results);
}
};
// Rejecter for promises. Rejects returned promise
// immediately, and overwrites rejecter var with a noop
// once promise to cover case where n < promises.length.
// TODO: Consider rejecting only when N (or promises.length - N?)
// promises have been rejected instead of only one?
rejecter = function(err) {
complete();
deferred.reject(err);
};
handleProgress = deferred.progress;
// TODO: Replace while with forEach
for(i = 0; i < len; ++i) {
if(i in promisesOrValues) {
when(promisesOrValues[i], resolve, reject, progress);
}
}
}
return ret;
}
/**
* Return a promise that will resolve only once all the supplied promisesOrValues
* have resolved. The resolution value of the returned promise will be an array
* containing the resolution values of each of the promisesOrValues.
*
* @memberOf when
*
* @param promisesOrValues {Array} array of anything, may contain a mix
* of {@link Promise}s and values
* @param [callback] {Function}
* @param [errback] {Function}
* @param [progressHandler] {Function}
*
* @returns {Promise}
*/
function all(promisesOrValues, callback, errback, progressHandler) {
var results, promise;
results = allocateArray(promisesOrValues.length);
promise = reduce(promisesOrValues, reduceIntoArray, results);
return when(promise, callback, errback, progressHandler);
}
function reduceIntoArray(current, val, i) {
current[i] = val;
return current;
}
/**
* Return a promise that will resolve when any one of the supplied promisesOrValues
* has resolved. The resolution value of the returned promise will be the resolution
* value of the triggering promiseOrValue.
*
* @memberOf when
*
* @param promisesOrValues {Array} array of anything, may contain a mix
* of {@link Promise}s and values
* @param [callback] {Function}
* @param [errback] {Function}
* @param [progressHandler] {Function}
*
* @returns {Promise}
*/
function any(promisesOrValues, callback, errback, progressHandler) {
function unwrapSingleResult(val) {
return callback(val[0]);
}
return some(promisesOrValues, 1, unwrapSingleResult, errback, progressHandler);
}
/**
* Traditional map function, similar to `Array.prototype.map()`, but allows
* input to contain {@link Promise}s and/or values, and mapFunc may return
* either a value or a {@link Promise}
*
* @memberOf when
*
* @param promisesOrValues {Array} array of anything, may contain a mix
* of {@link Promise}s and values
* @param mapFunc {Function} mapping function mapFunc(value) which may return
* either a {@link Promise} or value
*
* @returns {Promise} a {@link Promise} that will resolve to an array containing
* the mapped output values.
*/
function map(promisesOrValues, mapFunc) {
var results, i;
// Since we know the resulting length, we can preallocate the results
// array to avoid array expansions.
i = promisesOrValues.length;
results = allocateArray(i);
// Since mapFunc may be async, get all invocations of it into flight
// asap, and then use reduce() to collect all the results
for(;i >= 0; --i) {
if(i in promisesOrValues)
results[i] = when(promisesOrValues[i], mapFunc);
}
// Could use all() here, but that would result in another array
// being allocated, i.e. map() would end up allocating 2 arrays
// of size len instead of just 1. Since all() uses reduce()
// anyway, avoid the additional allocation by calling reduce
// directly.
return reduce(results, reduceIntoArray, results);
}
/**
* Traditional reduce function, similar to `Array.prototype.reduce()`, but
* input may contain {@link Promise}s and/or values, but reduceFunc
* may return either a value or a {@link Promise}, *and* initialValue may
* be a {@link Promise} for the starting value.
*
* @memberOf when
*
* @param promisesOrValues {Array} array of anything, may contain a mix
* of {@link Promise}s and values
* @param reduceFunc {Function} reduce function reduce(currentValue, nextValue, index, total),
* where total is the total number of items being reduced, and will be the same
* in each call to reduceFunc.
* @param initialValue starting value, or a {@link Promise} for the starting value
*
* @returns {Promise} that will resolve to the final reduced value
*/
function reduce(promisesOrValues, reduceFunc, initialValue) {
var total, args;
total = promisesOrValues.length;
// Skip promisesOrValues, since it will be used as 'this' in the call
// to the actual reduce engine below.
// Wrap the supplied reduceFunc with one that handles promises and then
// delegates to the supplied.
args = [
function (current, val, i) {
return when(current, function (c) {
return when(val, function (value) {
return reduceFunc(c, value, i, total);
});
});
}
];
if (arguments.length >= 3) args.push(initialValue);
return promise(reduceArray.apply(promisesOrValues, args));
}
/**
* Ensure that resolution of promiseOrValue will complete resolver with the completion
* value of promiseOrValue, or instead with resolveValue if it is provided.
*
* @memberOf when
*
* @param promiseOrValue
* @param resolver {Resolver}
* @param [resolveValue] anything
*
* @returns {Promise}
*/
function chain(promiseOrValue, resolver, resolveValue) {
var useResolveValue = arguments.length > 2;
return when(promiseOrValue,
function(val) {
if(useResolveValue) val = resolveValue;
resolver.resolve(val);
return val;
},
function(e) {
resolver.reject(e);
return rejected(e);
},
resolver.progress
);
}
//
// Public API
//
when.defer = defer;
when.isPromise = isPromise;
when.some = some;
when.all = all;
when.any = any;
when.reduce = reduce;
when.map = map;
when.chain = chain;
return when;
});
})(typeof define == 'function'
? define
: function (factory) { typeof module != 'undefined'
? (module.exports = factory())
: (this.when = factory());
}
// Boilerplate for AMD, Node, and browser global
);
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/function-task',['require','common/guid','when'],function ( require ) {
var guid = require( "common/guid" );
var when = require( "when" );
var Complete = function( value ) {
if( !( this instanceof Complete ) ) {
return new Complete( value );
}
this.value = value;
};
var DefaultSchedule = function() {
if( !( this instanceof DefaultSchedule ) ) {
return new DefaultSchedule();
}
this.tags = [];
this.dependsOn = [];
};
// Task states
var T_STARTED = 0,
T_PAUSED = 1,
T_CANCELLED = 2,
T_CLOSED = 3;
// Run states
var R_RUNNING = 0,
R_BLOCKED = 1,
R_RESOLVED = 2,
R_REJECTED = 3;
var FunctionTask = function( scheduler, thunk, schedule, context ) {
this.id = guid();
this._thunk = thunk;
this._taskState = T_PAUSED;
this._runState = R_RESOLVED;
this._scheduler = scheduler;
this._schedule = schedule || DefaultSchedule();
this.result = undefined;
this._deferred = when.defer();
this.then = this._deferred.promise.then;
this._context = context || this;
};
function start( schedule ) {
this._schedule = schedule || this._schedule;
if( this._taskState !== T_PAUSED ) {
throw new Error( "task is already started or completed" );
}
this._taskState = T_STARTED;
if( this._runState !== R_BLOCKED ) {
this._scheduler.insert( this, this.id, this._schedule );
}
return this;
}
function pause() {
if( this._runState === R_RUNNING ) {
throw new Error( "task can only be paused while blocked" );
}
this._taskState = T_PAUSED;
this._scheduler.remove( this.id );
return this;
}
function cancel() {
if( this._runState === R_RUNNING ) {
throw new Error( "tasks can only be cancelled while blocked" );
}
this._taskState = T_CANCELLED;
this._scheduler.insert( this, this.id );
return this;
}
function isStarted() {
return this._taskState === T_STARTED;
}
function isRunning() {
return this._runState === R_RUNNING;
}
function isComplete() {
return this._taskState === T_CLOSED;
}
// TD: this will need to change for cooperative tasks
// TD: most of this prototype can be factored into a Task base
function run() {
var task = this;
var result = task.result;
task.result = undefined;
task._scheduler.current = task;
try{
task._runState = R_RUNNING;
if( task._taskState === T_CANCELLED ) {
task._runState = R_RESOLVED;
task._taskState = T_CLOSED;
task._scheduler.remove( task.id );
} else if( task._taskState === T_STARTED ) {
// Run the task
result = task._thunk.call( this._context, result );
task._runState = R_BLOCKED;
// Process the result
if( result instanceof Complete ) {
task.result = result.value;
task._taskState = T_CLOSED;
task._runState = R_RESOLVED;
task._deferred.resolve( task.result );
} else {
task.result = when( result,
// callback
function( value ) {
task.result = value;
task._runState = R_RESOLVED;
if( task._taskState === T_STARTED ) {
task._scheduler.insert( task, task.id, task._schedule );
}
},
// errback
function( error ) {
task.result = error;
task._runState = R_REJECTED;
if( task._taskState === T_STARTED ) {
task._scheduler.insert( task, task.id, task._schedule );
}
}
);
}
} else {
throw Error( "task is not runnable" );
}
} catch( exception ) {
task.result = exception;
task._taskState = T_CLOSED;
task._runState = R_REJECTED;
task._deferred.reject( exception );
console.log( "Task", task.id, ": ", exception.stack );
}
task._scheduler.current = null;
return this;
}
function toString() {
return "[object FunctionTask " + this.id + "]";
}
FunctionTask.prototype = {
pause: pause,
start: start,
cancel: cancel,
isStarted: isStarted,
isRunning: isRunning,
isComplete: isComplete,
toString: toString,
run: run,
when: when,
Complete: Complete
};
return FunctionTask;
} );
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/timer',['require'],function( require ) {
var T_STARTED = 0,
T_PAUSED = 1;
var Timer = function( delegate, delay, callback, data ) {
this._delegate = delegate;
this._callback = callback;
this._data = data;
this._delay = delay;
this.elapsed = 0;
this._timerState = undefined;
this.start();
};
function update( delta ) {
if( T_PAUSED !== this._timerState ) {
this.elapsed += delta;
if( this.elapsed >= this._delay ) {
this._callback( this._data );
this.pause();
}
}
}
function start() {
this._timerState = T_STARTED;
this._delegate.subscribe( this.update );
}
function pause() {
this._timerState = T_PAUSED;
this._delegate.unsubscribe( this.update );
}
function isStarted() {
return this._timerState === T_STARTED;
}
function reset() {
this.elapsed = 0;
this.start();
}
Timer.prototype = {
start: start,
pause: pause,
update: update,
isStarted: isStarted,
reset: reset
};
return Timer;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/event',['require'],function( require ) {
function dispatch() {
var dispatchList = Array.prototype.slice.call( arguments, 0 );
var i, l;
if( dispatchList.length > 0 && Array.isArray( dispatchList[0] ) ) {
dispatchList = dispatchList[0];
}
for( i = 0, l = dispatchList.length; i < l; ++ i ) {
try {
var handler = dispatchList[i];
if( handler.handleEvent ) {
handler.handleEvent.call( handler, this );
}
} catch( error ) {
console.log( error );
}
}
}
var Event = function( type, data, queue ) {
if( undefined === type || type.length < 1 ) {
throw new Error( "event must have a non-trivial type" );
}
this.type = type;
this.data = data;
if( undefined === queue ) {
queue = true;
}
this.queue = queue;
this.dispatch = dispatch.bind( this );
};
return Event;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('common/decode-data-uri',['require'],function ( require ) {
function decodeDataUri(uri) {
var components = uri.match( ':.*,' )[0].slice(1, -1).split(';');
var contentType = components[0], encoding = components[1], base64 = components[2];
var data = decodeURIComponent(uri.match( ',.*' )[0].slice(1));
switch( contentType ) {
case '':
case 'text/plain':
return data;
default:
throw 'unknown content type: ' + contentType;
}
}
return decodeDataUri;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('common/decode-javascript-uri',['require'],function ( require ) {
function decodeJavaScriptUri( uri ) {
/*jshint scripturl:true*/
var js = uri.match( '^javascript://.*' )[0].slice( 'javascript://'.length );
return decodeURIComponent( js );
}
return decodeJavaScriptUri;
});
define('core/loaders/default',['require','common/decode-data-uri','common/decode-javascript-uri'],function(require) {
var decodeDataURI = require( "common/decode-data-uri" );
var decodeJavaScriptURI = require( "common/decode-javascript-uri" );
return function(url, onsuccess, onfailure) {
if( url.match('^data:') ) {
onsuccess( decodeDataURI( url ) );
} else if( url.match( '^javascript:' ) ) {
onsuccess( decodeJavaScriptURI( url ) );
} else {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if(4 != xhr.readyState) {
return;
}
if(xhr.status < 200 || xhr.status > 299) {
onfailure(xhr.statusText);
return;
}
onsuccess(xhr.responseText);
};
xhr.send(null);
}
};
});
define('core/get',['require','core/loaders/default'],function(require) {
var defaultLoad = require( 'core/loaders/default' );
var get = function resourceGet(requests, options) {
options = options || {};
options.oncomplete = options.oncomplete || function () {};
if(!requests.length) {
options.oncomplete();
return;
}
var requestsHandled = 0;
var requestHandled = function() {
++ requestsHandled;
if( requestsHandled === requests.length ) {
options.oncomplete();
}
};
var doLoad = function( load, request ) {
load(
request.url,
function loadSuccess(data) {
if(undefined === data) {
request.onfailure('load returned with not data');
} else {
var instance = new request.type(data);
request.onsuccess(instance);
}
requestHandled();
},
function loadFailure(error) {
request.onfailure('load failed: ' + error);
requestHandled();
}
);
};
for(var i = 0; i < requests.length; i++) {
var request = requests[i];
var load = request.load || defaultLoad;
doLoad( load, request );
}
return;
};
return get;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('common/get-url-params',['require'],function ( require ) {
function getURLParams( url ) {
var urlParts = url.split("?");
var result = {};
if( urlParts[1] ) {
var params = urlParts[1].split("&");
for ( var i = 0; i < params.length; ++i ) {
var item = params[i].split("=");
var key = decodeURIComponent(item[0]);
var val = decodeURIComponent(item[1]);
result[key] = val;
}
}
return result;
}
return getURLParams;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('base/component',['require','core/event'],function( require ) {
var Event = require( "core/event" );
var Component = function( type, provider, dependsOn ) {
this.type = type; // String identifying the type of this component
this.provider = provider; // Reference to the object instance that provides
// this component
this.dependsOn = dependsOn || []; // List of component types that this
// component depends on
this.owner = null; // Reference to the entity instance that owns this
this._queuedEvents = []; // List of queued events
};
function setOwner( owner ) {
if( owner !== this.owner ) {
var previous = this.owner;
this.owner = owner;
var event = new Event(
'ComponentOwnerChanged',
{
current: owner,
previous: previous
},
false
);
event.dispatch( this );
}
}
function handleEvent( event ) {
if( "on" + event.type in this ) {
if( event.queue ) {
this._queuedEvents.push( event );
} else {
var handler = this["on" + event.type];
try {
handler.call( this, event );
} catch( error ) {
console.log( error );
}
}
}
}
function handleQueuedEvent() {
if( this._queuedEvents.length > 0 ) {
var event = this._queuedEvents.shift();
if( "on" + event.type in this ) {
var handler = this["on" + event.type];
try {
handler.call( this, event );
} catch( error ) {
console.log( error );
}
}
}
return this._queuedEvents.length;
}
Component.prototype = {
setOwner: setOwner,
handleEvent: handleEvent,
handleQueuedEvent: handleQueuedEvent
};
return Component;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('base/service',['require','core/function-task'],function( require ) {
var Task = require( "core/function-task" );
var Service = function( scheduler, schedules, dependsOn ) {
this._schedules = schedules || {};
this.dependsOn = dependsOn || [];
this._tasks = {};
this._registeredComponents = {};
if( scheduler ) {
var i, l;
var callbackNames = Object.keys( this._schedules );
for( i = 0, l = callbackNames.length; i < l; ++ i ) {
var callbackName = callbackNames[i];
if( !this[callbackName] ) {
throw new Error( "missing scheduler target: " + callbackName );
}
var schedule = this._schedules[callbackName] || {};
// Create a new task to run this callback
this._tasks[callbackName] = new Task( scheduler, this[callbackName],
schedule, this );
this._tasks[callbackName].start();
}
}
};
function registerComponent( id, component ) {
if( !this._registeredComponents.hasOwnProperty( component.type ) ) {
this._registeredComponents[component.type] = {};
}
this._registeredComponents[component.type][id] = component;
return this;
}
function unregisterComponent( id, component ) {
if( this._registeredComponents.hasOwnProperty( component.type ) &&
this._registeredComponents[component.type].hasOwnProperty( id ) ) {
delete this._registeredComponents[component.type][id];
}
return this;
}
function suspend() {
var i, l;
var taskNames = Object.keys( this._tasks );
for( i = 0, l = taskNames.length; i < l; ++ i ) {
var taskName = taskNames[i];
this._tasks[taskName].pause();
}
return this;
}
function resume() {
var i, l;
var taskNames = Object.keys( this._tasks );
for( i = 0, l = taskNames.length; i < l; ++ i ) {
var taskName = taskNames[i];
var schedule = this._schedules[taskName] || {};
this._tasks[taskName].start( schedule );
}
return this;
}
function handleEvent( event ) {
var i, l;
if( "on" + event.type in this ) {
var handler = this["on" + event.type];
try {
handler.call( this, event );
} catch( error ) {
console.log( error );
}
}
}
Service.prototype = {
registerComponent: registerComponent,
unregisterComponent: unregisterComponent,
suspend: suspend,
resume: resume,
handleEvent: handleEvent
};
return Service;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('base/extension',['require'],function ( require ) {
var Extension = function( name, options ) {
if( typeof name !== "string" || name.length === 0 ) {
throw new Error( "extension needs a non-trivial name" );
}
this.name = name;
options = options || {};
var serviceNames, serviceName, service;
var componentNames, componentName, component;
var resourceNames, resourceName, resource;
var i, l;
var j, m;
this.services = {};
if( options.hasOwnProperty( "services" ) ) {
serviceNames = Object.keys( options.services );
for( i = 0, l = serviceNames.length; i < l; ++ i ) {
serviceName = serviceNames[i];
service = options.services[serviceName];
if( typeof service === "function" ) {
this.services[serviceName] = service;
} else if( typeof service === "object" ) {
this.services[serviceName] = {};
this.services[serviceName].service = service.service;
if( service.hasOwnProperty( "components" ) ) {
this.services[serviceName].components = {};
componentNames = Object.keys( service.components );
for( j = 0, m = componentNames.length; j < m; ++ j ) {
componentName = componentNames[j];
this.services[serviceName].components[componentName] = service.components[componentName];
}
}
if( service.hasOwnProperty( "resources" ) ) {
this.services[serviceName].resources = {};
resourceNames = Object.keys( service.resources );
for( j = 0, m = resourceNames.length; j < m; ++ j ) {
resourceName = resourceNames[j];
this.services[serviceName].resources[resourceName] = service.resources[resourceName];
}
}
} else {
throw new Error( "malformed extension" );
}
}
}
this.components = {};
if( options.hasOwnProperty( "components" ) ) {
this.components = options.components;
}
this.resources = {};
if( options.hasOwnProperty( "resources" ) ) {
this.resources = options.resources;
}
};
return Extension;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/entity',['require','common/guid','core/event'],function( require ) {
var guid = require( "common/guid" );
var Event = require( "core/event" );
var Entity = function( name, components, tags, parent ) {
this.id = guid();
this.name = name || "";
this.active = false;
this.parent = null;
this._children = {};
this.space = null;
this.size = 0;
this._components = {};
this.tags = tags || [];
// Add components from the constructor list
if( components && components.length > 0) {
if (this.validateDependencies.call(this, components)){
var i, l;
for ( i = 0, l = components.length; i < l; ++ i){
this.addComponent.call(this, components[i], true);
}
}else{
throw new Error( "required component missing" );
}
}
if( parent ) {
this.setParent( parent );
}
};
function addComponent( component, force ) {
if (force || this.validateDependencies.call(this, component)){
var previous = this.removeComponent( component.type );
component.setOwner( this );
this._components[component.type] = component;
++ this.size;
var event = new Event( "EntityComponentAdded", component );
event.dispatch( this );
return previous;
} else {
throw new Error( "required component missing");
}
}
function removeComponent( type ) {
var previous = null;
if( this.hasComponent( type ) ) {
previous = this._components[type];
delete this._components[type];
previous.setOwner( null );
-- this.size;
var event = new Event( "EntityComponentRemoved", previous );
event.dispatch( this );
//We need to re-pack the internal components into an array so that
//validate dependencies knows what to do with it
var componentArray = [];
var componentTypes = Object.keys(this._components);
for(var comIndex = 0; comIndex < componentTypes.length; comIndex++){
componentArray.push(this._components[componentTypes[comIndex]]);
}
//What we've done here is cause all of the existing components to be re-validated
//now that one of them has been removed
if (!this.validateDependencies.call({_components: []}, componentArray)){
throw new Error( "required component removed from entity- component dependency missing");
}
}
return previous;
}
function setParent( parent ) {
var event;
if( parent !== this.parent ) {
if( this.parent ) {
event = new Event( "ChildEntityRemoved", this );
event.dispatch( this.parent );
}
var previous = this.parent;
this.parent = parent;
event = new Event( "EntityParentChanged",
{ previous: previous, current: parent } );
event.dispatch( this );
if( this.parent ) {
event = new Event( "ChildEntityAdded", this );
event.dispatch( this.parent );
}
}
}
function setSpace( space ) {
if( space !== this.space ) {
var previous = this.space;
this.space = space;
if (!this.space && this.active){
setActive.call(this, false);
}
var event = new Event( "EntitySpaceChanged",
{ previous: previous, current: space } );
event.dispatch( this );
}
}
function setActive( value ) {
var event;
if (this.space){
if( value) {
this.active = true;
event = new Event( "EntityActivationChanged", true );
} else {
this.active = false;
event = new Event( "EntityActivationChanged", false );
}
} else {
if (value){
throw new Error( "Cannot set active to true on an entity that isn't in a space" );
} else {
this.active = false;
event = new Event( "EntityActivationChanged", false);
}
}
event.dispatch( this );
return this;
}
function findComponent( type ) {
if( this._components.hasOwnProperty( type ) ) {
return this._components[type];
}
return null;
}
function hasComponent( args ) {
var i, l;
var componentTypes = Object.keys( this._components );
if( Array.isArray( args ) ) {
if( args.length === 0 ) {
return true;
}
for( i = 0, l = args.length; i < l; ++ i ) {
if( componentTypes.indexOf( args[i] ) < 0 ) {
return false;
}
}
} else if (args){
if( componentTypes.indexOf( args ) < 0 ) {
return false;
}
} else {
return true;
}
return true;
}
//Check a list of components that we're going to add and make sure
//that all components that they are dependent on either already exist in
//this entity or are being added
function validateDependencies(componentsToValidate){
var componentTypes = Object.keys(this._components);
if (Array.isArray(componentsToValidate)){
componentsToValidate.forEach(
function (component){
componentTypes.push(component.type);
}
);
}else{
componentTypes.push(componentsToValidate.type);
componentsToValidate = [componentsToValidate];
}
var component;
for (var comIndex = 0; comIndex < componentsToValidate.length; comIndex++){
component = componentsToValidate[comIndex];
for (var depIndex = 0; depIndex < component.dependsOn.length; depIndex++){
if (componentTypes.indexOf(component.dependsOn[depIndex]) < 0){
return false;
}
}
}
return true;
}
function handleEvent( event ) {
var componentTypes = Object.keys( this._components );
var i, l;
if( this["on" + event.type] ) {
var handler = this["on" + event.type];
try {
handler.call( this, event );
} catch( error ) {
console.log( error );
}
}
for( i = 0, l = componentTypes.length; i < l; ++ i ) {
var componentType = componentTypes[i];
var component = this._components[componentType];
if( component.handleEvent ) {
component.handleEvent.call( component, event );
}
}
}
function onChildEntityAdded( event ) {
var child = event.data;
this._children[child.id] = child;
}
function onChildEntityRemoved( event ) {
var child = event.data;
delete this._children[child.id];
}
Entity.prototype = {
setParent: setParent,
setSpace: setSpace,
setActive: setActive,
findComponent: findComponent,
hasComponent: hasComponent,
addComponent: addComponent,
removeComponent: removeComponent,
validateDependencies: validateDependencies,
handleEvent: handleEvent,
onChildEntityAdded: onChildEntityAdded,
onChildEntityRemoved: onChildEntityRemoved
};
return Entity;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/space',['require','common/guid','core/entity','core/clock'],function( require ) {
function Space( clock ) {
// This will normally be the system simulation clock, but for a UI space
// it might be the realtime clock instead.
this.clock = new Clock( clock.signal ); // This clock controls updates for
// all entities in this space
this.id = guid();
this.size = 0; // The number of entities in this space
this._entities = {}; // Maps entity ID to object
this._nameIndex = {}; // Maps name to entity ID
this._tagIndex = {}; // Maps tag to entity ID
}
var guid = require( "common/guid" );
var Entity = require( "core/entity" );
var Clock = require( "core/clock" );
function add( entity ) {
var i, l;
this._entities[entity.id] = entity;
entity.space = this;
++ this.size;
if( entity.name ) {
if( !this._nameIndex.hasOwnProperty( entity.name ) ) {
this._nameIndex[entity.name] = [];
}
this._nameIndex[entity.name].push( entity.id );
}
if( entity.tags ) {
for( i = 0, l = entity.tags.length; i < l; ++ i ) {
var tag = entity.tags[i];
if( !this._tagIndex.hasOwnProperty( tag ) ) {
this._tagIndex[tag] = [];
}
this._tagIndex[tag].push( entity.id );
}
}
// Recursively add child entities to the space
if( entity._children ) {
for( var childId in entity._children ){
this.add.call( this, entity._children[childId] );
}
}
return this;
}
function remove( entity ) {
var i, l;
if( this._entities.hasOwnProperty( entity.id ) ) {
delete this._entities[entity.id];
entity.space = null;
-- this.size;
if( entity.name ) {
if( this._nameIndex.hasOwnProperty( entity.name ) ) {
delete this._nameIndex[entity.name];
}
}
if( entity.tags ) {
for( i = 0, l = entity.tags.length; i < l; ++ i ) {
var tag = entity.tags[i];
delete this._tagIndex[entity.id];
}
}
// Recursively remove child entities from the space
if( entity._children ) {
for( var childId in entity._children ){
this.remove.call( this, entity._children[childId] );
}
}
} else {
throw new Error("attempted to remove unavailable entity " +
entity.toString());
}
return this;
}
function findNamed( name ) {
if( this._nameIndex.hasOwnProperty( name ) ) {
var id = this._nameIndex[name][0];
return this._entities[id];
}
return null;
}
function findAllNamed( name ) {
var i, l;
if( this._nameIndex.hasOwnProperty( name ) ) {
var ids = this._nameIndex[name];
var result = [];
for( i = 0, l = ids.length; i < l; ++ i ) {
var id = ids[i];
result.push( this._entities[id] );
}
return result;
}
return [];
}
function findTagged( tag ) {
if( this._tagIndex.hasOwnProperty( tag ) ) {
var id = this._tagIndex[tag][0];
return this._entities[id];
}
return null;
}
function findAllTagged( tag ) {
var i, l;
if( this._tagIndex.hasOwnProperty( tag ) ) {
var ids = this._tagIndex[tag];
var result = [];
for( i = 0, l = ids.length; i < l; ++ i ) {
var id = ids[i];
result.push( this._entities[id] );
}
return result;
}
return [];
}
function findWith( type ) {
var i, l;
var entityIds = Object.keys( this._entities );
for( i = 0, l = entityIds.length; i < l; ++ i ) {
var id = entityIds[i];
var entity = this._entities[id];
if( entity.hasComponent( type ) ) {
return entity;
}
}
return null;
}
function findAllWith( type ) {
var i, l;
var result = [];
var entityIds = Object.keys( this._entities );
for( i = 0, l = entityIds.length; i < l; ++ i ) {
var id = entityIds[i];
var entity = this._entities[id];
if( entity.hasComponent( type ) ) {
result.push( entity );
}
}
return result;
}
Space.prototype = {
add: add,
remove: remove,
findNamed: findNamed,
findAllNamed: findAllNamed,
findTagged: findTagged,
findAllTagged: findAllTagged,
findWith: findWith,
findAllWith: findAllWith
};
return Space;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('common/extend',['require'],function ( require ) {
function extend( object, extra ) {
for ( var prop in extra ) {
if ( !object.hasOwnProperty( prop ) && extra.hasOwnProperty( prop ) ) {
object[prop] = extra[prop];
}
}
return object;
}
return extend;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/components/transform',['require','_math','common/extend','base/component'],function( require ) {
var math = require( "_math" );
var extend = require( "common/extend" );
var Component = require( "base/component" );
var Transform = function( position, rotation, scale ) {
Component.call( this, "Transform", null, [] );
// Local position
this._position = position ? new math.Vector3( position ) : new math.Vector3( math.vector3.zero );
this.__defineGetter__( "position", function() {
return this._position;
});
this.__defineSetter__( "position", function( value ) {
this._position.set( value );
this._cachedLocalMatrixIsValid = false;
this._cachedWorldMatrixIsvalid = false;
});
// Local rotation
this._rotation = rotation ? new math.Vector3( rotation ) : new math.Vector3( math.vector3.zero );
this.__defineGetter__( "rotation", function() {
return this._rotation;
});
this.__defineSetter__( "rotation", function( value ) {
this._rotation.set( value );
this._cachedLocalMatrixIsValid = false;
this._cachedWorldMatrixIsvalid = false;
});
this._rotationMatrix = new math.transform.rotate( this._rotation );
this._rotationMatrixIsValid = true;
// Local scale
this._scale = scale ? new math.Vector3( scale ) : new math.Vector3( math.vector3.one );
this.__defineGetter__( "scale", function() {
return this._scale;
});
this.__defineSetter__( "scale", function( value ) {
this._scale.set( value );
this._cachedLocalMatrixIsValid = false;
this._cachedWorldMatrixIsvalid = false;
});
this._cachedLocalMatrix = new math.T();
this._cachedLocalMatrixIsValid = false;
this._cachedWorldMatrix = new math.T();
this._cachedWorldMatrixIsvalid = false;
};
Transform.prototype = new Component();
Transform.prototype.constructor = Transform;
// Return the relative transform
function computeLocalMatrix() {
if( this._cachedLocalMatrixIsValid && !this.position.modified && !this.rotation.modified && !this.scale.modified) {
return this._cachedLocalMatrix;
} else {
math.transform.set(this._cachedLocalMatrix, this.position.buffer, this.rotation.buffer, this.scale.buffer);
this._cachedLocalMatrixIsValid = true;
this.position.modified = false;
this.rotation.modified = false;
this.scale.modified = false;
return this._cachedLocalMatrix;
}
}
// Return the world transform
function computeWorldMatrix() {
if( this.owner && this.owner.parent &&
this.owner.parent.hasComponent( "Transform" ) ) {
var parentTransform = this.owner.parent.findComponent( "Transform" );
math.matrix4.multiply( parentTransform.worldMatrix(), computeLocalMatrix.call( this),
this._cachedWorldMatrix );
} else {
math.matrix4.set( this._cachedWorldMatrix, computeLocalMatrix.call( this) );
}
return this._cachedWorldMatrix;
}
function computeWorldRotation(){
if( this.owner && this.owner.parent &&
this.owner.parent.hasComponent( "Transform" ) ) {
return math.matrix4.multiply(this.owner.parent.findComponent( "Transform").worldRotation(),
math.transform.rotate(this._rotation.buffer));
}else{
return math.transform.rotate(this._rotation.buffer);
}
}
function directionToWorld(direction, result) {
result = result || new math.V3();
var transformedDirection = math.matrix4.multiply(
computeWorldRotation.call(this),
math.transform.translate( direction ));
math.vector3.set(result, transformedDirection[3], transformedDirection[7], transformedDirection[11]);
return result;
}
function directionToLocal(direction, result) {
result = result || new math.V3();
var transformedDirection = math.matrix4.multiply(
math.transform.rotate(this._rotation.buffer),
math.transform.translate( direction ));
math.vector3.set(result, transformedDirection[3], transformedDirection[7], transformedDirection[11]);
return result;
}
var prototype = {
worldMatrix: computeWorldMatrix,
localMatrix: computeLocalMatrix,
directionToLocal: directionToLocal,
directionToWorld: directionToWorld,
worldRotation: computeWorldRotation,
toWorldPoint: undefined,
toLocalPoint: undefined,
lookAt: undefined,
target: undefined,
// Direction constants
forward: new math.Vector3( 0, 0, 1 ),
backward: new math.Vector3( 0, 0, -1 ),
left: new math.Vector3( -1, 0, 0 ),
right: new math.Vector3( 1, 0, 0 ),
up: new math.Vector3( 0, 1, 0 ),
down: new math.Vector3( 0, -1, 0 )
};
extend( Transform.prototype, prototype );
return Transform;
});
define('core/resources/script',['require'],function(require) {
var Script = function(data) {
if (data === undefined){
throw new Error("script body is undefined");
}
/*jslint evil:true */
var g = new Function([], 'var f = ' + data + '; return f.apply( null, Array.prototype.slice.call(arguments) );');
return g;
};
return Script;
});
define('core/loaders/procedural',['require','core/get','core/resources/script','common/get-url-params'],function(require) {
var get = require('core/get');
var Script = require('core/resources/script');
var getURLParams = require('common/get-url-params');
return function(url, onsuccess, onfailure) {
var scriptLocation = url.split( "?" )[0];
var scriptOptions = getURLParams(url);
get([{
url : scriptLocation,
type : Script,
onsuccess : function(instance) {
try {
var data = instance( scriptOptions );
onsuccess( data ) ;
} catch ( e ) {
onfailure( e );
}
},
onfailure : onfailure
}]);
};
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/services/updater',['require','base/service','core/event'],function ( require ) {
var Service = require( "base/service" );
var Event = require( "core/event" );
var Updater = function( scheduler, options ) {
options = options || {};
var schedules = {
"update": {
tags: ["@update", "logic"],
dependsOn: ["physics"]
}
};
Service.call( this, scheduler, schedules );
};
function update() {
var registeredComponents = this._registeredComponents;
// Update all logic components
var component;
var updateEvent = new Event( 'Update', false );
for( var componentType in registeredComponents ) {
for( var entityId in registeredComponents[componentType] ) {
component = registeredComponents[componentType][entityId];
while( component.handleQueuedEvent() ) {}
updateEvent.dispatch( component );
}
}
}
Updater.prototype = new Service();
Updater.prototype.constructor = Updater;
Updater.prototype.update = update;
return Updater;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/components/actor',['require','base/component','common/extend'],function( require ) {
var Component = require( "base/component" );
var extend = require( "common/extend" );
var Actor = function( service, eventMap ) {
Component.call( this, "Logic", service, [] );
eventMap = eventMap || {};
// Set up event handlers
var i, l;
var eventNames = Object.keys( eventMap );
for( i = 0, l = eventNames.length; i < l; ++ i ) {
var eventName = eventNames[i];
this["on" + eventName] = eventMap[eventName];
}
};
Actor.prototype = new Component();
Actor.prototype.constructor = Actor;
function onEntitySpaceChanged( event ) {
var data = event.data;
if( data.previous === null && data.current !== null && this.owner !== null ) {
this.provider.registerComponent( this.owner.id, this );
}
if( data.previous !== null && data.current === null && this.owner !== null ) {
this.provider.unregisterComponent( this.owner.id, this );
}
}
function onComponentOwnerChanged( event ) {
var data = event.data;
if( data.previous === null && this.owner !== null ) {
this.provider.registerComponent( this.owner.id, this );
}
if( this.owner === null && data.previous !== null ) {
this.provider.unregisterComponent( data.previous.id, this );
}
}
function onEntityActivationChanged( event ) {
var active = event.data;
if( active ) {
this.provider.registerComponent( this.owner.id, this );
} else {
this.provider.unregisterComponent( this.owner.id, this );
}
}
var prototype = {
onEntitySpaceChanged: onEntitySpaceChanged,
onComponentOwnerChanged: onComponentOwnerChanged,
onEntityActivationChanged: onEntityActivationChanged
};
extend( Actor.prototype, prototype );
return Actor;
});
define('core/resources/event-map',['require','core/get','core/resources/script'],function( require ) {
var get = require( "core/get" );
var Script = require( "core/resources/script" );
var EventMap = function( data ) {
data = data || {};
var map = {};
var getRequests = [];
var eventNames = Object.keys( data );
for( var eventName in eventNames ) {
if( "string" === typeof data[eventName] ) {
getRequests.push({
type: Script,
url: data[eventName],
onsuccess: function( script ) {
map[eventName] = script;
},
onfailure: function( error ) {
console.log( "error loading script: " + data[eventName] );
throw error;
}
});
} else if( "function" === typeof data[eventName] ) {
map[eventName] = data[eventName];
}
}
get( getRequests );
return map;
};
return EventMap;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/engine',['require','_math','common/multicast-delegate','core/request-animation-frame-loop','core/clock','core/dependency-scheduler','core/function-task','core/timer','core/event','core/get','core/loaders/default','core/loaders/procedural','base/component','base/service','base/extension','core/space','core/entity','core/components/transform','core/resources/script','core/services/updater','core/components/actor','core/resources/event-map'],function ( require ) {
var _Math = require( "_math" );
var MulticastDelegate = require( "common/multicast-delegate" );
var Loop = require( "core/request-animation-frame-loop" );
var Clock = require( "core/clock" );
var Scheduler = require( "core/dependency-scheduler" );
var FunctionTask = require( "core/function-task" );
var Timer = require( "core/timer" );
var Event = require( "core/event" );
var get = require( "core/get" );
var loaders = {
text: require( "core/loaders/default" ),
procedural: require( "core/loaders/procedural" )
};
var base = {
Component: require( "base/component" ),
Service: require( "base/service" ),
Extension: require( "base/extension" )
};
var Space = require( "core/space" );
var Entity = require( "core/entity" );
var core = new base.Extension( "core", {
components: {
"Transform": require( "core/components/transform" )
},
resources: {
"Script": require( "core/resources/script" )
}
});
var logic = new base.Extension( "logic", {
services: {
"updater": {
service: require( "core/services/updater" ),
components: {
"Actor": require( "core/components/actor" )
},
resources: {}
}
},
resources: {
"EventMap": require( "core/resources/event-map" )
}
});
function simulationLoop() {
// Increment frame counter
this.frame += 1;
// Update internal timestamp
var timestamp = Date.now();
this.cachedTimestamp = this.cachedTimestamp || timestamp; // This is a hack for the first frame
var delta = timestamp - this.cachedTimestamp;
this.cachedTimestamp = timestamp;
// Update system clock
this.realClock.update( delta );
// Update scheduler and run all tasks
this._scheduler.update();
while( this._scheduler.hasNext() ) {
this._scheduler.next().run();
}
// Run monitor callbacks
if( this._monitor.size > 0 ) {
this._monitor( this );
}
}
var Engine = function() {
this._loop = new Loop( simulationLoop, this );
this.frame = 0;
this._monitor = new MulticastDelegate();
// System clocks
this.realClock = new Clock();
// The simulation clock receives update signals from the realtime clock
this.simulationClock = new Clock( this.realClock.signal );
this._scheduler = new Scheduler();
// Bind the scheduler to the task constructor
this.FunctionTask = FunctionTask.bind( this, this._scheduler );
this.Timer = Timer;
this.Event = Event;
// Convenient constructors bound to each of the engine timers by default
this.RealTimer = Timer.bind( this, this.realClock.signal );
this.SimulationTimer = Timer.bind( this, this.simulationClock.signal );
// Base prototypes, useful for extending the engine at runtime
this.base = base;
this.Space = Space;
this.RealSpace = Space.bind( null, this.realClock );
this.SimulationSpace = Space.bind( null, this.simulationClock );
this.Entity = Entity;
// Registered extensions go in here; They are also exposed as properties
// on the engine instance
this._extensions = {};
// Register core extension
this.registerExtension( core );
// Register logic extension
this.registerExtension( logic );
};
function suspend() {
this._loop.suspend();
return this;
}
function resume() {
this._loop.resume();
return this;
}
function attach( callback ) {
this._monitor.subscribe( callback );
return this;
}
function detach( callback ) {
this._monitor.unsubscribe( callback );
return this;
}
function isRunning() {
return this._loop.isStarted();
}
function registerExtension( extension, options ) {
if( !extension instanceof base.Extension ) {
throw new Error( "argument is not an extension" );
}
options = options || {};
var i, l;
var j, m;
var extensionInstance = {};
var services = extension.services;
var serviceNames = Object.keys( services );
var serviceName, serviceOptions, service;
var components, componentNames, componentName, ComponentConstructor;
var resources, resourceNames, resourceName, ResourceConstructor;
for( i = 0, l = serviceNames.length; i < l; ++ i ) {
serviceName = serviceNames[i];
serviceOptions = options[serviceName] || {};
if( typeof services[serviceName] === "function" ) {
extensionInstance[serviceName] = new services[serviceName](
this._scheduler, serviceOptions );
} else if( typeof services[serviceName] === "object" ) {
service = new services[serviceName].service( this._scheduler,
serviceOptions );
extensionInstance[serviceName] = service;
components = services[serviceName].components;
componentNames = Object.keys( components );
for( j = 0, m = componentNames.length; j < m; ++ j ) {
componentName = componentNames[j];
ComponentConstructor = components[componentName].bind( null, service );
var componentProperties = Object.keys(components[componentName]);
for (i = 0, l = componentProperties.length; i < l; ++ i) {
ComponentConstructor[componentProperties[i]] = components[componentName][componentProperties[i]];
}
extensionInstance[componentName] = ComponentConstructor;
}
resources = services[serviceName].resources;
resourceNames = Object.keys( resources );
for( j = 0, m = resourceNames.length; j < m; ++ j ) {
resourceName = resourceNames[j];
ResourceConstructor = resources[resourceName].bind( null, service );
var resourceProperties = Object.keys(resources[resourceName]);
for (i = 0, l = resourceProperties.length; i < l; ++ i) {
ResourceConstructor[resourceProperties[i]] = resources[resourceName][resourceProperties[i]];
}
extensionInstance[resourceName] = ResourceConstructor;
}
}
}
components = extension.components;
componentNames = Object.keys( components );
for( i = 0, l = componentNames.length; i < l; ++ i ) {
componentName = componentNames[i];
ComponentConstructor = components[componentName];
extensionInstance[componentName] = ComponentConstructor;
}
resources = extension.resources;
resourceNames = Object.keys( resources );
for( i = 0, l = resourceNames.length; i < l; ++ i ) {
resourceName = resourceNames[i];
ResourceConstructor = resources[resourceName];
extensionInstance[resourceName] = ResourceConstructor;
}
this._extensions[extension.name] = extensionInstance;
if( !this.hasOwnProperty( name ) ) {
this[extension.name] = extensionInstance;
}
return this;
}
function unregisterExtension( extension ) {
throw new Error( "not implemented" );
}
function findExtension( name ) {
if( this._extensions.hasOwnProperty( name ) ) {
return this._extensions[name];
}
return undefined;
}
function hasExtension( name ) {
return this._extensions.hasOwnProperty( name );
}
Engine.prototype = {
isRunning: isRunning,
suspend: suspend,
resume: resume,
attach: attach,
detach: detach,
registerExtension: registerExtension,
unregisterExtension: unregisterExtension,
findExtension: findExtension,
hasExtension: hasExtension,
get: get,
loaders: loaders,
math: _Math
};
return Engine;
});
if ( typeof define !== "function" ) {
var define = require( "amdefine" )( module );
}
define('core/gladius-core',['require','core/engine'],function ( require ) {
var Engine = require( "core/engine" );
return Engine;
});
var Gladius = require( "core/gladius-core" );
return Gladius;
}));
| gladiusjs/gladius | gladius-core.js | JavaScript | bsd-3-clause | 419,352 |
var app = angular.module('MyApp');
app.controller('LoginCtrl', ['$scope', 'Auth', function($scope, Auth) {
$scope.login = function() {
Auth.login({
email: $scope.email,
password: $scope.password
});
};
}]);
| jsonxr/examples-node | fullstack/client/controllers/login.js | JavaScript | bsd-3-clause | 231 |
define([
'jquery',
'underscore',
'backbone',
'text!mockup-patterns-structure-url/templates/paging.xml',
'translate'
], function($, _, Backbone, PagingTemplate, _t) {
'use strict';
var PagingView = Backbone.View.extend({
events: {
'click a.servernext': 'nextResultPage',
'click a.serverprevious': 'previousResultPage',
'click a.serverlast': 'gotoLast',
'click a.page': 'gotoPage',
'click a.serverfirst': 'gotoFirst',
'click a.serverpage': 'gotoPage',
'click .serverhowmany a': 'changeCount'
},
tagName: 'aside',
template: _.template(PagingTemplate),
maxPages: 7,
initialize: function (options) {
this.options = options;
this.app = this.options.app;
this.collection = this.app.collection;
this.collection.on('reset', this.render, this);
this.collection.on('sync', this.render, this);
this.$el.appendTo('#pagination');
},
render: function () {
var data = this.collection.info();
data.pages = this.getPages(data);
var html = this.template($.extend({ _t: _t}, data));
this.$el.html(html);
return this;
},
getPages: function(data) {
var totalPages = data.totalPages;
if (!totalPages) {
return [];
}
var currentPage = data.currentPage;
var left = 1;
var right = totalPages;
if (totalPages > this.maxPages) {
left = Math.max(1, Math.floor(currentPage - (this.maxPages / 2)));
right = Math.min(left + this.maxPages, totalPages);
if ((right - left) < this.maxPages) {
left = left - Math.floor(this.maxPages / 2);
}
}
var pages = [];
for (var i = left; i <= right; i = i + 1) {
pages.push(i);
}
/* add before and after */
if (pages[0] > 1) {
if (pages[0] > 2) {
pages = ['...'].concat(pages);
}
pages = [1].concat(pages);
}
if (pages[pages.length - 1] < (totalPages - 1)) {
if (pages[pages.length - 2] < totalPages - 2) {
pages.push('...');
}
pages.push(totalPages);
}
return pages;
},
nextResultPage: function (e) {
e.preventDefault();
this.collection.requestNextPage();
},
previousResultPage: function (e) {
e.preventDefault();
this.collection.requestPreviousPage();
},
gotoFirst: function (e) {
e.preventDefault();
this.collection.goTo(this.collection.information.firstPage);
},
gotoLast: function (e) {
e.preventDefault();
this.collection.goTo(this.collection.information.totalPages);
},
gotoPage: function (e) {
e.preventDefault();
var page = $(e.target).text();
this.collection.goTo(page);
},
changeCount: function (e) {
e.preventDefault();
var per = $(e.target).text();
this.collection.howManyPer(per);
this.app.setCookieSetting('perPage', per);
}
});
return PagingView;
});
| termitnjak/mockup | mockup/patterns/structure/js/views/paging.js | JavaScript | bsd-3-clause | 3,015 |
'use strict';
togglbutton.render('#navbar:not(.toggl)', { observe: true }, function (elem) {
const description = $('.navbar-tree-name', elem);
const project = '';
const descFunc = function () {
return description.textContent.trim();
};
const link = togglbutton.createTimerLink({
className: 'gingko-toggl-btn',
description: descFunc,
projectName: project,
buttonType: 'minimal'
});
link.style.margin = '9px';
$('.right-block').appendChild(link);
});
| glensc/toggl-button | src/scripts/content/gingkoapp.js | JavaScript | bsd-3-clause | 490 |
/*
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(document) {
'use strict';
// Grab a reference to our auto-binding template
// and give it some initial binding values
// Learn more about auto-binding templates at http://goo.gl/Dx1u2g
var app = document.querySelector('#app');
app.route = 'home';
// setup the game
app.firebase = 'https://firebridge.firebaseio.com/cornhole/games';
app.selectedgame = null;
app.displayInstalledToast = function() {
document.querySelector('#caching-complete').show();
};
app.selected = 0;
app._onPrevClick = function() {
this.entryAnimation = 'slide-from-left-animation';
this.exitAnimation = 'slide-right-animation';
this.selected = this.selected === 0 ? 4 : (this.selected - 1);
};
app._onNextClick = function() {
this.entryAnimation = 'slide-from-right-animation';
this.exitAnimation = 'slide-left-animation';
this.selected = this.selected === 4 ? 0 : (this.selected + 1);
};
app.displayInstalledToast = function() {
document.querySelector('#caching-complete').show();
};
// Listen for template bound event to know when bindings
// have resolved and content has been stamped to the page
app.addEventListener('dom-change', function() {
});
// See https://github.com/Polymer/polymer/issues/1381
window.addEventListener('WebComponentsReady', function() {
// Silly
document.querySelector('#logo').className = 'logo-dropshadow';
});
})(document);
| PlywoodConnected/cornhole-next-polymer | app/scripts/app.js | JavaScript | bsd-3-clause | 1,939 |
version https://git-lfs.github.com/spec/v1
oid sha256:ed0844605e8d8e80ecae78a7693f5d7641e3e11db82586337e037922822f5d0d
size 20416
| yogeshsaroya/new-cdnjs | ajax/libs/ionic/0.9.20-alpha/js/angular/angular-sanitize.js | JavaScript | mit | 130 |
version https://git-lfs.github.com/spec/v1
oid sha256:fe8ee2c2ad37c614076a4f1aec39eca27748de08d481c731bd449e0a64860f65
size 17566
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.1.2/slider/slider-base.js | JavaScript | mit | 130 |
var util = require('../util');
var Node = require('./Node');
/**
* @class Edge
*
* A edge connects two nodes
* @param {Object} properties Object with properties. Must contain
* At least properties from and to.
* Available properties: from (number),
* to (number), label (string, color (string),
* width (number), style (string),
* length (number), title (string)
* @param {Network} network A Network object, used to find and edge to
* nodes.
* @param {Object} constants An object with default values for
* example for the color
*/
function Edge (properties, network, networkConstants) {
if (!network) {
throw "No network provided";
}
var fields = ['edges','physics'];
var constants = util.selectiveBridgeObject(fields,networkConstants);
this.options = constants.edges;
this.physics = constants.physics;
this.options['smoothCurves'] = networkConstants['smoothCurves'];
this.network = network;
// initialize variables
this.id = undefined;
this.fromId = undefined;
this.toId = undefined;
this.title = undefined;
this.widthSelected = this.options.width * this.options.widthSelectionMultiplier;
this.value = undefined;
this.selected = false;
this.hover = false;
this.labelDimensions = {top:0,left:0,width:0,height:0};
this.from = null; // a node
this.to = null; // a node
this.via = null; // a temp node
// we use this to be able to reconnect the edge to a cluster if its node is put into a cluster
// by storing the original information we can revert to the original connection when the cluser is opened.
this.originalFromId = [];
this.originalToId = [];
this.connected = false;
this.widthFixed = false;
this.lengthFixed = false;
this.setProperties(properties);
this.controlNodesEnabled = false;
this.controlNodes = {from:null, to:null, positions:{}};
this.connectedNode = null;
}
/**
* Set or overwrite properties for the edge
* @param {Object} properties an object with properties
* @param {Object} constants and object with default, global properties
*/
Edge.prototype.setProperties = function(properties) {
if (!properties) {
return;
}
var fields = ['style','fontSize','fontFace','fontColor','fontFill','width',
'widthSelectionMultiplier','hoverWidth','arrowScaleFactor','dash','inheritColor'
];
util.selectiveDeepExtend(fields, this.options, properties);
if (properties.from !== undefined) {this.fromId = properties.from;}
if (properties.to !== undefined) {this.toId = properties.to;}
if (properties.id !== undefined) {this.id = properties.id;}
if (properties.label !== undefined) {this.label = properties.label;}
if (properties.title !== undefined) {this.title = properties.title;}
if (properties.value !== undefined) {this.value = properties.value;}
if (properties.length !== undefined) {this.physics.springLength = properties.length;}
if (properties.color !== undefined) {
this.options.inheritColor = false;
if (util.isString(properties.color)) {
this.options.color.color = properties.color;
this.options.color.highlight = properties.color;
}
else {
if (properties.color.color !== undefined) {this.options.color.color = properties.color.color;}
if (properties.color.highlight !== undefined) {this.options.color.highlight = properties.color.highlight;}
if (properties.color.hover !== undefined) {this.options.color.hover = properties.color.hover;}
}
}
// A node is connected when it has a from and to node.
this.connect();
this.widthFixed = this.widthFixed || (properties.width !== undefined);
this.lengthFixed = this.lengthFixed || (properties.length !== undefined);
this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
// set draw method based on style
switch (this.options.style) {
case 'line': this.draw = this._drawLine; break;
case 'arrow': this.draw = this._drawArrow; break;
case 'arrow-center': this.draw = this._drawArrowCenter; break;
case 'dash-line': this.draw = this._drawDashLine; break;
default: this.draw = this._drawLine; break;
}
};
/**
* Connect an edge to its nodes
*/
Edge.prototype.connect = function () {
this.disconnect();
this.from = this.network.nodes[this.fromId] || null;
this.to = this.network.nodes[this.toId] || null;
this.connected = (this.from && this.to);
if (this.connected) {
this.from.attachEdge(this);
this.to.attachEdge(this);
}
else {
if (this.from) {
this.from.detachEdge(this);
}
if (this.to) {
this.to.detachEdge(this);
}
}
};
/**
* Disconnect an edge from its nodes
*/
Edge.prototype.disconnect = function () {
if (this.from) {
this.from.detachEdge(this);
this.from = null;
}
if (this.to) {
this.to.detachEdge(this);
this.to = null;
}
this.connected = false;
};
/**
* get the title of this edge.
* @return {string} title The title of the edge, or undefined when no title
* has been set.
*/
Edge.prototype.getTitle = function() {
return typeof this.title === "function" ? this.title() : this.title;
};
/**
* Retrieve the value of the edge. Can be undefined
* @return {Number} value
*/
Edge.prototype.getValue = function() {
return this.value;
};
/**
* Adjust the value range of the edge. The edge will adjust it's width
* based on its value.
* @param {Number} min
* @param {Number} max
*/
Edge.prototype.setValueRange = function(min, max) {
if (!this.widthFixed && this.value !== undefined) {
var scale = (this.options.widthMax - this.options.widthMin) / (max - min);
this.options.width= (this.value - min) * scale + this.options.widthMin;
this.widthSelected = this.options.width* this.options.widthSelectionMultiplier;
}
};
/**
* Redraw a edge
* Draw this edge in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
*/
Edge.prototype.draw = function(ctx) {
throw "Method draw not initialized in edge";
};
/**
* Check if this object is overlapping with the provided object
* @param {Object} obj an object with parameters left, top
* @return {boolean} True if location is located on the edge
*/
Edge.prototype.isOverlappingWith = function(obj) {
if (this.connected) {
var distMax = 10;
var xFrom = this.from.x;
var yFrom = this.from.y;
var xTo = this.to.x;
var yTo = this.to.y;
var xObj = obj.left;
var yObj = obj.top;
var dist = this._getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
return (dist < distMax);
}
else {
return false
}
};
Edge.prototype._getColor = function() {
var colorObj = this.options.color;
if (this.options.inheritColor == "to") {
colorObj = {
highlight: this.to.options.color.highlight.border,
hover: this.to.options.color.hover.border,
color: this.to.options.color.border
};
}
else if (this.options.inheritColor == "from" || this.options.inheritColor == true) {
colorObj = {
highlight: this.from.options.color.highlight.border,
hover: this.from.options.color.hover.border,
color: this.from.options.color.border
};
}
if (this.selected == true) {return colorObj.highlight;}
else if (this.hover == true) {return colorObj.hover;}
else {return colorObj.color;}
}
/**
* Redraw a edge as a line
* Draw this edge in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
* @private
*/
Edge.prototype._drawLine = function(ctx) {
// set style
ctx.strokeStyle = this._getColor();
ctx.lineWidth = this._getLineWidth();
if (this.from != this.to) {
// draw line
var via = this._line(ctx);
// draw label
var point;
if (this.label) {
if (this.options.smoothCurves.enabled == true && via != null) {
var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
point = {x:midpointX, y:midpointY};
}
else {
point = this._pointOnLine(0.5);
}
this._label(ctx, this.label, point.x, point.y);
}
}
else {
var x, y;
var radius = this.physics.springLength / 4;
var node = this.from;
if (!node.width) {
node.resize(ctx);
}
if (node.width > node.height) {
x = node.x + node.width / 2;
y = node.y - radius;
}
else {
x = node.x + radius;
y = node.y - node.height / 2;
}
this._circle(ctx, x, y, radius);
point = this._pointOnCircle(x, y, radius, 0.5);
this._label(ctx, this.label, point.x, point.y);
}
};
/**
* Get the line width of the edge. Depends on width and whether one of the
* connected nodes is selected.
* @return {Number} width
* @private
*/
Edge.prototype._getLineWidth = function() {
if (this.selected == true) {
return Math.max(Math.min(this.widthSelected, this.options.widthMax), 0.3*this.networkScaleInv);
}
else {
if (this.hover == true) {
return Math.max(Math.min(this.options.hoverWidth, this.options.widthMax), 0.3*this.networkScaleInv);
}
else {
return Math.max(this.options.width, 0.3*this.networkScaleInv);
}
}
};
Edge.prototype._getViaCoordinates = function () {
var xVia = null;
var yVia = null;
var factor = this.options.smoothCurves.roundness;
var type = this.options.smoothCurves.type;
var dx = Math.abs(this.from.x - this.to.x);
var dy = Math.abs(this.from.y - this.to.y);
if (type == 'discrete' || type == 'diagonalCross') {
if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
if (this.from.y > this.to.y) {
if (this.from.x < this.to.x) {
xVia = this.from.x + factor * dy;
yVia = this.from.y - factor * dy;
}
else if (this.from.x > this.to.x) {
xVia = this.from.x - factor * dy;
yVia = this.from.y - factor * dy;
}
}
else if (this.from.y < this.to.y) {
if (this.from.x < this.to.x) {
xVia = this.from.x + factor * dy;
yVia = this.from.y + factor * dy;
}
else if (this.from.x > this.to.x) {
xVia = this.from.x - factor * dy;
yVia = this.from.y + factor * dy;
}
}
if (type == "discrete") {
xVia = dx < factor * dy ? this.from.x : xVia;
}
}
else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
if (this.from.y > this.to.y) {
if (this.from.x < this.to.x) {
xVia = this.from.x + factor * dx;
yVia = this.from.y - factor * dx;
}
else if (this.from.x > this.to.x) {
xVia = this.from.x - factor * dx;
yVia = this.from.y - factor * dx;
}
}
else if (this.from.y < this.to.y) {
if (this.from.x < this.to.x) {
xVia = this.from.x + factor * dx;
yVia = this.from.y + factor * dx;
}
else if (this.from.x > this.to.x) {
xVia = this.from.x - factor * dx;
yVia = this.from.y + factor * dx;
}
}
if (type == "discrete") {
yVia = dy < factor * dx ? this.from.y : yVia;
}
}
}
else if (type == "straightCross") {
if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) { // up - down
xVia = this.from.x;
if (this.from.y < this.to.y) {
yVia = this.to.y - (1-factor) * dy;
}
else {
yVia = this.to.y + (1-factor) * dy;
}
}
else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) { // left - right
if (this.from.x < this.to.x) {
xVia = this.to.x - (1-factor) * dx;
}
else {
xVia = this.to.x + (1-factor) * dx;
}
yVia = this.from.y;
}
}
else if (type == 'horizontal') {
if (this.from.x < this.to.x) {
xVia = this.to.x - (1-factor) * dx;
}
else {
xVia = this.to.x + (1-factor) * dx;
}
yVia = this.from.y;
}
else if (type == 'vertical') {
xVia = this.from.x;
if (this.from.y < this.to.y) {
yVia = this.to.y - (1-factor) * dy;
}
else {
yVia = this.to.y + (1-factor) * dy;
}
}
else { // continuous
if (Math.abs(this.from.x - this.to.x) < Math.abs(this.from.y - this.to.y)) {
if (this.from.y > this.to.y) {
if (this.from.x < this.to.x) {
// console.log(1)
xVia = this.from.x + factor * dy;
yVia = this.from.y - factor * dy;
xVia = this.to.x < xVia ? this.to.x : xVia;
}
else if (this.from.x > this.to.x) {
// console.log(2)
xVia = this.from.x - factor * dy;
yVia = this.from.y - factor * dy;
xVia = this.to.x > xVia ? this.to.x :xVia;
}
}
else if (this.from.y < this.to.y) {
if (this.from.x < this.to.x) {
// console.log(3)
xVia = this.from.x + factor * dy;
yVia = this.from.y + factor * dy;
xVia = this.to.x < xVia ? this.to.x : xVia;
}
else if (this.from.x > this.to.x) {
// console.log(4, this.from.x, this.to.x)
xVia = this.from.x - factor * dy;
yVia = this.from.y + factor * dy;
xVia = this.to.x > xVia ? this.to.x : xVia;
}
}
}
else if (Math.abs(this.from.x - this.to.x) > Math.abs(this.from.y - this.to.y)) {
if (this.from.y > this.to.y) {
if (this.from.x < this.to.x) {
// console.log(5)
xVia = this.from.x + factor * dx;
yVia = this.from.y - factor * dx;
yVia = this.to.y > yVia ? this.to.y : yVia;
}
else if (this.from.x > this.to.x) {
// console.log(6)
xVia = this.from.x - factor * dx;
yVia = this.from.y - factor * dx;
yVia = this.to.y > yVia ? this.to.y : yVia;
}
}
else if (this.from.y < this.to.y) {
if (this.from.x < this.to.x) {
// console.log(7)
xVia = this.from.x + factor * dx;
yVia = this.from.y + factor * dx;
yVia = this.to.y < yVia ? this.to.y : yVia;
}
else if (this.from.x > this.to.x) {
// console.log(8)
xVia = this.from.x - factor * dx;
yVia = this.from.y + factor * dx;
yVia = this.to.y < yVia ? this.to.y : yVia;
}
}
}
}
return {x:xVia, y:yVia};
}
/**
* Draw a line between two nodes
* @param {CanvasRenderingContext2D} ctx
* @private
*/
Edge.prototype._line = function (ctx) {
// draw a straight line
ctx.beginPath();
ctx.moveTo(this.from.x, this.from.y);
if (this.options.smoothCurves.enabled == true) {
if (this.options.smoothCurves.dynamic == false) {
var via = this._getViaCoordinates();
if (via.x == null) {
ctx.lineTo(this.to.x, this.to.y);
ctx.stroke();
return null;
}
else {
// this.via.x = via.x;
// this.via.y = via.y;
ctx.quadraticCurveTo(via.x,via.y,this.to.x, this.to.y);
ctx.stroke();
return via;
}
}
else {
ctx.quadraticCurveTo(this.via.x,this.via.y,this.to.x, this.to.y);
ctx.stroke();
return this.via;
}
}
else {
ctx.lineTo(this.to.x, this.to.y);
ctx.stroke();
return null;
}
};
/**
* Draw a line from a node to itself, a circle
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x
* @param {Number} y
* @param {Number} radius
* @private
*/
Edge.prototype._circle = function (ctx, x, y, radius) {
// draw a circle
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.stroke();
};
/**
* Draw label with white background and with the middle at (x, y)
* @param {CanvasRenderingContext2D} ctx
* @param {String} text
* @param {Number} x
* @param {Number} y
* @private
*/
Edge.prototype._label = function (ctx, text, x, y) {
if (text) {
// TODO: cache the calculated size
ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
this.options.fontSize + "px " + this.options.fontFace;
var lines = String(text).split('\n');
var lineCount = lines.length;
var fontSize = (Number(this.options.fontSize) + 4);
var yLine = y + (1 - lineCount) / 2 * fontSize;
var width = ctx.measureText(lines[0]).width;
for (var i = 1; i < lineCount; i++) {
var lineWidth = ctx.measureText(lines[i]).width;
width = lineWidth > width ? lineWidth : width;
}
var height = this.options.fontSize * lineCount;
var left = x - width / 2;
var top = y - height / 2;
this.labelDimensions = {top:top,left:left,width:width,height:height};
if (this.options.fontFill !== undefined && this.options.fontFill !== null && this.options.fontFill !== "none") {
ctx.fillStyle = this.options.fontFill;
ctx.fillRect(left, top, width, height);
}
// draw text
ctx.fillStyle = this.options.fontColor || "black";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
for (var i = 0; i < lineCount; i++) {
ctx.fillText(lines[i], x, yLine);
yLine += fontSize;
}
}
};
/**
* Redraw a edge as a dashed line
* Draw this edge in the given canvas
* @author David Jordan
* @date 2012-08-08
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
* @private
*/
Edge.prototype._drawDashLine = function(ctx) {
// set style
if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight;}
else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover;}
else {ctx.strokeStyle = this.options.color.color;}
ctx.lineWidth = this._getLineWidth();
var via = null;
// only firefox and chrome support this method, else we use the legacy one.
if (ctx.mozDash !== undefined || ctx.setLineDash !== undefined) {
// configure the dash pattern
var pattern = [0];
if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) {
pattern = [this.options.dash.length,this.options.dash.gap];
}
else {
pattern = [5,5];
}
// set dash settings for chrome or firefox
if (typeof ctx.setLineDash !== 'undefined') { //Chrome
ctx.setLineDash(pattern);
ctx.lineDashOffset = 0;
} else { //Firefox
ctx.mozDash = pattern;
ctx.mozDashOffset = 0;
}
// draw the line
via = this._line(ctx);
// restore the dash settings.
if (typeof ctx.setLineDash !== 'undefined') { //Chrome
ctx.setLineDash([0]);
ctx.lineDashOffset = 0;
} else { //Firefox
ctx.mozDash = [0];
ctx.mozDashOffset = 0;
}
}
else { // unsupporting smooth lines
// draw dashed line
ctx.beginPath();
ctx.lineCap = 'round';
if (this.options.dash.altLength !== undefined) //If an alt dash value has been set add to the array this value
{
ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
[this.options.dash.length,this.options.dash.gap,this.options.dash.altLength,this.options.dash.gap]);
}
else if (this.options.dash.length !== undefined && this.options.dash.gap !== undefined) //If a dash and gap value has been set add to the array this value
{
ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
[this.options.dash.length,this.options.dash.gap]);
}
else //If all else fails draw a line
{
ctx.moveTo(this.from.x, this.from.y);
ctx.lineTo(this.to.x, this.to.y);
}
ctx.stroke();
}
// draw label
if (this.label) {
var point;
if (this.options.smoothCurves.enabled == true && via != null) {
var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
point = {x:midpointX, y:midpointY};
}
else {
point = this._pointOnLine(0.5);
}
this._label(ctx, this.label, point.x, point.y);
}
};
/**
* Get a point on a line
* @param {Number} percentage. Value between 0 (line start) and 1 (line end)
* @return {Object} point
* @private
*/
Edge.prototype._pointOnLine = function (percentage) {
return {
x: (1 - percentage) * this.from.x + percentage * this.to.x,
y: (1 - percentage) * this.from.y + percentage * this.to.y
}
};
/**
* Get a point on a circle
* @param {Number} x
* @param {Number} y
* @param {Number} radius
* @param {Number} percentage. Value between 0 (line start) and 1 (line end)
* @return {Object} point
* @private
*/
Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
var angle = (percentage - 3/8) * 2 * Math.PI;
return {
x: x + radius * Math.cos(angle),
y: y - radius * Math.sin(angle)
}
};
/**
* Redraw a edge as a line with an arrow halfway the line
* Draw this edge in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
* @private
*/
Edge.prototype._drawArrowCenter = function(ctx) {
var point;
// set style
if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
ctx.lineWidth = this._getLineWidth();
if (this.from != this.to) {
// draw line
var via = this._line(ctx);
var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
// draw an arrow halfway the line
if (this.options.smoothCurves.enabled == true && via != null) {
var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
point = {x:midpointX, y:midpointY};
}
else {
point = this._pointOnLine(0.5);
}
ctx.arrow(point.x, point.y, angle, length);
ctx.fill();
ctx.stroke();
// draw label
if (this.label) {
this._label(ctx, this.label, point.x, point.y);
}
}
else {
// draw circle
var x, y;
var radius = 0.25 * Math.max(100,this.physics.springLength);
var node = this.from;
if (!node.width) {
node.resize(ctx);
}
if (node.width > node.height) {
x = node.x + node.width * 0.5;
y = node.y - radius;
}
else {
x = node.x + radius;
y = node.y - node.height * 0.5;
}
this._circle(ctx, x, y, radius);
// draw all arrows
var angle = 0.2 * Math.PI;
var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
point = this._pointOnCircle(x, y, radius, 0.5);
ctx.arrow(point.x, point.y, angle, length);
ctx.fill();
ctx.stroke();
// draw label
if (this.label) {
point = this._pointOnCircle(x, y, radius, 0.5);
this._label(ctx, this.label, point.x, point.y);
}
}
};
/**
* Redraw a edge as a line with an arrow
* Draw this edge in the given canvas
* The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
* @param {CanvasRenderingContext2D} ctx
* @private
*/
Edge.prototype._drawArrow = function(ctx) {
// set style
if (this.selected == true) {ctx.strokeStyle = this.options.color.highlight; ctx.fillStyle = this.options.color.highlight;}
else if (this.hover == true) {ctx.strokeStyle = this.options.color.hover; ctx.fillStyle = this.options.color.hover;}
else {ctx.strokeStyle = this.options.color.color; ctx.fillStyle = this.options.color.color;}
ctx.lineWidth = this._getLineWidth();
var angle, length;
//draw a line
if (this.from != this.to) {
angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
var dx = (this.to.x - this.from.x);
var dy = (this.to.y - this.from.y);
var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
var via;
if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true ) {
via = this.via;
}
else if (this.options.smoothCurves.enabled == true) {
via = this._getViaCoordinates();
}
if (this.options.smoothCurves.enabled == true && via.x != null) {
angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
dx = (this.to.x - via.x);
dy = (this.to.y - via.y);
edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
}
var toBorderDist = this.to.distanceToBorder(ctx, angle);
var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
var xTo,yTo;
if (this.options.smoothCurves.enabled == true && via.x != null) {
xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
}
else {
xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
}
ctx.beginPath();
ctx.moveTo(xFrom,yFrom);
if (this.options.smoothCurves.enabled == true && via.x != null) {
ctx.quadraticCurveTo(via.x,via.y,xTo, yTo);
}
else {
ctx.lineTo(xTo, yTo);
}
ctx.stroke();
// draw arrow at the end of the line
length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
ctx.arrow(xTo, yTo, angle, length);
ctx.fill();
ctx.stroke();
// draw label
if (this.label) {
var point;
if (this.options.smoothCurves.enabled == true && via != null) {
var midpointX = 0.5*(0.5*(this.from.x + via.x) + 0.5*(this.to.x + via.x));
var midpointY = 0.5*(0.5*(this.from.y + via.y) + 0.5*(this.to.y + via.y));
point = {x:midpointX, y:midpointY};
}
else {
point = this._pointOnLine(0.5);
}
this._label(ctx, this.label, point.x, point.y);
}
}
else {
// draw circle
var node = this.from;
var x, y, arrow;
var radius = 0.25 * Math.max(100,this.physics.springLength);
if (!node.width) {
node.resize(ctx);
}
if (node.width > node.height) {
x = node.x + node.width * 0.5;
y = node.y - radius;
arrow = {
x: x,
y: node.y,
angle: 0.9 * Math.PI
};
}
else {
x = node.x + radius;
y = node.y - node.height * 0.5;
arrow = {
x: node.x,
y: y,
angle: 0.6 * Math.PI
};
}
ctx.beginPath();
// TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
ctx.stroke();
// draw all arrows
var length = (10 + 5 * this.options.width) * this.options.arrowScaleFactor;
ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
ctx.fill();
ctx.stroke();
// draw label
if (this.label) {
point = this._pointOnCircle(x, y, radius, 0.5);
this._label(ctx, this.label, point.x, point.y);
}
}
};
/**
* Calculate the distance between a point (x3,y3) and a line segment from
* (x1,y1) to (x2,y2).
* http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} x3
* @param {number} y3
* @private
*/
Edge.prototype._getDistanceToEdge = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
var returnValue = 0;
if (this.from != this.to) {
if (this.options.smoothCurves.enabled == true) {
var xVia, yVia;
if (this.options.smoothCurves.enabled == true && this.options.smoothCurves.dynamic == true) {
xVia = this.via.x;
yVia = this.via.y;
}
else {
var via = this._getViaCoordinates();
xVia = via.x;
yVia = via.y;
}
var minDistance = 1e9;
var distance;
var i,t,x,y, lastX, lastY;
for (i = 0; i < 10; i++) {
t = 0.1*i;
x = Math.pow(1-t,2)*x1 + (2*t*(1 - t))*xVia + Math.pow(t,2)*x2;
y = Math.pow(1-t,2)*y1 + (2*t*(1 - t))*yVia + Math.pow(t,2)*y2;
if (i > 0) {
distance = this._getDistanceToLine(lastX,lastY,x,y, x3,y3);
minDistance = distance < minDistance ? distance : minDistance;
}
lastX = x; lastY = y;
}
returnValue = minDistance;
}
else {
returnValue = this._getDistanceToLine(x1,y1,x2,y2,x3,y3);
}
}
else {
var x, y, dx, dy;
var radius = 0.25 * this.physics.springLength;
var node = this.from;
if (node.width > node.height) {
x = node.x + 0.5 * node.width;
y = node.y - radius;
}
else {
x = node.x + radius;
y = node.y - 0.5 * node.height;
}
dx = x - x3;
dy = y - y3;
returnValue = Math.abs(Math.sqrt(dx*dx + dy*dy) - radius);
}
if (this.labelDimensions.left < x3 &&
this.labelDimensions.left + this.labelDimensions.width > x3 &&
this.labelDimensions.top < y3 &&
this.labelDimensions.top + this.labelDimensions.height > y3) {
return 0;
}
else {
return returnValue;
}
};
Edge.prototype._getDistanceToLine = function(x1,y1,x2,y2,x3,y3) {
var px = x2-x1,
py = y2-y1,
something = px*px + py*py,
u = ((x3 - x1) * px + (y3 - y1) * py) / something;
if (u > 1) {
u = 1;
}
else if (u < 0) {
u = 0;
}
var x = x1 + u * px,
y = y1 + u * py,
dx = x - x3,
dy = y - y3;
//# Note: If the actual distance does not matter,
//# if you only want to compare what this function
//# returns to other results of this function, you
//# can just return the squared distance instead
//# (i.e. remove the sqrt) to gain a little performance
return Math.sqrt(dx*dx + dy*dy);
}
/**
* This allows the zoom level of the network to influence the rendering
*
* @param scale
*/
Edge.prototype.setScale = function(scale) {
this.networkScaleInv = 1.0/scale;
};
Edge.prototype.select = function() {
this.selected = true;
};
Edge.prototype.unselect = function() {
this.selected = false;
};
Edge.prototype.positionBezierNode = function() {
if (this.via !== null && this.from !== null && this.to !== null) {
this.via.x = 0.5 * (this.from.x + this.to.x);
this.via.y = 0.5 * (this.from.y + this.to.y);
}
};
/**
* This function draws the control nodes for the manipulator. In order to enable this, only set the this.controlNodesEnabled to true.
* @param ctx
*/
Edge.prototype._drawControlNodes = function(ctx) {
if (this.controlNodesEnabled == true) {
if (this.controlNodes.from === null && this.controlNodes.to === null) {
var nodeIdFrom = "edgeIdFrom:".concat(this.id);
var nodeIdTo = "edgeIdTo:".concat(this.id);
var constants = {
nodes:{group:'', radius:8},
physics:{damping:0},
clustering: {maxNodeSizeIncrements: 0 ,nodeScaling: {width:0, height: 0, radius:0}}
};
this.controlNodes.from = new Node(
{id:nodeIdFrom,
shape:'dot',
color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
},{},{},constants);
this.controlNodes.to = new Node(
{id:nodeIdTo,
shape:'dot',
color:{background:'#ff4e00', border:'#3c3c3c', highlight: {background:'#07f968'}}
},{},{},constants);
}
if (this.controlNodes.from.selected == false && this.controlNodes.to.selected == false) {
this.controlNodes.positions = this.getControlNodePositions(ctx);
this.controlNodes.from.x = this.controlNodes.positions.from.x;
this.controlNodes.from.y = this.controlNodes.positions.from.y;
this.controlNodes.to.x = this.controlNodes.positions.to.x;
this.controlNodes.to.y = this.controlNodes.positions.to.y;
}
this.controlNodes.from.draw(ctx);
this.controlNodes.to.draw(ctx);
}
else {
this.controlNodes = {from:null, to:null, positions:{}};
}
};
/**
* Enable control nodes.
* @private
*/
Edge.prototype._enableControlNodes = function() {
this.controlNodesEnabled = true;
};
/**
* disable control nodes
* @private
*/
Edge.prototype._disableControlNodes = function() {
this.controlNodesEnabled = false;
};
/**
* This checks if one of the control nodes is selected and if so, returns the control node object. Else it returns null.
* @param x
* @param y
* @returns {null}
* @private
*/
Edge.prototype._getSelectedControlNode = function(x,y) {
var positions = this.controlNodes.positions;
var fromDistance = Math.sqrt(Math.pow(x - positions.from.x,2) + Math.pow(y - positions.from.y,2));
var toDistance = Math.sqrt(Math.pow(x - positions.to.x ,2) + Math.pow(y - positions.to.y ,2));
if (fromDistance < 15) {
this.connectedNode = this.from;
this.from = this.controlNodes.from;
return this.controlNodes.from;
}
else if (toDistance < 15) {
this.connectedNode = this.to;
this.to = this.controlNodes.to;
return this.controlNodes.to;
}
else {
return null;
}
};
/**
* this resets the control nodes to their original position.
* @private
*/
Edge.prototype._restoreControlNodes = function() {
if (this.controlNodes.from.selected == true) {
this.from = this.connectedNode;
this.connectedNode = null;
this.controlNodes.from.unselect();
}
if (this.controlNodes.to.selected == true) {
this.to = this.connectedNode;
this.connectedNode = null;
this.controlNodes.to.unselect();
}
};
/**
* this calculates the position of the control nodes on the edges of the parent nodes.
*
* @param ctx
* @returns {{from: {x: number, y: number}, to: {x: *, y: *}}}
*/
Edge.prototype.getControlNodePositions = function(ctx) {
var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
var dx = (this.to.x - this.from.x);
var dy = (this.to.y - this.from.y);
var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
var fromBorderDist = this.from.distanceToBorder(ctx, angle + Math.PI);
var fromBorderPoint = (edgeSegmentLength - fromBorderDist) / edgeSegmentLength;
var xFrom = (fromBorderPoint) * this.from.x + (1 - fromBorderPoint) * this.to.x;
var yFrom = (fromBorderPoint) * this.from.y + (1 - fromBorderPoint) * this.to.y;
var via;
if (this.options.smoothCurves.dynamic == true && this.options.smoothCurves.enabled == true) {
via = this.via;
}
else if (this.options.smoothCurves.enabled == true) {
via = this._getViaCoordinates();
}
if (this.options.smoothCurves.enabled == true && via.x != null) {
angle = Math.atan2((this.to.y - via.y), (this.to.x - via.x));
dx = (this.to.x - via.x);
dy = (this.to.y - via.y);
edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
}
var toBorderDist = this.to.distanceToBorder(ctx, angle);
var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
var xTo,yTo;
if (this.options.smoothCurves.enabled == true && via.x != null) {
xTo = (1 - toBorderPoint) * via.x + toBorderPoint * this.to.x;
yTo = (1 - toBorderPoint) * via.y + toBorderPoint * this.to.y;
}
else {
xTo = (1 - toBorderPoint) * this.from.x + toBorderPoint * this.to.x;
yTo = (1 - toBorderPoint) * this.from.y + toBorderPoint * this.to.y;
}
return {from:{x:xFrom,y:yFrom},to:{x:xTo,y:yTo}};
};
module.exports = Edge; | sekys/ivda | web/libs/vis/lib/network/Edge.js | JavaScript | mit | 36,449 |
// update license year and version
var fs = require('fs')
module.exports = function() {
var version = require('./package.json').version
var license = fs.readFileSync('LICENSE', 'utf-8')
.replace(/\(c\) ([0-9]+)/, '(c) ' + (new Date).getFullYear())
.replace(/SYNAPTIC \(v(.*)\)/, 'SYNAPTIC (v' + version + ')')
fs.writeFileSync('LICENSE', license)
return license
}
| DDOS-Attacks/dino-bot-3000 | node_modules/synaptic/license.js | JavaScript | mit | 376 |
// show that no match events happen while paused.
var tap = require("tap")
, child_process = require("child_process")
// just some gnarly pattern with lots of matches
, pattern = "test/a/!(symlink)/**"
, bashResults = require("./bash-results.json")
, patterns = Object.keys(bashResults)
, glob = require("../")
, Glob = glob.Glob
, path = require("path")
// run from the root of the project
// this is usually where you're at anyway, but be sure.
process.chdir(path.resolve(__dirname, ".."))
function alphasort (a, b) {
a = a.toLowerCase()
b = b.toLowerCase()
return a > b ? 1 : a < b ? -1 : 0
}
function cleanResults (m) {
// normalize discrepancies in ordering, duplication,
// and ending slashes.
return m.map(function (m) {
return m.replace(/\/+/g, "/").replace(/\/$/, "")
}).sort(alphasort).reduce(function (set, f) {
if (f !== set[set.length - 1]) set.push(f)
return set
}, []).sort(alphasort).map(function (f) {
// de-windows
return (process.platform !== 'win32') ? f
| wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/should/node_modules/gulp-uglify/node_modules/tape/node_modules/glob/test/pause-resume.js | JavaScript | mit | 1,024 |
'use strict';
define([
'jquery',
'three',
'pubsub',
'underscore',
'motifExplorer',
'explorer'
], function(
jQuery,
THREE,
PubSub,
_,
MotifExplorer,
Explorer
) {
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
function CrystalMouseEvents( client, _camera, domElement, state, dollEditor, atomCustomizer, keyboard ) {
var _this =this ;
this.camera = _camera;
this.container = domElement;
this.motifEditorAtms = [] ;
this.client = client ;
this.state = state ;
this.dollEditor = dollEditor;
this.atomCustomizer = atomCustomizer;
this.offset = new THREE.Vector3();
this.coloredAtomsExist = false;
this.keyboard = keyboard;
this.coloredPlanesExist = false;
var mMoove = this.onDocumentMouseMove.bind(this) ;
document.getElementById(this.container).addEventListener("mousemove", mMoove, false);
var mDown = this.onDocumentMouseDown.bind(this) ;
document.getElementById(this.container).addEventListener("mousedown", mDown, false);
var mUp = this.onDocumentMouseUp.bind(this) ;
document.getElementById(this.container).addEventListener("mouseup" , mUp, false);
};
CrystalMouseEvents.prototype.onDocumentMouseDown = function(event){
event.preventDefault();
var _this = this;
if(this.state === 'default'){
mouse.x = ( event.clientX / $('#'+this.container).width() ) * 2 - 1;
mouse.y = - ( event.clientY / $('#'+this.container).height() ) * 2 + 1;
}
else if(_this.state === 'motifScreen'){
mouse.x = ( event.clientX / $('#'+this.container).width() ) * 2 - 3;
mouse.y = - ( event.clientY / $('#'+this.container).height() ) * 2 + 1;
}
raycaster.setFromCamera( mouse, this.camera );
var crystalobjsIntersects = raycaster.intersectObjects( this.getCrystalObjects() );
if ( crystalobjsIntersects.length > 0 ) {
if(crystalobjsIntersects[0].object.parent.name === 'atom'){
var obj = crystalobjsIntersects[0].object ;
var filteredAtom = _.findWhere(_this.client.actualAtoms, {uniqueID : obj.parent.uniqueID});
if(filteredAtom === undefined){
filteredAtom = _.findWhere(_this.client.cachedAtoms, {uniqueID : obj.parent.uniqueID});
}
if(filteredAtom !== undefined){
this.atomCustomizer.atomJustClicekd(filteredAtom, this.keyboard.pressed("ctrl"));
}
}
}
};
CrystalMouseEvents.prototype.onDocumentMouseUp = function(event){
};
CrystalMouseEvents.prototype.onDocumentMouseMove = function(event){
var _this = this;
event.preventDefault();
if(_this.state === 'default'){
mouse.x = ( event.clientX / $('#'+_this.container).width() ) * 2 - 1;
mouse.y = - ( event.clientY / $('#'+_this.container).height() ) * 2 + 1;
}
else if(_this.state === 'motifScreen'){
mouse.x = ( event.clientX / $('#'+_this.container).width() ) * 2 - 3;
mouse.y = - ( event.clientY / $('#'+_this.container).height() ) * 2 + 1;
}
raycaster.setFromCamera( mouse, this.camera );
var crystalPlanesIntersects = raycaster.intersectObjects( this.getCrystalPlanes() );
if ( crystalPlanesIntersects.length > 0 ) {
this.coloredPlanesExist = true;
if(crystalPlanesIntersects[0].object.name === 'plane'){
for (var i = this.client.millerPlanes.length - 1; i >= 0; i--) {
this.client.millerPlanes[i].plane.setColor();
};
for (var i = this.client.tempPlanes.length - 1; i >= 0; i--) {
this.client.tempPlanes[i].plane.setColor();
};
crystalPlanesIntersects[0].object.material.color.setHex( 0xCC2EFA );
document.getElementById(this.container).style.cursor = 'pointer';
}
}
else{
if(this.coloredPlanesExist === true){
for (var i = this.client.millerPlanes.length - 1; i >= 0; i--) {
this.client.millerPlanes[i].plane.setColor();
};
for (var i = this.client.tempPlanes.length - 1; i >= 0; i--) {
this.client.tempPlanes[i].plane.setColor();
};
this.coloredPlanesExist = false;
}
}
var crystalobjsIntersects = raycaster.intersectObjects( this.getCrystalObjects() );
if ( crystalobjsIntersects.length > 0 ) {
for (var i = this.client.actualAtoms.length - 1; i >= 0; i--) {
this.client.actualAtoms[i].setColorMaterial();
this.client.actualAtoms[i].object3d.visible = this.client.actualAtoms[i].visibility;
};
this.dollEditor.setAtomUnderDoll(crystalobjsIntersects[0].object.parent);
var obj = crystalobjsIntersects[0].object ;
//console.log(obj.parent.uniqueID);
var filteredAtom = _.findWhere(_this.client.actualAtoms, {uniqueID : obj.parent.uniqueID});
if(filteredAtom === undefined){
filteredAtom = _.findWhere(this.client.cachedAtoms, {uniqueID : obj.parent.uniqueID});
if(filteredAtom === undefined){
return;
}
}
if(filteredAtom.object3d.visible === false){
filteredAtom.object3d.visible = true ;
}
filteredAtom.setColorMaterial(0xCC2EFA, true);
this.coloredAtomsExist = true;
document.getElementById(this.container).style.cursor = 'pointer';
}
else{
this.dollEditor.setAtomUnderDoll(undefined);
if(this.coloredAtomsExist === true){
for (var i = this.client.actualAtoms.length - 1; i >= 0; i--) {
this.client.actualAtoms[i].setColorMaterial();
this.client.actualAtoms[i].object3d.visible = this.client.actualAtoms[i].visibility;
};
for (var i = this.client.cachedAtoms.length - 1; i >= 0; i--) {
this.client.cachedAtoms[i].setColorMaterial();
this.client.cachedAtoms[i].object3d.visible = this.client.cachedAtoms[i].visibility;
};
this.coloredAtomsExist = false;
document.getElementById(this.container).style.cursor = 'default';
}
}
}
CrystalMouseEvents.prototype.getCrystalPlanesTODELETE = function() {
var _this = this;
var crystalPlanes = [] ;
Explorer.getInstance().object3d.traverse (function (object) {
if (object.name === 'face' && object.visible === true){
crystalPlanes.push(object);
}
});
return crystalPlanes;
};
CrystalMouseEvents.prototype.getCrystalPlanes = function() {
var _this = this;
var crystalPlanes = [] ;
Explorer.getInstance().object3d.traverse (function (object) {
if (object.name === 'plane' && object.visible === true){
crystalPlanes.push(object);
}
});
return crystalPlanes;
};
CrystalMouseEvents.prototype.getCrystalObjects = function() {
var _this = this;
var crystalObjs = [] ;
Explorer.getInstance().object3d.traverse (function (object) {
if (
(object.name === 'plane' ) ||
(object.name === 'atom' && object.latticeIndex !== '-') ||
( object.name === 'atom' &&
object.latticeIndex === '-' &&
object.visible === true )
||
object.name === 'miller'
) {
for (var i = 0; i < object.children.length; i++) {
crystalObjs.push(object.children[i]);
};
}
});
return crystalObjs;
};
return CrystalMouseEvents;
});
| gvcm/CWAPP | scripts/crystalMouseEvents.js | JavaScript | mit | 7,499 |
'use strict';
var resolve = require('path').resolve
, isNotFoundError = require('../../module/is-module-not-found-error')
, pg = resolve(__dirname, '../__playground/module/require-first-in-tree');
module.exports = function (t, a) {
var path = pg + '/first/dir'
, m = require(path + '/module');
a(t('module', pg + '/first/dir'), m, "First in tree");
m = require(pg + '/mid/dir/module');
a(t('module', pg + '/mid/dir/dir2/dir3'), m, "Somewhere in a middle");
m = require(pg + '/top/module');
a(t('module', pg + '/top/one/two', pg + '/top'), m, "Last in tree");
try {
t('module', path = pg + '/beyond/one/dir/dir2', pg + '/beyond/one');
a.never();
} catch (e) {
a(isNotFoundError(e, 'module'), true, "Beyond");
}
};
| medikoo/node-ext | test/module/require-first-in-tree.js | JavaScript | mit | 750 |
var gulp = require('gulp');
var paths = require('../paths');
var browserSync = require('browser-sync');
function reportChange(event){
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
}
gulp.task('watch', function() {
gulp.watch(paths.source, ['build-system', browserSync.reload]).on('change', reportChange);
gulp.watch(paths.html, ['build-html', browserSync.reload]).on('change', reportChange);
gulp.watch(paths.style, browserSync.reload).on('change', reportChange);
});
| behzad88/aurelia-appInsights | Aurelia-AppInsights/build/tasks/watch.js | JavaScript | mit | 521 |
/*!
* THREE.Extras.Shaders contains extra Fx shaders like godrays
*
* @author Thibaut 'BKcore' Despoulain <http://bkcore.com>
*
*/
THREE = THREE || {};
THREE.Extras = THREE.Extras || {};
THREE.Extras.Shaders = {
// Volumetric Light Approximation (Godrays)
Godrays: {
uniforms: {
tDiffuse: {type: "t", value:0, texture:null},
fX: {type: "f", value: 0.5},
fY: {type: "f", value: 0.5},
fExposure: {type: "f", value: 0.6},
fDecay: {type: "f", value: 0.93},
fDensity: {type: "f", value: 0.96},
fWeight: {type: "f", value: 0.4},
fClamp: {type: "f", value: 1.0}
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = vec2( uv.x, 1.0 - uv.y );",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"varying vec2 vUv;",
"uniform sampler2D tDiffuse;",
"uniform float fX;",
"uniform float fY;",
"uniform float fExposure;",
"uniform float fDecay;",
"uniform float fDensity;",
"uniform float fWeight;",
"uniform float fClamp;",
"const int iSamples = 20;",
"void main()",
"{",
"vec2 deltaTextCoord = vec2(vUv - vec2(fX,fY));",
"deltaTextCoord *= 1.0 / float(iSamples) * fDensity;",
"vec2 coord = vUv;",
"float illuminationDecay = 1.0;",
"vec4 FragColor = vec4(0.0);",
"for(int i=0; i < iSamples ; i++)",
"{",
"coord -= deltaTextCoord;",
"vec4 texel = texture2D(tDiffuse, coord);",
"texel *= illuminationDecay * fWeight;",
"FragColor += texel;",
"illuminationDecay *= fDecay;",
"}",
"FragColor *= fExposure;",
"FragColor = clamp(FragColor, 0.0, fClamp);",
"gl_FragColor = FragColor;",
"}"
].join("\n")
},
// Coeff'd additive buffer blending
Additive: {
uniforms: {
tDiffuse: { type: "t", value: 0, texture: null },
tAdd: { type: "t", value: 1, texture: null },
fCoeff: { type: "f", value: 1.0 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
"vUv = vec2( uv.x, 1.0 - uv.y );",
"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join("\n"),
fragmentShader: [
"uniform sampler2D tDiffuse;",
"uniform sampler2D tAdd;",
"uniform float fCoeff;",
"varying vec2 vUv;",
"void main() {",
"vec4 texel = texture2D( tDiffuse, vUv );",
"vec4 add = texture2D( tAdd, vUv );",
"gl_FragColor = texel + add * fCoeff;",
"}"
].join("\n")
}
}; | modulexcite/tquery | plugins/glow/examples/tmp/js/extras/Shaders.js | JavaScript | mit | 2,485 |
export default function getCurrentUserId(state) {
return state.getIn(['user', 'account', 'id']);
}
| outoftime/learnpad | src/selectors/getCurrentUserId.js | JavaScript | mit | 101 |
const DrawCard = require('../../drawcard.js');
class Yoren extends DrawCard {
setupCardAbilities() {
this.reaction({
when: {
onCardEntersPlay: event => event.card === this && event.playingType === 'marshal'
},
target: {
cardCondition: card => card.location === 'discard pile' && card.getType() === 'character' && card.owner !== this.controller && card.getPrintedCost() <= 3 && this.controller.canPutIntoPlay(card)
},
handler: context => {
this.controller.putIntoPlay(context.target);
this.game.addMessage('{0} uses {1} to put {2} into play from {3}\'s discard pile under their control', this.controller, this, context.target, context.target.owner);
}
});
}
}
Yoren.code = '01129';
module.exports = Yoren;
| cryogen/throneteki | server/game/cards/01-Core/Yoren.js | JavaScript | mit | 868 |
define({
"add": "Klikkige uue järjehoidja lisamiseks",
"title": "Pealkiri",
"placeholderBookmarkName": "Järjehoidja nimi",
"ok": "OK",
"cancel": "Tühista",
"warning": "Viige muutmine lõpule!",
"edit": "Muuda järjehoidjat",
"errorNameExist": "Järjehoidja on olemas!",
"errorNameNull": "Vigane järjehoidja nimi!",
"addBookmark": "Loo uus järjehoidja",
"thumbnail": "Pisipilt",
"thumbnailHint": "Uuendamiseks klõpsake pilti"
}); | cmccullough2/cmv-wab-widgets | wab/2.3/widgets/Bookmark/setting/nls/et/strings.js | JavaScript | mit | 458 |
import webdriver from 'selenium-webdriver';
import { expect } from 'chai';
import electronPath from 'electron-prebuilt';
import homeStyles from '../app/components/Home.module.css';
import counterStyles from '../app/components/Counter.module.css';
describe('main window', function spec() {
before((done) => {
this.timeout(5000);
this.driver = new webdriver.Builder()
.usingServer('http://localhost:9515')
.withCapabilities({
chromeOptions: {
binary: electronPath,
args: [ 'app=.' ]
}
})
.forBrowser('electron')
.build();
done();
});
after((done) => {
this.timeout(10000);
this.driver.quit().then(done);
});
const findCounter = () => {
return this.driver.findElement(webdriver.By.className(counterStyles.counter));
};
const findButtons = () => {
return this.driver.findElements(webdriver.By.className(counterStyles.btn));
};
it('should open window', (done) => {
async () => {
const title = await this.driver.getTitle();
expect(title).to.equal('Hello Electron React!');
done();
}().catch(done);
});
it('should to Counter with click "to Counter" link', (done) => {
async () => {
const link = await this.driver.findElement(webdriver.By.css(`.${homeStyles.container} > a`));
link.click();
const counter = await findCounter();
expect(await counter.getText()).to.equal('0');
done();
}().catch(done);
});
it('should display updated count after increment button click', (done) => {
async () => {
const buttons = await findButtons();
buttons[0].click();
const counter = await findCounter();
expect(await counter.getText()).to.equal('1');
done();
}().catch(done);
});
it('should display updated count after descrement button click', (done) => {
async () => {
const buttons = await findButtons();
const counter = await findCounter();
buttons[1].click(); // -
expect(await counter.getText()).to.equal('0');
done();
}().catch(done);
});
it('shouldnt change if even and if odd button clicked', (done) => {
async () => {
const buttons = await findButtons();
const counter = await findCounter();
buttons[2].click(); // odd
expect(await counter.getText()).to.equal('0');
done();
}().catch(done);
});
it('should change if odd and if odd button clicked', (done) => {
async () => {
const buttons = await findButtons();
const counter = await findCounter();
buttons[0].click(); // +
buttons[2].click(); // odd
expect(await counter.getText()).to.equal('2');
done();
}().catch(done);
});
it('should change if async button clicked and a second later', (done) => {
async () => {
const buttons = await findButtons();
const counter = await findCounter();
buttons[3].click(); // async
expect(await counter.getText()).to.equal('2');
await this.driver.wait(() =>
counter.getText().then(text => text === '3' )
, 1000, 'count not as expected');
done();
}().catch(done);
});
it('should back to home if back button clicked', (done) => {
async () => {
const link = await this.driver.findElement(webdriver.By.css(`.${counterStyles.backButton} > a`));
link.click();
await this.driver.findElement(webdriver.By.className(homeStyles.container));
done();
}().catch(done);
});
});
| foysalit/runkeeper-desktop | test/e2e.js | JavaScript | mit | 3,520 |
/// <reference path="../../observable.ts" />
(function () {
var o;
o = o.findIndex(function (x) { return true; });
o = o.findIndex(function (x) { return true; }, {});
});
//# sourceMappingURL=findindex.js.map | cyberpuffin/remanddel | node_modules/lite-server/node_modules/browser-sync/node_modules/rx/ts/core/linq/observable/findindex.js | JavaScript | mit | 220 |
/*! jQuery UI - v1.10.4 - 2014-04-20
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.ka={closeText:"დახურვა",prevText:"< წინა",nextText:"შემდეგი >",currentText:"დღეს",monthNames:["იანვარი","თებერვალი","მარტი","აპრილი","მაისი","ივნისი","ივლისი","აგვისტო","სექტემბერი","ოქტომბერი","ნოემბერი","დეკემბერი"],monthNamesShort:["იან","თებ","მარ","აპრ","მაი","ივნ","ივლ","აგვ","სექ","ოქტ","ნოე","დეკ"],dayNames:["კვირა","ორშაბათი","სამშაბათი","ოთხშაბათი","ხუთშაბათი","პარასკევი","შაბათი"],dayNamesShort:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],dayNamesMin:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],weekHeader:"კვირა",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.ka)}); | snipertomcat/MusiczarconiaBundle | web/bundles/stcbase/js/jquery/development-bundle/ui/minified/i18n/jquery.ui.datepicker-ka.min.js | JavaScript | mit | 1,334 |
steal('can/util', 'can/observe', function (can) {
var define = can.define = {};
var getPropDefineBehavior = function(behavior, attr, define) {
var prop, defaultProp;
if(define) {
prop = define[attr];
defaultProp = define['*'];
if(prop && prop[behavior] !== undefined) {
return prop[behavior];
}
else if(defaultProp && defaultProp[behavior] !== undefined) {
return defaultProp[behavior];
}
}
};
// This is called when the Map is defined
can.Map.helpers.define = function (Map) {
var definitions = Map.prototype.define;
//!steal-remove-start
if(Map.define){
can.dev.warn("The define property should be on the map's prototype properties, "+
"not the static properies.");
}
//!steal-remove-end
Map.defaultGenerators = {};
for (var prop in definitions) {
var type = definitions[prop].type;
if( typeof type === "string" ) {
if(typeof define.types[type] === "object") {
delete definitions[prop].type;
can.extend(definitions[prop], define.types[type]);
}
}
if ("value" in definitions[prop]) {
if (typeof definitions[prop].value === "function") {
Map.defaultGenerators[prop] = definitions[prop].value;
} else {
Map.defaults[prop] = definitions[prop].value;
}
}
if (typeof definitions[prop].Value === "function") {
(function (Constructor) {
Map.defaultGenerators[prop] = function () {
return new Constructor();
};
})(definitions[prop].Value);
}
}
};
var oldSetupDefaults = can.Map.prototype._setupDefaults;
can.Map.prototype._setupDefaults = function (obj) {
var defaults = oldSetupDefaults.call(this),
propsCommittedToAttr = {},
Map = this.constructor,
originalGet = this._get;
// Overwrite this._get with a version that commits defaults to
// this.attr() as needed. Because calling this.attr() for each individual
// default would be expensive.
this._get = function (originalProp) {
// If a this.attr() was called using dot syntax (e.g number.0),
// disregard everything after the "." until we call the
// original this._get().
prop = (originalProp.indexOf('.') !== -1 ?
originalProp.substr(0, originalProp.indexOf('.')) :
prop);
// If this property has a default and we haven't yet committed it to
// this.attr()
if ((prop in defaults) && ! (prop in propsCommittedToAttr)) {
// Commit the property's default so that it can be read in
// other defaultGenerators.
this.attr(prop, defaults[prop]);
// Make not so that we don't commit this property again.
propsCommittedToAttr[prop] = true;
}
return originalGet.apply(this, arguments);
};
for (var prop in Map.defaultGenerators) {
// Only call the prop's value method if the property wasn't provided
// during instantiation.
if (! obj || ! (prop in obj)) {
defaults[prop] = Map.defaultGenerators[prop].call(this);
}
}
// Replace original this.attr
this._get = originalGet;
return defaults;
};
var proto = can.Map.prototype,
oldSet = proto.__set;
proto.__set = function (prop, value, current, success, error) {
//!steal-remove-start
var asyncTimer;
//!steal-remove-end
// check if there's a setter
var errorCallback = function (errors) {
//!steal-remove-start
clearTimeout(asyncTimer);
//!steal-remove-end
var stub = error && error.call(self, errors);
// if 'validations' is on the page it will trigger
// the error itself and we dont want to trigger
// the event twice. :)
if (stub !== false) {
can.trigger(self, 'error', [
prop,
errors
], true);
}
return false;
},
self = this,
setter = getPropDefineBehavior("set", prop, this.define),
getter = getPropDefineBehavior("get", prop, this.define);
// if we have a setter
if (setter) {
// call the setter, if returned value is undefined,
// this means the setter is async so we
// do not call update property and return right away
can.batch.start();
var setterCalled = false,
setValue = setter.call(this, value, function (value) {
if(getter) {
self[prop](value);
} else {
oldSet.call(self, prop, value, current, success, errorCallback);
}
setterCalled = true;
//!steal-remove-start
clearTimeout(asyncTimer);
//!steal-remove-end
}, errorCallback, getter ? this[prop].computeInstance.lastSetValue.get() : current);
if (getter) {
// if there's a getter we don't call old set
// instead we call the getter's compute with the new value
if(setValue !== undefined && !setterCalled && setter.length >= 1) {
this[prop](setValue);
}
can.batch.stop();
return;
}
// if it took a setter and returned nothing, don't set the value
else if (setValue === undefined && !setterCalled && setter.length >= 1) {
//!steal-remove-start
asyncTimer = setTimeout(function () {
can.dev.warn('can/map/setter.js: Setter "' + prop + '" did not return a value or call the setter callback.');
}, can.dev.warnTimeout);
//!steal-remove-end
can.batch.stop();
return;
} else {
if (!setterCalled) {
oldSet.call(self, prop,
// if no arguments, we are side-effects only
setter.length === 0 && setValue === undefined ? value : setValue,
current,
success,
errorCallback);
}
can.batch.stop();
return this;
}
} else {
oldSet.call(self, prop, value, current, success, errorCallback);
}
return this;
};
define.types = {
'date': function (str) {
var type = typeof str;
if (type === 'string') {
str = Date.parse(str);
return isNaN(str) ? null : new Date(str);
} else if (type === 'number') {
return new Date(str);
} else {
return str;
}
},
'number': function (val) {
if(val == null) {
return val;
}
return +(val);
},
'boolean': function (val) {
if (val === 'false' || val === '0' || !val) {
return false;
}
return true;
},
/**
* Implements HTML-style boolean logic for attribute strings, where
* any string, including "", is truthy.
*/
'htmlbool': function(val) {
return typeof val === "string" || !!val;
},
'*': function (val) {
return val;
},
'string': function (val) {
if(val == null) {
return val;
}
return '' + val;
},
'compute': {
set: function(newValue, setVal, setErr, oldValue){
if(newValue.isComputed) {
return newValue;
}
if(oldValue && oldValue.isComputed) {
oldValue(newValue);
return oldValue;
}
return newValue;
},
get: function(value){
return value && value.isComputed ? value() : value;
}
}
};
// the old type sets up bubbling
var oldType = proto.__type;
proto.__type = function (value, prop) {
var type = getPropDefineBehavior("type", prop, this.define),
Type = getPropDefineBehavior("Type", prop, this.define),
newValue = value;
if (typeof type === "string") {
type = define.types[type];
}
if (type || Type) {
// If there's a type, convert it.
if (type) {
newValue = type.call(this, newValue, prop);
}
// If there's a Type create a new instance of it
if (Type && !(newValue instanceof Type)) {
newValue = new Type(newValue);
}
// If the newValue is a Map, we need to hook it up
return newValue;
}
// If we pass in a object with define
else if(can.isPlainObject(newValue) && newValue.define) {
newValue = can.Map.extend(newValue);
newValue = new newValue();
}
return oldType.call(this, newValue, prop);
};
var oldRemove = proto._remove;
proto._remove = function (prop, current) {
var remove = getPropDefineBehavior("remove", prop, this.define),
res;
if (remove) {
can.batch.start();
res = remove.call(this, current);
if (res === false) {
can.batch.stop();
return;
} else {
res = oldRemove.call(this, prop, current);
can.batch.stop();
return res;
}
}
return oldRemove.call(this, prop, current);
};
var oldSetupComputes = proto._setupComputes;
proto._setupComputes = function (defaultsValues) {
oldSetupComputes.apply(this, arguments);
for (var attr in this.define) {
var def = this.define[attr],
get = def.get;
if (get) {
this[attr] = can.compute.async(defaultsValues[attr], get, this);
this._computedBindings[attr] = {
count: 0
};
}
}
};
// Overwrite the invidual property serializer b/c we will overwrite it.
var oldSingleSerialize = can.Map.helpers._serialize;
can.Map.helpers._serialize = function(map, name, val){
return serializeProp(map, name, val);
};
// If the map has a define serializer for the given attr, run it.
var serializeProp = function(map, attr, val) {
var serializer = attr === "*" ? false : getPropDefineBehavior("serialize", attr, map.define);
if(serializer === undefined) {
return oldSingleSerialize.apply(this, arguments);
} else if(serializer !== false){
return typeof serializer === "function" ? serializer.call(map, val, attr): oldSingleSerialize.apply(this, arguments);
}
};
// Overwrite serialize to add in any missing define serialized properties.
var oldSerialize = proto.serialize;
proto.serialize = function (property) {
var serialized = oldSerialize.apply(this, arguments);
if(property){
return serialized;
}
// add in properties not already serialized
var serializer,
val;
// Go through each property.
for(var attr in this.define){
// if it's not already defined
if(!(attr in serialized)) {
// check there is a serializer so we aren't doing extra work on serializer:false
serializer = this.define && this.define[attr] && this.define[attr].serialize;
if(serializer) {
val = serializeProp(this, attr, this.attr(attr));
if(val !== undefined) {
serialized[attr] = val;
}
}
}
}
return serialized;
};
return can.define;
});
| patrick-steele-idem/canjs | map/define/define.js | JavaScript | mit | 9,933 |
'use strict';
// src/services/user/hooks/gravatar.js
//
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html
// We need this to create the MD5 hash
const crypto = require('crypto');
// The Gravatar image service
const gravatarUrl = 'https://s.gravatar.com/avatar';
// The size query. Our ScoreBoard needs 60px images
const query = `s=60`;
// Returns a full URL to a Gravatar image for a given email address
const gravatarImage = (email) => {
// Gravatar uses MD5 hashes from an email address to get the image
const hash = crypto.createHash('md5').update(email).digest('hex');
return `${gravatarUrl}/${hash}?${query}`;
};
module.exports = function() {
return function(hook) {
// Assign the new data with the Gravatar image
hook.data = Object.assign({}, hook.data, {
avatar: gravatarImage(hook.data.email)
});
};
};
| tlohstroh/dots-and-boxes | src/services/user/hooks/gravatar.js | JavaScript | mit | 936 |
var path = require('path'),
events = require('events'),
assert = require('assert'),
fs = require('fs'),
vows = require('../lib/vows');
var api = vows.prepare({
get: function (id, callback) {
process.nextTick(function () { callback(null, id) });
},
version: function () { return '1.0' }
}, ['get']);
var promiser = function (val) {
return function () {
var promise = new(events.EventEmitter);
process.nextTick(function () { promise.emit('success', val) });
return promise;
}
};
vows.describe("Vows").addBatch({
"A context": {
topic: promiser("hello world"),
"with a nested context": {
topic: function (parent) {
this.state = 42;
return promiser(parent)();
},
"has access to the environment": function () {
assert.equal(this.state, 42);
},
"and a sub nested context": {
topic: function () {
return this.state;
},
"has access to the parent environment": function (r) {
assert.equal(r, 42);
assert.equal(this.state, 42);
},
"has access to the parent context object": function (r) {
assert.ok(Array.isArray(this.context.topics));
assert.include(this.context.topics, "hello world");
}
}
}
},
"A nested context": {
topic: promiser(1),
".": {
topic: function (a) { return promiser(2)() },
".": {
topic: function (b, a) { return promiser(3)() },
".": {
topic: function (c, b, a) { return promiser([4, c, b, a])() },
"should have access to the parent topics": function (topics) {
assert.equal(topics.join(), [4, 3, 2, 1].join());
}
},
"from": {
topic: function (c, b, a) { return promiser([4, c, b, a])() },
"the parent topics": function(topics) {
assert.equal(topics.join(), [4, 3, 2, 1].join());
}
}
}
}
},
"Nested contexts with callback-style async": {
topic: function () {
fs.stat(__dirname + '/vows-test.js', this.callback);
},
'after a successful `fs.stat`': {
topic: function (stat) {
fs.open(__dirname + '/vows-test.js', "r", stat.mode, this.callback);
},
'after a successful `fs.open`': {
topic: function (fd, stat) {
fs.read(fd, stat.size, 0, "utf8", this.callback);
},
'after a successful `fs.read`': function (data) {
assert.match (data, /after a successful `fs.read`/);
}
}
}
},
"A nested context with no topics": {
topic: 45,
".": {
".": {
"should pass the value down": function (topic) {
assert.equal(topic, 45);
}
}
}
},
"A Nested context with topic gaps": {
topic: 45,
".": {
".": {
topic: 101,
".": {
".": {
topic: function (prev, prev2) {
return this.context.topics.slice(0);
},
"should pass the topics down": function (topics) {
assert.length(topics, 2);
assert.equal(topics[0], 101);
assert.equal(topics[1], 45);
}
}
}
}
}
},
"A non-promise return value": {
topic: function () { return 1 },
"should be converted to a promise": function (val) {
assert.equal(val, 1);
}
},
"A 'prepared' interface": {
"with a wrapped function": {
topic: function () { return api.get(42) },
"should work as expected": function (val) {
assert.equal(val, 42);
}
},
"with a non-wrapped function": {
topic: function () { return api.version() },
"should work as expected": function (val) {
assert.equal(val, '1.0');
}
}
},
"A non-function topic": {
topic: 45,
"should work as expected": function (topic) {
assert.equal(topic, 45);
}
},
"A non-function topic with a falsy value": {
topic: 0,
"should work as expected": function (topic) {
assert.equal(topic, 0);
}
},
"A topic returning a function": {
topic: function () {
return function () { return 42 };
},
"should work as expected": function (topic) {
assert.isFunction(topic);
assert.equal(topic(), 42);
},
"in a sub-context": {
"should work as expected": function (topic) {
assert.isFunction(topic);
assert.equal(topic(), 42);
},
}
},
"A topic emitting an error": {
topic: function () {
var promise = new(events.EventEmitter);
process.nextTick(function () {
promise.emit("error", 404);
});
return promise;
},
"shouldn't raise an exception if the test expects it": function (e, res) {
assert.equal(e, 404);
assert.ok(! res);
}
},
"A topic not emitting an error": {
topic: function () {
var promise = new(events.EventEmitter);
process.nextTick(function () {
promise.emit("success", true);
});
return promise;
},
"should pass `null` as first argument, if the test is expecting an error": function (e, res) {
assert.strictEqual(e, null);
assert.equal(res, true);
},
"should pass the result as first argument if the test isn't expecting an error": function (res) {
assert.equal(res, true);
}
},
"A topic with callback-style async": {
"when successful": {
topic: function () {
var that = this;
process.nextTick(function () {
that.callback(null, "OK");
});
},
"should work like an event-emitter": function (res) {
assert.equal(res, "OK");
},
"should assign `null` to the error argument": function (e, res) {
assert.strictEqual(e, null);
assert.equal(res, "OK");
}
},
"when unsuccessful": {
topic: function () {
function async(callback) {
process.nextTick(function () {
callback("ERROR");
});
}
async(this.callback);
},
"should have a non-null error value": function (e, res) {
assert.equal(e, "ERROR");
},
"should work like an event-emitter": function (e, res) {
assert.equal(res, undefined);
}
},
"using this.callback synchronously": {
topic: function () {
this.callback(null, 'hello');
},
"should work the same as returning a value": function (res) {
assert.equal(res, 'hello');
}
},
"using this.callback with a user context": {
topic: function () {
this.callback.call({ boo: true }, null, 'hello');
},
"should give access to the user context": function (res) {
assert.isTrue(this.boo);
}
},
"passing this.callback to a function": {
topic: function () {
this.boo = true;
var async = function (callback) {
callback(null);
};
async(this.callback);
},
"should give access to the topic context": function () {
assert.isTrue(this.boo);
}
},
"with multiple arguments": {
topic: function () {
this.callback(null, 1, 2, 3);
},
"should pass them to the vow": function (e, a, b, c) {
assert.strictEqual(e, null);
assert.strictEqual(a, 1);
assert.strictEqual(b, 2);
assert.strictEqual(c, 3);
},
"and a sub-topic": {
topic: function (a, b, c) {
return [a, b, c];
},
"should receive them too": function (val) {
assert.deepEqual(val, [1, 2, 3]);
}
}
}
}
}).addBatch({
"A Sibling context": {
"'A', with `this.foo = true`": {
topic: function () {
this.foo = true;
return this;
},
"should have `this.foo` set to true": function (res) {
assert.equal(res.foo, true);
}
},
"'B', with nothing set": {
topic: function () {
return this;
},
"shouldn't have access to `this.foo`": function (e, res) {
assert.isUndefined(res.foo);
}
}
}
}).addBatch({
"A 2nd batch": {
topic: function () {
var p = new(events.EventEmitter);
setTimeout(function () {
p.emit("success");
}, 100);
return p;
},
"should run after the first": function () {}
}
}).addBatch({
"A 3rd batch": {
topic: true, "should run last": function () {}
}
}).addBatch({}).export(module);
vows.describe("Vows with a single batch", {
"This is a batch that's added as the optional parameter to describe()": {
topic: true,
"And a vow": function () {}
}
}).export(module);
vows.describe("Vows with multiple batches added as optional parameters", {
"First batch": {
topic: true,
"should be run first": function () {}
}
}, {
"Second batch": {
topic: true,
"should be run second": function () {}
}
}).export(module);
vows.describe("Vows with teardowns").addBatch({
"A context": {
topic: function () {
return { flag: true };
},
"And a vow": function (topic) {
assert.isTrue(topic.flag);
},
"And another vow": function (topic) {
assert.isTrue(topic.flag);
},
"And a final vow": function (topic) {
assert.isTrue(topic.flag);
},
'subcontext': {
'nested': function (_, topic) {
assert.isTrue(topic.flag);
}
},
teardown: function (topic) {
topic.flag = false;
},
"with a subcontext" : {
topic: function (topic) {
var that = this;
process.nextTick(function () {
that.callback(null, topic);
});
},
"Waits for the subcontext before teardown" : function(topic) {
assert.isTrue(topic.flag);
}
}
}
}).export(module);
| rwaldron/vows | test/vows-test.js | JavaScript | mit | 11,827 |
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import ButtonGroup from '../ButtonGroup';
const buttons = ['Button 1', 'Button 2', 'Button 3'];
const buttonsElement = [{ element: 'Text' }, { element: 'View' }];
describe('ButtonGroup Component', () => {
it('should render without issues', () => {
const component = shallow(<ButtonGroup buttons={buttons} />);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should have onPress event', () => {
const onPress = jest.fn();
const component = shallow(
<ButtonGroup
buttons={buttons}
onPress={onPress}
containerStyle={{ backgroundColor: 'yellow' }}
buttonStyle={{ backgroundColor: 'blue' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render selectedIndex', () => {
const component = shallow(
<ButtonGroup
buttons={buttons}
selectedIndex={1}
selectedBackgroundColor="red"
selectedTextStyle={{ fontSize: 12 }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render with button.element', () => {
const component = shallow(
<ButtonGroup
buttons={buttonsElement}
innerBorderStyle={{ width: 300, color: 'red' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render lastButtonStyle', () => {
const component = shallow(
<ButtonGroup
buttons={buttons}
lastBorderStyle={{ backgroundColor: 'red' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
});
| kosiakMD/react-native-elements | src/buttons/__tests__/ButtonGroup.js | JavaScript | mit | 1,831 |
"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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var NameGenerator = function () {
function NameGenerator() {
_classCallCheck(this, NameGenerator);
}
_createClass(NameGenerator, null, [{
key: "generateName",
value: function generateName(prototype, type) {
return type.substr(0, 1).toUpperCase() + type.substr(1);
}
}]);
return NameGenerator;
}();
exports.default = NameGenerator; | vovance/3d-demo | lib/utils/name-generator.js | JavaScript | mit | 1,167 |
'use strict';
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
module.exports = function parseDate(key, value) {
return (typeof value === 'string' && reISO.exec(value)) ? new Date(value) : value;
};
| ezekielthao/mozu-node-sdk | utils/parse-json-dates.js | JavaScript | mit | 248 |
var testCase = require('../deps/nodeunit').testCase,
debug = require('util').debug,
inspect = require('util').inspect,
nodeunit = require('../deps/nodeunit'),
gleak = require('../tools/gleak'),
Db = require('../lib/mongodb').Db,
Cursor = require('../lib/mongodb').Cursor,
Step = require("../deps/step/lib/step"),
Collection = require('../lib/mongodb').Collection,
Server = require('../lib/mongodb').Server;
var MONGODB = 'integration_tests';
var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)});
// Define the tests, we want them to run as a nested test so we only clean up the
// db connection once
var tests = testCase({
setUp: function(callback) {
client.open(function(err, db_p) {
if(numberOfTestsRun == Object.keys(tests).length) {
// If first test drop the db
client.dropDatabase(function(err, done) {
callback();
});
} else {
return callback();
}
});
},
tearDown: function(callback) {
numberOfTestsRun = numberOfTestsRun - 1;
// Drop the database and close it
if(numberOfTestsRun <= 0) {
// client.dropDatabase(function(err, done) {
client.close();
callback();
// });
} else {
client.close();
callback();
}
},
shouldCorrectlyExecuteToArray : function(test) {
// Create a non-unique index and test inserts
client.createCollection('test_array', function(err, collection) {
collection.insert({'b':[1, 2, 3]}, {safe:true}, function(err, ids) {
collection.find().toArray(function(err, documents) {
test.deepEqual([1, 2, 3], documents[0].b);
// Let's close the db
test.done();
});
});
});
},
shouldCorrectlyExecuteToArrayAndFailOnFurtherCursorAccess : function(test) {
client.createCollection('test_to_a', function(err, collection) {
test.ok(collection instanceof Collection);
collection.insert({'a':1}, {safe:true}, function(err, ids) {
collection.find({}, function(err, cursor) {
cursor.toArray(function(err, items) {
// Should fail if called again (cursor should be closed)
cursor.toArray(function(err, items) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
// Should fail if called again (cursor should be closed)
cursor.each(function(err, item) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
// Let's close the db
test.done();
});
});
});
});
});
});
},
shouldCorrectlyFailToArrayDueToFinishedEachOperation : function(test) {
client.createCollection('test_to_a_after_each', function(err, collection) {
test.ok(collection instanceof Collection);
collection.insert({'a':1}, {safe:true}, function(err, ids) {
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
if(item == null) {
cursor.toArray(function(err, items) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
// Let's close the db
test.done();
});
};
});
});
});
});
},
shouldCorrectlyExecuteCursorExplain : function(test) {
client.createCollection('test_explain', function(err, collection) {
collection.insert({'a':1}, {safe:true}, function(err, r) {
collection.find({'a':1}, function(err, cursor) {
cursor.explain(function(err, explaination) {
test.ok(explaination.cursor != null);
test.ok(explaination.n.constructor == Number);
test.ok(explaination.millis.constructor == Number);
test.ok(explaination.nscanned.constructor == Number);
// Let's close the db
test.done();
});
});
});
});
},
shouldCorrectlyExecuteCursorCount : function(test) {
client.createCollection('test_count', function(err, collection) {
collection.find(function(err, cursor) {
cursor.count(function(err, count) {
test.equal(0, count);
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 10; i++) {
collection.insert({'x':i}, {safe:true}, group());
}
},
function finished() {
collection.find().count(function(err, count) {
test.equal(10, count);
test.ok(count.constructor == Number);
});
collection.find({}, {'limit':5}).count(function(err, count) {
test.equal(10, count);
});
collection.find({}, {'skip':5}).count(function(err, count) {
test.equal(10, count);
});
collection.find(function(err, cursor) {
cursor.count(function(err, count) {
test.equal(10, count);
cursor.each(function(err, item) {
if(item == null) {
cursor.count(function(err, count2) {
test.equal(10, count2);
test.equal(count, count2);
// Let's close the db
test.done();
});
}
});
});
});
client.collection('acollectionthatdoesn', function(err, collection) {
collection.count(function(err, count) {
test.equal(0, count);
});
})
}
)
});
});
});
},
shouldCorrectlyExecuteSortOnCursor : function(test) {
client.createCollection('test_sort', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 5; i++) {
collection.insert({'a':i}, {safe:true}, group());
}
},
function finished() {
collection.find(function(err, cursor) {
cursor.sort(['a', 1], function(err, cursor) {
test.ok(cursor instanceof Cursor);
test.deepEqual(['a', 1], cursor.sortValue);
});
});
collection.find(function(err, cursor) {
cursor.sort('a', 1, function(err, cursor) {
cursor.nextObject(function(err, doc) {
test.equal(0, doc.a);
});
});
});
collection.find(function(err, cursor) {
cursor.sort('a', -1, function(err, cursor) {
cursor.nextObject(function(err, doc) {
test.equal(4, doc.a);
});
});
});
collection.find(function(err, cursor) {
cursor.sort('a', "asc", function(err, cursor) {
cursor.nextObject(function(err, doc) {
test.equal(0, doc.a);
});
});
});
collection.find(function(err, cursor) {
cursor.sort([['a', -1], ['b', 1]], function(err, cursor) {
test.ok(cursor instanceof Cursor);
test.deepEqual([['a', -1], ['b', 1]], cursor.sortValue);
});
});
collection.find(function(err, cursor) {
cursor.sort('a', 1, function(err, cursor) {
cursor.sort('a', -1, function(err, cursor) {
cursor.nextObject(function(err, doc) {
test.equal(4, doc.a);
});
})
});
});
collection.find(function(err, cursor) {
cursor.sort('a', -1, function(err, cursor) {
cursor.sort('a', 1, function(err, cursor) {
cursor.nextObject(function(err, doc) {
test.equal(0, doc.a);
});
})
});
});
collection.find(function(err, cursor) {
cursor.nextObject(function(err, doc) {
cursor.sort(['a'], function(err, cursor) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
});
});
});
collection.find(function(err, cursor) {
cursor.sort('a', 25, function(err, cursor) {
cursor.nextObject(function(err, doc) {
test.ok(err instanceof Error);
test.equal("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message);
});
});
});
collection.find(function(err, cursor) {
cursor.sort(25, function(err, cursor) {
cursor.nextObject(function(err, doc) {
test.ok(err instanceof Error);
test.equal("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message);
// Let's close the db
test.done();
});
});
});
}
);
});
},
shouldCorrectlyThrowErrorOnToArrayWhenMissingCallback : function(test) {
client.createCollection('test_to_array', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 2; i++) {
collection.save({'x':1}, {safe:true}, group());
}
},
function finished() {
collection.find(function(err, cursor) {
test.throws(function () {
cursor.toArray();
});
test.done();
});
}
)
});
},
shouldThrowErrorOnEachWhenMissingCallback : function(test) {
client.createCollection('test_each', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 2; i++) {
collection.save({'x':1}, {safe:true}, group());
}
},
function finished() {
collection.find(function(err, cursor) {
test.throws(function () {
cursor.each();
});
test.done();
});
}
)
});
},
shouldCorrectlyHandleLimitOnCursor : function(test) {
client.createCollection('test_cursor_limit', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 10; i++) {
collection.save({'x':1}, {safe:true}, group());
}
},
function finished() {
collection.find().count(function(err, count) {
test.equal(10, count);
});
collection.find(function(err, cursor) {
cursor.limit(5, function(err, cursor) {
cursor.toArray(function(err, items) {
test.equal(5, items.length);
// Let's close the db
test.done();
});
});
});
}
);
});
},
shouldCorrectlyReturnErrorsOnIllegalLimitValues : function(test) {
client.createCollection('test_limit_exceptions', function(err, collection) {
collection.insert({'a':1}, {safe:true}, function(err, docs) {});
collection.find(function(err, cursor) {
cursor.limit('not-an-integer', function(err, cursor) {
test.ok(err instanceof Error);
test.equal("limit requires an integer", err.message);
});
});
collection.find(function(err, cursor) {
cursor.nextObject(function(err, doc) {
cursor.limit(1, function(err, cursor) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
});
});
});
collection.find(function(err, cursor) {
cursor.close(function(err, cursor) {
cursor.limit(1, function(err, cursor) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
test.done();
});
});
});
});
},
shouldCorrectlySkipRecordsOnCursor : function(test) {
client.createCollection('test_skip', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 10; i++) {
collection.insert({'x':i}, {safe:true}, group());
}
},
function finished() {
collection.find(function(err, cursor) {
cursor.count(function(err, count) {
test.equal(10, count);
});
});
collection.find(function(err, cursor) {
cursor.toArray(function(err, items) {
test.equal(10, items.length);
collection.find(function(err, cursor) {
cursor.skip(2, function(err, cursor) {
cursor.toArray(function(err, items2) {
test.equal(8, items2.length);
// Check that we have the same elements
var numberEqual = 0;
var sliced = items.slice(2, 10);
for(var i = 0; i < sliced.length; i++) {
if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1;
}
test.equal(8, numberEqual);
// Let's close the db
test.done();
});
});
});
});
});
}
)
});
},
shouldCorrectlyReturnErrorsOnIllegalSkipValues : function(test) {
client.createCollection('test_skip_exceptions', function(err, collection) {
collection.insert({'a':1}, {safe:true}, function(err, docs) {});
collection.find(function(err, cursor) {
cursor.skip('not-an-integer', function(err, cursor) {
test.ok(err instanceof Error);
test.equal("skip requires an integer", err.message);
});
});
collection.find(function(err, cursor) {
cursor.nextObject(function(err, doc) {
cursor.skip(1, function(err, cursor) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
});
});
});
collection.find(function(err, cursor) {
cursor.close(function(err, cursor) {
cursor.skip(1, function(err, cursor) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
test.done();
});
});
});
});
},
shouldReturnErrorsOnIllegalBatchSizes : function(test) {
client.createCollection('test_batchSize_exceptions', function(err, collection) {
collection.insert({'a':1}, {safe:true}, function(err, docs) {});
collection.find(function(err, cursor) {
cursor.batchSize('not-an-integer', function(err, cursor) {
test.ok(err instanceof Error);
test.equal("batchSize requires an integer", err.message);
});
});
collection.find(function(err, cursor) {
cursor.nextObject(function(err, doc) {
cursor.nextObject(function(err, doc) {
cursor.batchSize(1, function(err, cursor) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
});
});
});
});
collection.find(function(err, cursor) {
cursor.close(function(err, cursor) {
cursor.batchSize(1, function(err, cursor) {
test.ok(err instanceof Error);
test.equal("Cursor is closed", err.message);
test.done();
});
});
});
});
},
shouldCorrectlyHandleChangesInBatchSizes : function(test) {
client.createCollection('test_not_multiple_batch_size', function(err, collection) {
var records = 6;
var batchSize = 2;
var docs = [];
for(var i = 0; i < records; i++) {
docs.push({'a':i});
}
collection.insert(docs, {safe:true}, function() {
collection.find({}, {batchSize : batchSize}, function(err, cursor) {
//1st
cursor.nextObject(function(err, items) {
//cursor.items should contain 1 since nextObject already popped one
test.equal(1, cursor.items.length);
test.ok(items != null);
//2nd
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
test.ok(items != null);
//test batch size modification on the fly
batchSize = 3;
cursor.batchSize(batchSize);
//3rd
cursor.nextObject(function(err, items) {
test.equal(2, cursor.items.length);
test.ok(items != null);
//4th
cursor.nextObject(function(err, items) {
test.equal(1, cursor.items.length);
test.ok(items != null);
//5th
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
test.ok(items != null);
//6th
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
test.ok(items != null);
//No more
cursor.nextObject(function(err, items) {
test.ok(items == null);
test.ok(cursor.isClosed());
test.done();
});
});
});
});
});
});
});
});
});
});
},
shouldCorrectlyHandleBatchSize : function(test) {
client.createCollection('test_multiple_batch_size', function(err, collection) {
//test with the last batch that is a multiple of batchSize
var records = 4;
var batchSize = 2;
var docs = [];
for(var i = 0; i < records; i++) {
docs.push({'a':i});
}
collection.insert(docs, {safe:true}, function() {
collection.find({}, {batchSize : batchSize}, function(err, cursor) {
//1st
cursor.nextObject(function(err, items) {
test.equal(1, cursor.items.length);
test.ok(items != null);
//2nd
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
test.ok(items != null);
//3rd
cursor.nextObject(function(err, items) {
test.equal(1, cursor.items.length);
test.ok(items != null);
//4th
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
test.ok(items != null);
//No more
cursor.nextObject(function(err, items) {
test.ok(items == null);
test.ok(cursor.isClosed());
test.done();
});
});
});
});
});
});
});
});
},
shouldHandleWhenLimitBiggerThanBatchSize : function(test) {
client.createCollection('test_limit_greater_than_batch_size', function(err, collection) {
var limit = 4;
var records = 10;
var batchSize = 3;
var docs = [];
for(var i = 0; i < records; i++) {
docs.push({'a':i});
}
collection.insert(docs, {safe:true}, function() {
collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) {
//1st
cursor.nextObject(function(err, items) {
test.equal(2, cursor.items.length);
//2nd
cursor.nextObject(function(err, items) {
test.equal(1, cursor.items.length);
//3rd
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
//4th
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
//No more
cursor.nextObject(function(err, items) {
test.ok(items == null);
test.ok(cursor.isClosed());
test.done();
});
});
});
});
});
});
});
});
},
shouldHandleLimitLessThanBatchSize : function(test) {
client.createCollection('test_limit_less_than_batch_size', function(err, collection) {
var limit = 2;
var records = 10;
var batchSize = 4;
var docs = [];
for(var i = 0; i < records; i++) {
docs.push({'a':i});
}
collection.insert(docs, {safe:true}, function() {
collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) {
//1st
cursor.nextObject(function(err, items) {
test.equal(1, cursor.items.length);
//2nd
cursor.nextObject(function(err, items) {
test.equal(0, cursor.items.length);
//No more
cursor.nextObject(function(err, items) {
test.ok(items == null);
test.ok(cursor.isClosed());
test.done();
});
});
});
});
});
});
},
shouldHandleSkipLimitChaining : function(test) {
client.createCollection('test_limit_skip_chaining', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 10; i++) {
collection.insert({'x':1}, {safe:true}, group());
}
},
function finished() {
collection.find(function(err, cursor) {
cursor.toArray(function(err, items) {
test.equal(10, items.length);
collection.find(function(err, cursor) {
cursor.limit(5, function(err, cursor) {
cursor.skip(3, function(err, cursor) {
cursor.toArray(function(err, items2) {
test.equal(5, items2.length);
// Check that we have the same elements
var numberEqual = 0;
var sliced = items.slice(3, 8);
for(var i = 0; i < sliced.length; i++) {
if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1;
}
test.equal(5, numberEqual);
// Let's close the db
test.done();
});
});
});
});
});
});
}
)
});
},
shouldCorrectlyHandleLimitSkipChainingInline : function(test) {
client.createCollection('test_limit_skip_chaining_inline', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 10; i++) {
collection.insert({'x':1}, {safe:true}, group());
}
},
function finished() {
collection.find(function(err, cursor) {
cursor.toArray(function(err, items) {
test.equal(10, items.length);
collection.find(function(err, cursor) {
cursor.limit(5).skip(3).toArray(function(err, items2) {
test.equal(5, items2.length);
// Check that we have the same elements
var numberEqual = 0;
var sliced = items.slice(3, 8);
for(var i = 0; i < sliced.length; i++) {
if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1;
}
test.equal(5, numberEqual);
// Let's close the db
test.done();
});
});
});
});
}
)
});
},
shouldCloseCursorNoQuerySent : function(test) {
client.createCollection('test_close_no_query_sent', function(err, collection) {
collection.find(function(err, cursor) {
cursor.close(function(err, cursor) {
test.equal(true, cursor.isClosed());
// Let's close the db
test.done();
});
});
});
},
shouldCorrectlyRefillViaGetMoreCommand : function(test) {
client.createCollection('test_refill_via_get_more', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 1000; i++) {
collection.save({'a': i}, {safe:true}, group());
}
},
function finished() {
collection.count(function(err, count) {
test.equal(1000, count);
});
var total = 0;
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
if(item != null) {
total = total + item.a;
} else {
test.equal(499500, total);
collection.count(function(err, count) {
test.equal(1000, count);
});
collection.count(function(err, count) {
test.equal(1000, count);
var total2 = 0;
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
if(item != null) {
total2 = total2 + item.a;
} else {
test.equal(499500, total2);
collection.count(function(err, count) {
test.equal(1000, count);
test.equal(total, total2);
// Let's close the db
test.done();
});
}
});
});
});
}
});
});
}
)
});
},
shouldCorrectlyRefillViaGetMoreAlternativeCollection : function(test) {
client.createCollection('test_refill_via_get_more_alt_coll', function(err, collection) {
Step(
function insert() {
var group = this.group();
for(var i = 0; i < 1000; i++) {
collection.save({'a': i}, {safe:true}, group());
}
},
function finished() {
collection.count(function(err, count) {
test.equal(1000, count);
});
var total = 0;
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
if(item != null) {
total = total + item.a;
} else {
test.equal(499500, total);
collection.count(function(err, count) {
test.equal(1000, count);
});
collection.count(function(err, count) {
test.equal(1000, count);
var total2 = 0;
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
if(item != null) {
total2 = total2 + item.a;
} else {
test.equal(499500, total2);
collection.count(function(err, count) {
test.equal(1000, count);
test.equal(total, total2);
// Let's close the db
test.done();
});
}
});
});
});
}
});
});
}
)
});
},
shouldCloseCursorAfterQueryHasBeenSent : function(test) {
client.createCollection('test_close_after_query_sent', function(err, collection) {
collection.insert({'a':1}, {safe:true}, function(err, r) {
collection.find({'a':1}, function(err, cursor) {
cursor.nextObject(function(err, item) {
cursor.close(function(err, cursor) {
test.equal(true, cursor.isClosed());
// Let's close the db
test.done();
})
});
});
});
});
},
shouldCorrectlyExecuteCursorCountWithFields : function(test) {
client.createCollection('test_count_with_fields', function(err, collection) {
collection.save({'x':1, 'a':2}, {safe:true}, function(err, doc) {
collection.find({}, {'fields':['a']}).toArray(function(err, items) {
test.equal(1, items.length);
test.equal(2, items[0].a);
test.equal(null, items[0].x);
});
collection.findOne({}, {'fields':['a']}, function(err, item) {
test.equal(2, item.a);
test.equal(null, item.x);
test.done();
});
});
});
},
shouldCorrectlyCountWithFieldsUsingExclude : function(test) {
client.createCollection('test_count_with_fields_using_exclude', function(err, collection) {
collection.save({'x':1, 'a':2}, {safe:true}, function(err, doc) {
collection.find({}, {'fields':{'x':0}}).toArray(function(err, items) {
test.equal(1, items.length);
test.equal(2, items[0].a);
test.equal(null, items[0].x);
test.done();
});
});
});
},
shouldCorrectlyInsert5000RecordsWithDateAndSortCorrectlyWithIndex : function(test) {
var docs = [];
for(var i = 0; i < 5000; i++) {
var d = new Date().getTime() + i*1000;
docs[i] = {createdAt:new Date(d)};
}
// Create collection
client.createCollection('shouldCorrectlyInsert5000RecordsWithDateAndSortCorrectlyWithIndex', function(err, collection) {
// ensure index of createdAt index
collection.ensureIndex({createdAt:1}, function(err, indexName) {
test.equal(null, err);
// insert all docs
collection.insert(docs, {safe:true}, function(err, result) {
test.equal(null, err);
// Find with sort
collection.find().sort(['createdAt', 'asc']).toArray(function(err, items) {
if (err) logger.error("error in collection_info.find: " + err);
test.equal(5000, items.length);
test.done();
})
})
});
});
},
'Should correctly rewind and restart cursor' : function(test) {
var docs = [];
for(var i = 0; i < 100; i++) {
var d = new Date().getTime() + i*1000;
docs[i] = {'a':i, createdAt:new Date(d)};
}
// Create collection
client.createCollection('Should_correctly_rewind_and_restart_cursor', function(err, collection) {
test.equal(null, err);
// insert all docs
collection.insert(docs, {safe:true}, function(err, result) {
test.equal(null, err);
var cursor = collection.find({});
cursor.nextObject(function(err, item) {
test.equal(0, item.a)
// Rewind the cursor
cursor.rewind();
// Grab the first object
cursor.nextObject(function(err, item) {
test.equal(0, item.a)
test.done();
})
})
})
});
},
// run this last
noGlobalsLeaked: function(test) {
var leaks = gleak.detectNew();
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
test.done();
}
})
// Stupid freaking workaround due to there being no way to run setup once for each suite
var numberOfTestsRun = Object.keys(tests).length;
// Assign out tests
module.exports = tests;
| liminglu/node_iblog | node_modules/mongoose/node_modules/mongodb/test/cursor_test.js | JavaScript | mit | 33,025 |
/**
* @file Visual solution, for consistent option specification.
*/
var zrUtil = require('zrender/lib/core/util');
var VisualMapping = require('./VisualMapping');
var each = zrUtil.each;
function hasKeys(obj) {
if (obj) {
for (var name in obj){
if (obj.hasOwnProperty(name)) {
return true;
}
}
}
}
var visualSolution = {
/**
* @param {Object} option
* @param {Array.<string>} stateList
* @param {Function} [supplementVisualOption]
* @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
*/
createVisualMappings: function (option, stateList, supplementVisualOption) {
var visualMappings = {};
each(stateList, function (state) {
var mappings = visualMappings[state] = createMappings();
each(option[state], function (visualData, visualType) {
if (!VisualMapping.isValidType(visualType)) {
return;
}
var mappingOption = {
type: visualType,
visual: visualData
};
supplementVisualOption && supplementVisualOption(mappingOption, state);
mappings[visualType] = new VisualMapping(mappingOption);
// Prepare a alpha for opacity, for some case that opacity
// is not supported, such as rendering using gradient color.
if (visualType === 'opacity') {
mappingOption = zrUtil.clone(mappingOption);
mappingOption.type = 'colorAlpha';
mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
}
});
});
return visualMappings;
function createMappings() {
var Creater = function () {};
// Make sure hidden fields will not be visited by
// object iteration (with hasOwnProperty checking).
Creater.prototype.__hidden = Creater.prototype;
var obj = new Creater();
return obj;
}
},
/**
* @param {Object} thisOption
* @param {Object} newOption
* @param {Array.<string>} keys
*/
replaceVisualOption: function (thisOption, newOption, keys) {
// Visual attributes merge is not supported, otherwise it
// brings overcomplicated merge logic. See #2853. So if
// newOption has anyone of these keys, all of these keys
// will be reset. Otherwise, all keys remain.
var has;
zrUtil.each(keys, function (key) {
if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
has = true;
}
});
has && zrUtil.each(keys, function (key) {
if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
thisOption[key] = zrUtil.clone(newOption[key]);
}
else {
delete thisOption[key];
}
});
},
/**
* @param {Array.<string>} stateList
* @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
* @param {module:echarts/data/List} list
* @param {Function} getValueState param: valueOrIndex, return: state.
* @param {object} [scope] Scope for getValueState
* @param {string} [dimension] Concrete dimension, if used.
*/
applyVisual: function (stateList, visualMappings, data, getValueState, scope, dimension) {
var visualTypesMap = {};
zrUtil.each(stateList, function (state) {
var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
visualTypesMap[state] = visualTypes;
});
var dataIndex;
function getVisual(key) {
return data.getItemVisual(dataIndex, key);
}
function setVisual(key, value) {
data.setItemVisual(dataIndex, key, value);
}
if (dimension == null) {
data.each(eachItem, true);
}
else {
data.each([dimension], eachItem, true);
}
function eachItem(valueOrIndex, index) {
dataIndex = dimension == null ? valueOrIndex : index;
var valueState = getValueState.call(scope, valueOrIndex);
var mappings = visualMappings[valueState];
var visualTypes = visualTypesMap[valueState];
for (var i = 0, len = visualTypes.length; i < len; i++) {
var type = visualTypes[i];
mappings[type] && mappings[type].applyVisual(
valueOrIndex, getVisual, setVisual
);
}
}
}
};
module.exports = visualSolution;
| ytbryan/chart | node_modules/echarts/lib/visual/visualSolution.js | JavaScript | mit | 5,294 |
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator', '$modal',
function ($scope, $state, $http, $location, $window, Authentication, PasswordValidator, $modal) {
$scope.authentication = Authentication;
$scope.popoverMsg = PasswordValidator.getPopoverMsg();
// Get an eventual error defined in the URL query string:
$scope.error = $location.search().err;
// If user is signed in then redirect back home
if ($scope.authentication.user) {
$location.path('/');
}
$scope.signup = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'userForm');
return false;
}
$http.post('/api/v1/auth/signup', $scope.credentials)
.success(function (response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the previous or home page
$state.go($state.previous.state.name || 'home', $state.previous.params);
}).error(function (response) {
$scope.error = response.message;
});
};
$scope.signin = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'userForm');
return false;
}
$http.post('/api/v1/auth/signin', $scope.credentials).success(function (response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the previous or home page
$state.go($state.previous.state.name || 'home', $state.previous.params);
}).error(function (response) {
$scope.error = response.message;
});
};
// OAuth provider request
$scope.callOauthProvider = function (url) {
if ($state.previous && $state.previous.href) {
url += '?redirect_to=' + encodeURIComponent($state.previous.href);
}
// Effectively call OAuth authentication route:
$window.location.href = url;
};
$scope.goToSignUp = function ($state) {
$state.go('signup');
};
// Reroutes from sign in to sign up on modal
$scope.modalOpenSignUp = function () {
var isSwitched = false;
$modal.open({
templateUrl: function () {
if (!isSwitched) {
isSwitched = false;
return 'modules/users/client/views/authentication/signup.client.view.html';
} else {
return 'modules/users/client/views/authentication/signin.client.view.html';
}
},
size: 'lg',
backdropClass: 'sign-in-modal-background',
windowClass: 'sign-in-modal-background',
backdrop: false,
controller: function ($scope) {
}
}).then(function () {
console.log('Success!!!!!');
});
};
}
]);
| IsomerEDU/MappingSLC | modules/users/client/controllers/authentication.client.controller.js | JavaScript | mit | 3,029 |
var ngdoc = require('../src/ngdoc.js');
var DOM = require('../src/dom.js').DOM;
describe('ngdoc', function() {
var Doc = ngdoc.Doc;
var dom;
beforeEach(function() {
dom = new DOM();
this.addMatchers({
toContain: function(text) {
this.actual = this.actual.toString();
return this.actual.indexOf(text) > -1;
}
});
});
describe('Doc', function() {
describe('metadata', function() {
it('should find keywords and filter ignored words', function() {
expect(new Doc('\nHello: World! @ignore. $abc').keywords()).toEqual('$abc hello world');
expect(new Doc('The `ng:class-odd` and').keywords()).toEqual('ng:class-odd');
});
it('should get property and methods', function() {
var doc = new Doc('Document');
doc.properties.push(new Doc('Proprety'));
doc.properties.push(new Doc('Method'));
expect(doc.keywords()).toEqual('document method proprety');
});
it('should have shortName', function() {
var d1 = new Doc('@name a.b.c').parse();
var d2 = new Doc('@name a.b.ng-c').parse();
var d3 = new Doc('@name some text: more text').parse();
expect(ngdoc.metadata([d1])[0].shortName).toEqual('c');
expect(ngdoc.metadata([d2])[0].shortName).toEqual('ng-c');
expect(ngdoc.metadata([d3])[0].shortName).toEqual('more text');
});
});
describe('parse', function() {
it('should convert @names into properties', function() {
var doc = new Doc('\n@name name\n@desc\ndesc\ndesc2\n@dep\n');
doc.parse();
expect(doc.name).toEqual('name');
expect(doc.desc).toEqual('desc\ndesc2');
expect(doc.dep).toEqual('');
});
it('should parse parameters', function() {
var doc = new Doc(
'@name a\n' +
'@param {*} a short\n' +
'@param {Type} b med\n' +
'@param {Class=} [c=2] long\nline\n' +
'@param {function(number, string=)} d fn with optional arguments');
doc.parse();
expect(doc.param).toEqual([
{name:'a', description:'<p>short</p>', type:'*', optional:false, 'default':undefined},
{name:'b', description:'<p>med</p>', type:'Type', optional:false, 'default':undefined},
{name:'c', description:'<p>long\nline</p>', type:'Class', optional:true, 'default':'2'},
{name:'d', description:'<p>fn with optional arguments</p>',
type: 'function(number, string=)', optional: false, 'default':undefined}
]);
});
it('should parse return', function() {
var doc = new Doc('@name a\n@returns {Type} text *bold*.');
doc.parse();
expect(doc.returns).toEqual({
type: 'Type',
description: '<p>text <em>bold</em>.</p>'
});
});
it('should parse filename', function() {
var doc = new Doc('@name friendly name', 'docs/a.b.ngdoc', 1);
doc.parse(0);
expect(doc.id).toEqual('a.b');
expect(doc.name).toEqual('friendly name');
});
it('should store all links', function() {
var doc = new Doc('@name a\n@description {@link api/angular.link}');
doc.parse();
expect(doc.links).toContain('api/angular.link');
});
describe('convertUrlToAbsolute', function() {
var doc;
beforeEach(function() {
doc = new Doc({section: 'section'});
});
it('should not change absolute url', function() {
expect(doc.convertUrlToAbsolute('guide/index')).toEqual('guide/index');
});
it('should prepend current section to relative url', function() {
expect(doc.convertUrlToAbsolute('angular.widget')).toEqual('section/angular.widget');
});
it('should change id to index if not specified', function() {
expect(doc.convertUrlToAbsolute('guide/')).toEqual('guide/index');
});
});
describe('sorting', function() {
function property(name) {
return function(obj) {return obj[name];};
}
function noop() {}
function doc(type, name){
return {
id: name,
ngdoc: type,
keywords: noop
};
}
var dev_guide_overview = doc('overview', 'dev_guide.overview');
var dev_guide_bootstrap = doc('function', 'dev_guide.bootstrap');
it('should put angular.fn() in front of dev_guide.overview, etc', function() {
expect(ngdoc.metadata([dev_guide_overview, dev_guide_bootstrap]).map(property('id')))
.toEqual(['dev_guide.overview', 'dev_guide.bootstrap']);
});
});
});
});
describe('markdown', function() {
it('should not replace anything in <pre>, but escape the html escape the content', function() {
expect(new Doc().markdown('bah x\n<pre>\n<b>angular</b>.k\n</pre>\n asdf x')).
toEqual(
'<p>bah x\n' +
'<pre class="prettyprint linenums">\n' +
'<b>angular</b>.k\n' +
'</pre>\n' +
' asdf x</p>');
});
it('should replace text between two <pre></pre> tags', function() {
expect(new Doc().markdown('<pre>x</pre>\n# One\n<pre>b</pre>')).
toMatch('</pre>\n\n<h1 id="one">One</h1>\n\n<pre');
});
it('should replace inline variable type hints', function() {
expect(new Doc().markdown('{@type string}')).
toMatch(/<a\s+.*?class=".*?type-hint type-hint-string.*?".*?>/);
});
it('should ignore nested doc widgets', function() {
expect(new Doc().markdown(
'before<div class="tabbable">\n' +
'<div class="tab-pane well" id="git-mac" ng:model="Git on Mac/Linux">' +
'\ngit bla bla\n</doc:tutorial-instruction>\n' +
'</doc:tutorial-instructions>')).toEqual(
'<p>before<div class="tabbable">\n' +
'<div class="tab-pane well" id="git-mac" ng:model="Git on Mac/Linux">\n' +
'git bla bla\n' +
'</doc:tutorial-instruction>\n' +
'</doc:tutorial-instructions></p>');
});
it('should unindent text before processing based on the second line', function() {
expect(new Doc().markdown('first line\n' +
' second line\n\n' +
' third line\n' +
' fourth line\n\n' +
' fifth line')).
toMatch('<p>first line\n' +
'second line</p>\n\n' +
'<pre><code>third line\n' +
' fourth line\n</code></pre>\n\n' +
'<p>fifth line</p>');
});
it('should unindent text before processing based on the first line', function() {
expect(new Doc().markdown(' first line\n\n' +
' second line\n' +
' third line\n' +
' fourth line\n\n' +
' fifth line')).
toMatch('<p>first line</p>\n\n' +
'<pre><code>second line\n' +
'third line\n' +
' fourth line\n</code></pre>\n\n' +
'<p>fifth line</p>');
});
});
describe('trim', function() {
var trim = ngdoc.trim;
it('should remove leading/trailing space', function() {
expect(trim(' \nabc\n ')).toEqual('abc');
});
it('should remove leading space on every line', function() {
expect(trim('\n 1\n 2\n 3\n')).toEqual('1\n 2\n 3');
});
});
describe('merge', function() {
it('should merge child with parent', function() {
var parent = new Doc({id: 'ng.abc', name: 'ng.abc', section: 'api'});
var methodA = new Doc({name: 'methodA', methodOf: 'ng.abc'});
var methodB = new Doc({name: 'methodB', methodOf: 'ng.abc'});
var propA = new Doc({name: 'propA', propertyOf: 'ng.abc'});
var propB = new Doc({name: 'propB', propertyOf: 'ng.abc'});
var eventA = new Doc({name: 'eventA', eventOf: 'ng.abc'});
var eventB = new Doc({name: 'eventB', eventOf: 'ng.abc'});
var docs = [methodB, methodA, eventB, eventA, propA, propB, parent]; // keep wrong order;
ngdoc.merge(docs);
expect(docs.length).toEqual(1);
expect(docs[0].id).toEqual('ng.abc');
expect(docs[0].methods).toEqual([methodA, methodB]);
expect(docs[0].events).toEqual([eventA, eventB]);
expect(docs[0].properties).toEqual([propA, propB]);
});
describe('links checking', function() {
var docs;
beforeEach(function() {
spyOn(console, 'log');
docs = [new Doc({section: 'api', id: 'fake.id1', links: ['non-existing-link']}),
new Doc({section: 'api', id: 'fake.id2'}),
new Doc({section: 'api', id: 'fake.id3'})];
});
it('should log warning when any link doesn\'t exist', function() {
ngdoc.merge(docs);
expect(console.log).toHaveBeenCalled();
expect(console.log.argsForCall[0][0]).toContain('WARNING:');
});
it('should say which link doesn\'t exist', function() {
ngdoc.merge(docs);
expect(console.log.argsForCall[0][0]).toContain('non-existing-link');
});
it('should say where is the non-existing link', function() {
ngdoc.merge(docs);
expect(console.log.argsForCall[0][0]).toContain('api/fake.id1');
});
});
});
////////////////////////////////////////
describe('TAG', function() {
describe('@param', function() {
it('should parse with no default', function() {
var doc = new Doc('@name a\n@param {(number|string)} number Number \n to format.');
doc.parse();
expect(doc.param).toEqual([{
type : '(number|string)',
name : 'number',
optional: false,
'default' : undefined,
description : '<p>Number \nto format.</p>' }]);
});
it('should parse with default and optional', function() {
var doc = new Doc('@name a\n@param {(number|string)=} [fractionSize=2] desc');
doc.parse();
expect(doc.param).toEqual([{
type : '(number|string)',
name : 'fractionSize',
optional: true,
'default' : '2',
description : '<p>desc</p>' }]);
});
});
describe('@requires', function() {
it('should parse more @requires tag into array', function() {
var doc = new Doc('@name a\n@requires $service for \n`A`\n@requires $another for `B`');
doc.ngdoc = 'service';
doc.parse();
expect(doc.requires).toEqual([
{name:'$service', text:'<p>for \n<code>A</code></p>'},
{name:'$another', text:'<p>for <code>B</code></p>'}]);
expect(doc.html()).toContain('<a href="api/ng.$service">$service</a>');
expect(doc.html()).toContain('<a href="api/ng.$another">$another</a>');
expect(doc.html()).toContain('<p>for \n<code>A</code></p>');
expect(doc.html()).toContain('<p>for <code>B</code></p>');
});
});
describe('@scope', function() {
it('should state the new scope will be created', function() {
var doc = new Doc('@name a\n@scope');
doc.ngdoc = 'directive';
doc.parse();
expect(doc.scope).toEqual('');
expect(doc.html()).toContain('This directive creates new scope.');
});
});
describe('@priority', function() {
it('should state the priority', function() {
var doc = new Doc('@name a\n@priority 123');
doc.ngdoc = 'directive';
doc.parse();
expect(doc.priority).toEqual('123');
expect(doc.html()).toContain('This directive executes at priority level 123.');
});
});
describe('@property', function() {
it('should parse @property tags into array', function() {
var doc = new Doc("@name a\n@property {type} name1 desc\n@property {type} name2 desc");
doc.parse();
expect(doc.properties.length).toEqual(2);
});
it('should not parse @property without a type', function() {
var doc = new Doc("@property fake", 'test.js', '44');
expect(function() { doc.parse(); }).
toThrow(new Error("Not a valid 'property' format: fake (found in: test.js:44)"));
});
it('should parse @property with type', function() {
var doc = new Doc("@name a\n@property {string} name");
doc.parse();
expect(doc.properties[0].name).toEqual('name');
expect(doc.properties[0].type).toEqual('string');
});
it('should parse @property with optional description', function() {
var doc = new Doc("@name a\n@property {string} name desc rip tion");
doc.parse();
expect(doc.properties[0].name).toEqual('name');
expect(doc.properties[0].description).toEqual('<p>desc rip tion</p>');
});
it('should parse @property with type and description both', function() {
var doc = new Doc("@name a\n@property {bool} name desc rip tion");
doc.parse();
expect(doc.properties[0].name).toEqual('name');
expect(doc.properties[0].type).toEqual('bool');
expect(doc.properties[0].description).toEqual('<p>desc rip tion</p>');
});
});
describe('@returns', function() {
it('should not parse @returns without type', function() {
var doc = new Doc("@returns lala");
expect(function() { doc.parse(); }).
toThrow();
});
it('should not parse @returns with invalid type', function() {
var doc = new Doc("@returns {xx}x} lala", 'test.js', 34);
expect(function() { doc.parse(); }).
toThrow(new Error("Not a valid 'returns' format: {xx}x} lala (found in: test.js:34)"));
});
it('should parse @returns with type and description', function() {
var doc = new Doc("@name a\n@returns {string} descrip tion");
doc.parse();
expect(doc.returns).toEqual({type: 'string', description: '<p>descrip tion</p>'});
});
it('should parse @returns with complex type and description', function() {
var doc = new Doc("@name a\n@returns {function(string, number=)} description");
doc.parse();
expect(doc.returns).toEqual({type: 'function(string, number=)', description: '<p>description</p>'});
});
it('should transform description of @returns with markdown', function() {
var doc = new Doc("@name a\n@returns {string} descrip *tion*");
doc.parse();
expect(doc.returns).toEqual({type: 'string', description: '<p>descrip <em>tion</em></p>'});
});
it('should support multiline content', function() {
var doc = new Doc("@name a\n@returns {string} description\n new line\n another line");
doc.parse();
expect(doc.returns).
toEqual({type: 'string', description: '<p>description\nnew line\nanother line</p>'});
});
});
describe('@description', function() {
it('should support pre blocks', function() {
var doc = new Doc("@name a\n@description <pre><b>abc</b></pre>");
doc.parse();
expect(doc.description).
toBe('<pre class="prettyprint linenums"><b>abc</b></pre>');
});
it('should support multiple pre blocks', function() {
var doc = new Doc("@name a\n@description foo \n<pre>abc</pre>\n#bah\nfoo \n<pre>cba</pre>");
doc.parse();
expect(doc.description).
toBe('<p>foo \n' +
'<pre class="prettyprint linenums">abc</pre>\n\n' +
'<h1 id="bah">bah</h1>\n\n' +
'<p>foo \n' +
'<pre class="prettyprint linenums">cba</pre>');
});
it('should support nested @link annotations with or without description', function() {
var doc = new Doc("@name a\n@description " +
'foo {@link angular.foo}\n\n da {@link angular.foo bar foo bar } \n\n' +
'dad{@link angular.foo}\n\n' +
'external{@link http://angularjs.org}\n\n' +
'external{@link ./static.html}\n\n' +
'{@link angular.directive.ng-foo ng:foo}');
doc.section = 'api';
doc.parse();
expect(doc.description).
toContain('foo <a href="api/angular.foo"><code>angular.foo</code></a>');
expect(doc.description).
toContain('da <a href="api/angular.foo"><code>bar foo bar</code></a>');
expect(doc.description).
toContain('dad<a href="api/angular.foo"><code>angular.foo</code></a>');
expect(doc.description).
toContain('<a href="api/angular.directive.ng-foo"><code>ng:foo</code></a>');
expect(doc.description).
toContain('<a href="http://angularjs.org">http://angularjs.org</a>');
expect(doc.description).
toContain('<a href="./static.html">./static.html</a>');
});
it('should support line breaks in @link', function() {
var doc = new Doc("@name a\n@description " +
'{@link\napi/angular.foo\na\nb}');
doc.parse();
expect(doc.description).
toContain('<a href="api/angular.foo"><code>a b</code></a>');
});
});
describe('@example', function() {
it('should not remove {{}}', function() {
var doc = new Doc('@name a\n@example text {{ abc }}');
doc.parse();
expect(doc.example).toEqual('<p>text {{ abc }}</p>');
});
});
describe('@deprecated', function() {
it('should parse @deprecated', function() {
var doc = new Doc('@name a\n@deprecated Replaced with foo.');
doc.parse();
expect(doc.deprecated).toBe('Replaced with foo.');
});
});
describe('@this', function() {
it('should render @this', function() {
var doc = new Doc('@name a\n@this I am self.');
doc.ngdoc = 'filter';
doc.parse();
expect(doc.html()).toContain('<h3>Method\'s <code>this</code></h3>\n' +
'<div>' +
'<p>I am self.</p>' +
'</div>\n');
expect(doc.html()).toContain('<h3>Method\'s <code>this</code></h3>\n' +
'<div><p>I am self.</p></div>');
});
});
describe('@animations', function() {
it('should render @this', function() {
var doc = new Doc('@name a\n@animations\nenter - Add text\nleave - Remove text\n');
doc.ngdoc = 'filter';
doc.parse();
expect(doc.html()).toContain(
'<h3 id="Animations">Animations</h3>\n' +
'<div class="animations">' +
'<ul>' +
'<li>enter - Add text</li>' +
'<li>leave - Remove text</li>' +
'</ul>' +
'</div>');
});
});
});
describe('usage', function() {
describe('overview', function() {
it('should supress description heading', function() {
var doc = new Doc('@ngdoc overview\n@name angular\n@description\n#heading\ntext');
doc.parse();
expect(doc.html()).toContain('text');
expect(doc.html()).toContain('<h2 id="heading">heading</h2>');
expect(doc.html()).not.toContain('Description');
});
});
describe('function', function() {
it('should format', function() {
var doc = new Doc({
ngdoc:'function',
name:'some.name',
param: [
{name:'a', type: 'string', optional: true},
{name:'b', type: 'someType', optional: true, 'default': '"xxx"'},
{name:'c', type: 'string', description: 'param desc'}
],
returns: {type: 'number', description: 'return desc'}
});
doc.html_usage_function(dom);
expect(dom).toContain('name([a][, b], c)'); //TODO(i) the comma position here is lame
expect(dom).toContain('param desc');
expect(dom).toContain('(optional)');
expect(dom).toContain('return desc');
});
});
describe('filter', function() {
it('should format', function() {
var doc = new Doc({
ngdoc:'formatter',
shortName:'myFilter',
param: [
{name:'a', type:'string'},
{name:'b', type:'string'}
]
});
doc.html_usage_filter(dom);
expect(dom).toContain('myFilter_expression | myFilter:b');
expect(dom).toContain('$filter(\'myFilter\')(a, b)');
});
});
describe('property', function() {
it('should format', function() {
var doc = new Doc({
ngdoc:'property',
name:'myProp',
type:'string',
returns:{type: 'type', description: 'description'}
});
doc.html_usage_property(dom);
expect(dom).toContain('myProp');
expect(dom).toContain('type');
expect(dom).toContain('description');
});
});
});
});
| Ore4444/angular.js | docs/spec/ngdocSpec.js | JavaScript | mit | 21,003 |
"use strict";
/**
* Copyright 2017 Google Inc.
*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("@firebase/util");
var Change_1 = require("./Change");
var util_2 = require("@firebase/util");
/**
* @constructor
*/
var ChildChangeAccumulator = /** @class */ (function () {
function ChildChangeAccumulator() {
this.changeMap_ = {};
}
/**
* @param {!Change} change
*/
ChildChangeAccumulator.prototype.trackChildChange = function (change) {
var type = change.type;
var childKey /** @type {!string} */ = change.childName;
util_2.assert(type == Change_1.Change.CHILD_ADDED ||
type == Change_1.Change.CHILD_CHANGED ||
type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');
util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
var oldChange = util_1.safeGet(this.changeMap_, childKey);
if (oldChange) {
var oldType = oldChange.type;
if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {
this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);
}
else if (type == Change_1.Change.CHILD_REMOVED &&
oldType == Change_1.Change.CHILD_ADDED) {
delete this.changeMap_[childKey];
}
else if (type == Change_1.Change.CHILD_REMOVED &&
oldType == Change_1.Change.CHILD_CHANGED) {
this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);
}
else if (type == Change_1.Change.CHILD_CHANGED &&
oldType == Change_1.Change.CHILD_ADDED) {
this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);
}
else if (type == Change_1.Change.CHILD_CHANGED &&
oldType == Change_1.Change.CHILD_CHANGED) {
this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);
}
else {
throw util_2.assertionError('Illegal combination of changes: ' +
change +
' occurred after ' +
oldChange);
}
}
else {
this.changeMap_[childKey] = change;
}
};
/**
* @return {!Array.<!Change>}
*/
ChildChangeAccumulator.prototype.getChanges = function () {
return util_1.getValues(this.changeMap_);
};
return ChildChangeAccumulator;
}());
exports.ChildChangeAccumulator = ChildChangeAccumulator;
//# sourceMappingURL=ChildChangeAccumulator.js.map
| aggiedefenders/aggiedefenders.github.io | node_modules/@firebase/database/dist/cjs/src/core/view/ChildChangeAccumulator.js | JavaScript | mit | 3,422 |
/**
@module ember
@submodule ember-testing
*/
import { checkWaiters } from '../test/waiters';
import { RSVP } from 'ember-runtime';
import { run } from 'ember-metal';
import { pendingRequests } from '../test/pending_requests';
/**
Causes the run loop to process any pending events. This is used to ensure that
any async operations from other helpers (or your assertions) have been processed.
This is most often used as the return value for the helper functions (see 'click',
'fillIn','visit',etc).
Example:
```javascript
Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) {
visit('secured/path/here')
.fillIn('#username', username)
.fillIn('#password', password)
.click('.submit')
return app.testHelpers.wait();
});
@method wait
@param {Object} value The value to be returned.
@return {RSVP.Promise}
@public
*/
export default function wait(app, value) {
return new RSVP.Promise(function(resolve) {
let router = app.__container__.lookup('router:main');
// Every 10ms, poll for the async thing to have finished
let watcher = setInterval(() => {
// 1. If the router is loading, keep polling
let routerIsLoading = router.router && !!router.router.activeTransition;
if (routerIsLoading) { return; }
// 2. If there are pending Ajax requests, keep polling
if (pendingRequests()) { return; }
// 3. If there are scheduled timers or we are inside of a run loop, keep polling
if (run.hasScheduledTimers() || run.currentRunLoop) { return; }
if (checkWaiters()) {
return;
}
// Stop polling
clearInterval(watcher);
// Synchronously resolve the promise
run(null, resolve, value);
}, 10);
});
}
| rfsv/ember.js | packages/ember-testing/lib/helpers/wait.js | JavaScript | mit | 1,768 |
var mappings = {
getIndices: function() {
return ['foo', 'bar', 'qux'];
},
getTypes: function(index) {
return {
foo: ['foobar'],
bar: ['baz', 'qux'],
qux: ['bar']
}[index];
}
};
test("Autocomplete first part of path", function() {
var suggest = new URLAutocomplete(mappings);
deepEqual(suggest.getAlternatives('f'), [ "_msearch", "_search", "_suggest", "bar", "foo", "qux" ], 'First part suggest');
});
test("Autocomplete second part of path", function() {
var suggest = new URLAutocomplete(mappings);
deepEqual(suggest.getAlternatives('foo/'), [ "foo/_msearch", "foo/_search", "foo/_suggest", "foo/foobar" ], 'Second prt suggest foo/');
deepEqual(suggest.getAlternatives('foo/f'), [ "foo/_msearch", "foo/_search", "foo/_suggest", "foo/foobar" ], 'Second part suggest foo/f');
deepEqual(suggest.getAlternatives('_search/'), [ "_search/exists", "_search/template" ], 'Second part suggest _search/');
});
test("Autocomplete third part of path", function() {
var suggest = new URLAutocomplete(mappings);
deepEqual(suggest.getAlternatives('foo/foobar/'), [ "foo/foobar/_msearch", "foo/foobar/_search" ], 'Third part suggest foo/foobar/');
deepEqual(suggest.getAlternatives('foo/_search/'), [ "foo/_search/exists", "foo/_search/template" ], 'Third part suggest foo/_search/');
});
test("Autocomplete fourth part of path", function() {
var suggest = new URLAutocomplete(mappings);
deepEqual(suggest.getAlternatives('bar/baz/_search/'), [ "bar/baz/_search/exists", "bar/baz/_search/template" ], 'Third part suggest bar/baz/_search');
deepEqual(suggest.getAlternatives('qux/bar/_msearch/'), [ "qux/bar/_msearch/template" ], 'Third part suggest qux/bar/_msearch');
}); | lmenezes/elasticsearch-kopf | tests/models/url_autocomplete.js | JavaScript | mit | 1,726 |
/**
* @module drivshare-gui/updater
*/
'use strict';
const about = require('../package');
const {EventEmitter} = require('events');
const request = require('request');
const assert = require('assert');
const semver = require('semver');
class Updater extends EventEmitter {
constructor() {
super();
}
/**
* Fetches remote package metadata and determines if update is available
*/
checkForUpdates() {
const self = this;
const options = {
url: 'https://api.github.com/repos/Storj/storjshare-gui/releases/latest',
headers: { 'User-Agent': 'storj/storjshare-gui' },
json: true
};
request(options, function(err, res, body) {
if (err || res.statusCode !== 200) {
return self.emit('error', err || new Error('Failed to check updates'));
}
try {
self._validateResponse(body);
} catch (err) {
return self.emit('error', new Error('Failed to parse update info'));
}
var meta = {
releaseTag: body.tag_name,
releaseURL: body.html_url
};
if (semver.lt(about.version, meta.releaseTag)) {
self.emit('update_available', meta);
}
});
}
/**
* Validates the response body from version check
* @param {Object} body
*/
_validateResponse(body) {
assert(typeof body === 'object');
assert(typeof body.html_url === 'string');
assert(typeof body.tag_name === 'string');
}
}
module.exports = new Updater();
| Storj/driveshare-gui | app/lib/updater.js | JavaScript | mit | 1,478 |
var check = require('./lib/util/check')
var extend = require('./lib/util/extend')
var dynamic = require('./lib/dynamic')
var raf = require('./lib/util/raf')
var clock = require('./lib/util/clock')
var createStringStore = require('./lib/strings')
var initWebGL = require('./lib/webgl')
var wrapExtensions = require('./lib/extension')
var wrapLimits = require('./lib/limits')
var wrapBuffers = require('./lib/buffer')
var wrapElements = require('./lib/elements')
var wrapTextures = require('./lib/texture')
var wrapRenderbuffers = require('./lib/renderbuffer')
var wrapFramebuffers = require('./lib/framebuffer')
var wrapAttributes = require('./lib/attribute')
var wrapShaders = require('./lib/shader')
var wrapRead = require('./lib/read')
var createCore = require('./lib/core')
var createStats = require('./lib/stats')
var createTimer = require('./lib/timer')
var GL_COLOR_BUFFER_BIT = 16384
var GL_DEPTH_BUFFER_BIT = 256
var GL_STENCIL_BUFFER_BIT = 1024
var GL_ARRAY_BUFFER = 34962
var CONTEXT_LOST_EVENT = 'webglcontextlost'
var CONTEXT_RESTORED_EVENT = 'webglcontextrestored'
var DYN_PROP = 1
var DYN_CONTEXT = 2
var DYN_STATE = 3
function find (haystack, needle) {
for (var i = 0; i < haystack.length; ++i) {
if (haystack[i] === needle) {
return i
}
}
return -1
}
module.exports = function wrapREGL (args) {
var config = initWebGL(args)
if (!config) {
return null
}
var gl = config.gl
var glAttributes = gl.getContextAttributes()
var contextLost = gl.isContextLost()
var extensionState = wrapExtensions(gl, config)
if (!extensionState) {
return null
}
var stringStore = createStringStore()
var stats = createStats()
var extensions = extensionState.extensions
var timer = createTimer(gl, extensions)
var START_TIME = clock()
var WIDTH = gl.drawingBufferWidth
var HEIGHT = gl.drawingBufferHeight
var contextState = {
tick: 0,
time: 0,
viewportWidth: WIDTH,
viewportHeight: HEIGHT,
framebufferWidth: WIDTH,
framebufferHeight: HEIGHT,
drawingBufferWidth: WIDTH,
drawingBufferHeight: HEIGHT,
pixelRatio: config.pixelRatio
}
var uniformState = {}
var drawState = {
elements: null,
primitive: 4, // GL_TRIANGLES
count: -1,
offset: 0,
instances: -1
}
var limits = wrapLimits(gl, extensions)
var bufferState = wrapBuffers(gl, stats, config)
var elementState = wrapElements(gl, extensions, bufferState, stats)
var attributeState = wrapAttributes(
gl,
extensions,
limits,
bufferState,
stringStore)
var shaderState = wrapShaders(gl, stringStore, stats, config)
var textureState = wrapTextures(
gl,
extensions,
limits,
function () { core.procs.poll() },
contextState,
stats,
config)
var renderbufferState = wrapRenderbuffers(gl, extensions, limits, stats, config)
var framebufferState = wrapFramebuffers(
gl,
extensions,
limits,
textureState,
renderbufferState,
stats)
var core = createCore(
gl,
stringStore,
extensions,
limits,
bufferState,
elementState,
textureState,
framebufferState,
uniformState,
attributeState,
shaderState,
drawState,
contextState,
timer,
config)
var readPixels = wrapRead(
gl,
framebufferState,
core.procs.poll,
contextState,
glAttributes, extensions)
var nextState = core.next
var canvas = gl.canvas
var rafCallbacks = []
var lossCallbacks = []
var restoreCallbacks = []
var destroyCallbacks = [config.onDestroy]
var activeRAF = null
function handleRAF () {
if (rafCallbacks.length === 0) {
if (timer) {
timer.update()
}
activeRAF = null
return
}
// schedule next animation frame
activeRAF = raf.next(handleRAF)
// poll for changes
poll()
// fire a callback for all pending rafs
for (var i = rafCallbacks.length - 1; i >= 0; --i) {
var cb = rafCallbacks[i]
if (cb) {
cb(contextState, null, 0)
}
}
// flush all pending webgl calls
gl.flush()
// poll GPU timers *after* gl.flush so we don't delay command dispatch
if (timer) {
timer.update()
}
}
function startRAF () {
if (!activeRAF && rafCallbacks.length > 0) {
activeRAF = raf.next(handleRAF)
}
}
function stopRAF () {
if (activeRAF) {
raf.cancel(handleRAF)
activeRAF = null
}
}
function handleContextLoss (event) {
event.preventDefault()
// set context lost flag
contextLost = true
// pause request animation frame
stopRAF()
// lose context
lossCallbacks.forEach(function (cb) {
cb()
})
}
function handleContextRestored (event) {
// clear error code
gl.getError()
// clear context lost flag
contextLost = false
// refresh state
extensionState.restore()
shaderState.restore()
bufferState.restore()
textureState.restore()
renderbufferState.restore()
framebufferState.restore()
if (timer) {
timer.restore()
}
// refresh state
core.procs.refresh()
// restart RAF
startRAF()
// restore context
restoreCallbacks.forEach(function (cb) {
cb()
})
}
if (canvas) {
canvas.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false)
canvas.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false)
}
function destroy () {
rafCallbacks.length = 0
stopRAF()
if (canvas) {
canvas.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss)
canvas.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored)
}
shaderState.clear()
framebufferState.clear()
renderbufferState.clear()
textureState.clear()
elementState.clear()
bufferState.clear()
if (timer) {
timer.clear()
}
destroyCallbacks.forEach(function (cb) {
cb()
})
}
function compileProcedure (options) {
check(!!options, 'invalid args to regl({...})')
check.type(options, 'object', 'invalid args to regl({...})')
function flattenNestedOptions (options) {
var result = extend({}, options)
delete result.uniforms
delete result.attributes
delete result.context
if ('stencil' in result && result.stencil.op) {
result.stencil.opBack = result.stencil.opFront = result.stencil.op
delete result.stencil.op
}
function merge (name) {
if (name in result) {
var child = result[name]
delete result[name]
Object.keys(child).forEach(function (prop) {
result[name + '.' + prop] = child[prop]
})
}
}
merge('blend')
merge('depth')
merge('cull')
merge('stencil')
merge('polygonOffset')
merge('scissor')
merge('sample')
return result
}
function separateDynamic (object) {
var staticItems = {}
var dynamicItems = {}
Object.keys(object).forEach(function (option) {
var value = object[option]
if (dynamic.isDynamic(value)) {
dynamicItems[option] = dynamic.unbox(value, option)
} else {
staticItems[option] = value
}
})
return {
dynamic: dynamicItems,
static: staticItems
}
}
// Treat context variables separate from other dynamic variables
var context = separateDynamic(options.context || {})
var uniforms = separateDynamic(options.uniforms || {})
var attributes = separateDynamic(options.attributes || {})
var opts = separateDynamic(flattenNestedOptions(options))
var stats = {
gpuTime: 0.0,
cpuTime: 0.0,
count: 0
}
var compiled = core.compile(opts, attributes, uniforms, context, stats)
var draw = compiled.draw
var batch = compiled.batch
var scope = compiled.scope
// FIXME: we should modify code generation for batch commands so this
// isn't necessary
var EMPTY_ARRAY = []
function reserve (count) {
while (EMPTY_ARRAY.length < count) {
EMPTY_ARRAY.push(null)
}
return EMPTY_ARRAY
}
function REGLCommand (args, body) {
var i
if (contextLost) {
check.raise('context lost')
}
if (typeof args === 'function') {
return scope.call(this, null, args, 0)
} else if (typeof body === 'function') {
if (typeof args === 'number') {
for (i = 0; i < args; ++i) {
scope.call(this, null, body, i)
}
return
} else if (Array.isArray(args)) {
for (i = 0; i < args.length; ++i) {
scope.call(this, args[i], body, i)
}
return
} else {
return scope.call(this, args, body, 0)
}
} else if (typeof args === 'number') {
if (args > 0) {
return batch.call(this, reserve(args | 0), args | 0)
}
} else if (Array.isArray(args)) {
if (args.length) {
return batch.call(this, args, args.length)
}
} else {
return draw.call(this, args)
}
}
return extend(REGLCommand, {
stats: stats
})
}
var setFBO = framebufferState.setFBO = compileProcedure({
framebuffer: dynamic.define.call(null, DYN_PROP, 'framebuffer')
})
function clearImpl (_, options) {
var clearFlags = 0
core.procs.poll()
var c = options.color
if (c) {
gl.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0)
clearFlags |= GL_COLOR_BUFFER_BIT
}
if ('depth' in options) {
gl.clearDepth(+options.depth)
clearFlags |= GL_DEPTH_BUFFER_BIT
}
if ('stencil' in options) {
gl.clearStencil(options.stencil | 0)
clearFlags |= GL_STENCIL_BUFFER_BIT
}
check(!!clearFlags, 'called regl.clear with no buffer specified')
gl.clear(clearFlags)
}
function clear (options) {
check(
typeof options === 'object' && options,
'regl.clear() takes an object as input')
if ('framebuffer' in options) {
if (options.framebuffer &&
options.framebuffer_reglType === 'framebufferCube') {
for (var i = 0; i < 6; ++i) {
setFBO(extend({
framebuffer: options.framebuffer.faces[i]
}, options), clearImpl)
}
} else {
setFBO(options, clearImpl)
}
} else {
clearImpl(null, options)
}
}
function frame (cb) {
check.type(cb, 'function', 'regl.frame() callback must be a function')
rafCallbacks.push(cb)
function cancel () {
// FIXME: should we check something other than equals cb here?
// what if a user calls frame twice with the same callback...
//
var i = find(rafCallbacks, cb)
check(i >= 0, 'cannot cancel a frame twice')
function pendingCancel () {
var index = find(rafCallbacks, pendingCancel)
rafCallbacks[index] = rafCallbacks[rafCallbacks.length - 1]
rafCallbacks.length -= 1
if (rafCallbacks.length <= 0) {
stopRAF()
}
}
rafCallbacks[i] = pendingCancel
}
startRAF()
return {
cancel: cancel
}
}
// poll viewport
function pollViewport () {
var viewport = nextState.viewport
var scissorBox = nextState.scissor_box
viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0
contextState.viewportWidth =
contextState.framebufferWidth =
contextState.drawingBufferWidth =
viewport[2] =
scissorBox[2] = gl.drawingBufferWidth
contextState.viewportHeight =
contextState.framebufferHeight =
contextState.drawingBufferHeight =
viewport[3] =
scissorBox[3] = gl.drawingBufferHeight
}
function poll () {
contextState.tick += 1
contextState.time = now()
pollViewport()
core.procs.poll()
}
function refresh () {
pollViewport()
core.procs.refresh()
if (timer) {
timer.update()
}
}
function now () {
return (clock() - START_TIME) / 1000.0
}
refresh()
function addListener (event, callback) {
check.type(callback, 'function', 'listener callback must be a function')
var callbacks
switch (event) {
case 'frame':
return frame(callback)
case 'lost':
callbacks = lossCallbacks
break
case 'restore':
callbacks = restoreCallbacks
break
case 'destroy':
callbacks = destroyCallbacks
break
default:
check.raise('invalid event, must be one of frame,lost,restore,destroy')
}
callbacks.push(callback)
return {
cancel: function () {
for (var i = 0; i < callbacks.length; ++i) {
if (callbacks[i] === callback) {
callbacks[i] = callbacks[callbacks.length - 1]
callbacks.pop()
return
}
}
}
}
}
var regl = extend(compileProcedure, {
// Clear current FBO
clear: clear,
// Short cuts for dynamic variables
prop: dynamic.define.bind(null, DYN_PROP),
context: dynamic.define.bind(null, DYN_CONTEXT),
this: dynamic.define.bind(null, DYN_STATE),
// executes an empty draw command
draw: compileProcedure({}),
// Resources
buffer: function (options) {
return bufferState.create(options, GL_ARRAY_BUFFER, false, false)
},
elements: function (options) {
return elementState.create(options, false)
},
texture: textureState.create2D,
cube: textureState.createCube,
renderbuffer: renderbufferState.create,
framebuffer: framebufferState.create,
framebufferCube: framebufferState.createCube,
// Expose context attributes
attributes: glAttributes,
// Frame rendering
frame: frame,
on: addListener,
// System limits
limits: limits,
hasExtension: function (name) {
return limits.extensions.indexOf(name.toLowerCase()) >= 0
},
// Read pixels
read: readPixels,
// Destroy regl and all associated resources
destroy: destroy,
// Direct GL state manipulation
_gl: gl,
_refresh: refresh,
poll: function () {
poll()
if (timer) {
timer.update()
}
},
// Current time
now: now,
// regl Statistics Information
stats: stats
})
config.onDone(null, regl)
return regl
}
| mikolalysenko/regl | regl.js | JavaScript | mit | 14,415 |
var env = require('./environment.js');
// Smoke tests to be run on CI servers - covers more browsers than
// ciConf.js, but does not run all tests.
exports.config = {
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
SELENIUM_PROMISE_MANAGER: false,
framework: 'jasmine',
specs: [
// TODO(selenium4): revert back. For now just put on lib_spec.js
// 'basic/locators_spec.js',
// 'basic/mockmodule_spec.js',
// 'basic/synchronize_spec.js'
'basic/lib_spec.js'
],
// Two latest versions of IE, and Safari.
// The second latest version of Chrome and Firefox (latest versions are
// tested against the full suite in ciFullConf)
// TODO - add mobile.
multiCapabilities: [{
'browserName': 'chrome',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER,
'name': 'Protractor smoke tests',
'version': '55',
'chromedriver-version': '2.27',
'platform': 'OS X 10.11'
}, {
'browserName': 'firefox',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER,
'name': 'Protractor smoke tests',
'version': 'beta'
}, {
// TODO: Add Safari 10 once Saucelabs gets Selenium 3
'browserName': 'safari',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER,
'name': 'Protractor smoke tests',
'version': '9',
}, {
'browserName': 'MicrosoftEdge',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER,
'name': 'Protractor smoke tests',
'version': '14.14393',
'platform': 'Windows 10'
}, {
'browserName': 'Internet Explorer',
'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
'build': process.env.TRAVIS_BUILD_NUMBER,
'name': 'Protractor smoke tests',
'version': '11',
'platform': 'Windows 8.1'
}],
baseUrl: env.baseUrl + '/ng1/',
// Up the timeouts for the slower browsers (IE, Safari).
allScriptsTimeout: 120000,
getPageTimeout: 120000,
jasmineNodeOpts: {
showTiming: true,
defaultTimeoutInterval: 120000
},
params: {
login: {
user: 'Jane',
password: '1234'
}
}
};
| mgiambalvo/protractor | spec/ciSmokeConf.js | JavaScript | mit | 2,248 |
$(function () {
$(".help-block").effect( "pulsate", {times:7}, 10000 );
$('#flashdatas .alert').delay(5000).slideUp('fast');
if ($("#search_page_ajax").length > 0) {
$("#search_page_ajax").autocomplete({
minLength: 2,
scrollHeight: 220,
source: function(req, add) {
return $.ajax({
url: $("#search_page_ajax").attr('data-url'),
type: "get",
dataType: "json",
data: "word=" + req.term,
async: true,
cache: true,
success: function(data) {
return add($.map(data, function(item) {
return {
nom: item.nom,
url: item.url
};
}));
}
});
},
focus: function(event, ui) {
$(this).val(ui.item.nom);
return false;
},
select: function(event, ui) {
window.location.href = ui.item.url;
return false;
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li></li>").data("ui-autocomplete-item", item).append("<a href=\"" + item.url + "\">" + item.nom + "</span></a>").appendTo(ul.addClass("list-row"));
};
}
if ($("#search_input").length > 0) {
$("#search_input").autocomplete({
minLength: 2,
scrollHeight: 220,
source: function(req, add) {
return $.ajax({
url: $("#search_input").attr('data-url'),
type: "get",
dataType: "json",
data: "word=" + req.term,
async: true,
cache: true,
success: function(data) {
return add($.map(data, function(item) {
return {
nom: item.nom,
url: item.url
};
}));
}
});
},
focus: function(event, ui) {
$(this).val(ui.item.nom);
return false;
},
select: function(event, ui) {
window.location.href = ui.item.url;
return false;
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li></li>").data("ui-autocomplete-item", item).append("<a href=\"" + item.url + "\">" + item.nom + "</span></a>").appendTo(ul.addClass("list-row"));
};
}
/*
$('#Cinhetic_publicbundle_actors_city').autocomplete({
source : function(requete, reponse){ // les deux arguments représentent les données nécessaires au plugin
$.ajax({
url : 'http://ws.geonames.org/searchJSON', // on appelle le script JSON
dataType : 'json', // on spécifie bien que le type de données est en JSON
data : {
name_startsWith : $('#Cinhetic_publicbundle_actors_city').val(), // on donne la chaîne de caractère tapée dans le champ de recherche
maxRows : 15
},
success : function(donnee){
reponse($.map(donnee.geonames, function(objet){
return objet.name + ', ' + objet.countryName; // on retourne cette forme de suggestion
}));
}
});
}
});
*/
$(window).scroll(function () {
if ($(document).scrollTop() >= 100) {
return $('body .navbar-default').stop(true, true).animate({
opacity: 0.8
});
} else {
return $('body .navbar-default').stop(true, true).animate({
opacity: 1
});
}
});
$("body .navbar-default").hover((function () {
return $(this).stop(true, true).animate({
opacity: 1
});
}), function () {
if ($(document).scrollTop() >= 100) {
return $('body .navbar-default').stop(true, true).animate({
opacity: 0.8
});
}
});
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp(str, "gi");
return this.each(function () {
$(this).contents().filter(function() {
return this.nodeType == 3 && regex.test(this.nodeValue);
}).replaceWith(function() {
return (this.nodeValue || "").replace(regex, function(match) {
return "<span class=\"" + className + "\">" + match + "</span>";
});
});
});
};
var search = $('#search_input').val();
$('#search_input').parents("#listmovies *").highlight(search, "highlight");
$('.favoris_link').click(function (evt) {
$obj = $(this);
$.ajax({
url: $(this).attr('data-url'),
type: "get",
dataType: "json",
success: function (data) {
if($obj.find('i').hasClass('fa-star')){
$obj.find('i').attr('class','fa fa-star-o');
$('#main-navbar-collapse .right-navbar-nav li:eq(0)').effect( "pulsate", {times:10}, 3000 );
}else{
$obj.find('i').attr('class','fa fa-star');
$('#main-navbar-collapse .right-navbar-nav li:eq(0)').effect( "pulsate", {times:10}, 3000 );
}
}
});
});
$('.ishome').click(function (evt) {
$obj = $(this);
$.ajax({
url: $(this).attr('data-url'),
type: "get",
dataType: "json",
success: function (data) {
if($obj.hasClass('athome')){
$obj.find('i').attr('class','pull-left glyphicon glyphicon-heart-empty');
}else{
$obj.find('i').attr('class','pull-left glyphicon glyphicon-heart');
}
}
});
});
$('#moresearch').click(function () {
return $('#advancedsearch').toggleClass('hide', '');
});
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
$('form').on("submit", function (event) {
$(this).find('button[type=submit]').attr('disabled', 'disabled');
$(this).find('button[type=submit]').text('Envoi en cours...');
return $('#overlay').removeClass('hide');
});
$("input[required]").on("blur", function (event) {
if ($(this).val().length == 0 && $(this).val() == "") {
return $(this).addClass('parsley-error');
}
});
$("input[required]").on("keydown", function (event) {
return $(this).removeClass('parsley-error');
});
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
return $(".scrollup").fadeIn();
} else {
return $(".scrollup").fadeOut();
}
});
return $(".scrollup").click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
$('.alert-success').delay(5000).slideUp('fast');
});
| Symfomany/cinhetic | web/js/a2646bf_main_1.js | JavaScript | mit | 7,492 |
(function () {
var pagebreak = (function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
var getSeparatorHtml = function (editor) {
return editor.getParam('pagebreak_separator', '<!-- pagebreak -->');
};
var shouldSplitBlock = function (editor) {
return editor.getParam('pagebreak_split_block', false);
};
var $_1hv0yhhmjh8lpvdi = {
getSeparatorHtml: getSeparatorHtml,
shouldSplitBlock: shouldSplitBlock
};
var getPageBreakClass = function () {
return 'mce-pagebreak';
};
var getPlaceholderHtml = function () {
return '<img src="' + global$1.transparentSrc + '" class="' + getPageBreakClass() + '" data-mce-resize="false" data-mce-placeholder />';
};
var setup = function (editor) {
var separatorHtml = $_1hv0yhhmjh8lpvdi.getSeparatorHtml(editor);
var pageBreakSeparatorRegExp = new RegExp(separatorHtml.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function (a) {
return '\\' + a;
}), 'gi');
editor.on('BeforeSetContent', function (e) {
e.content = e.content.replace(pageBreakSeparatorRegExp, getPlaceholderHtml());
});
editor.on('PreInit', function () {
editor.serializer.addNodeFilter('img', function (nodes) {
var i = nodes.length, node, className;
while (i--) {
node = nodes[i];
className = node.attr('class');
if (className && className.indexOf('mce-pagebreak') !== -1) {
var parentNode = node.parent;
if (editor.schema.getBlockElements()[parentNode.name] && $_1hv0yhhmjh8lpvdi.shouldSplitBlock(editor)) {
parentNode.type = 3;
parentNode.value = separatorHtml;
parentNode.raw = true;
node.remove();
continue;
}
node.type = 3;
node.value = separatorHtml;
node.raw = true;
}
}
});
});
};
var $_55pzfihkjh8lpvdh = {
setup: setup,
getPlaceholderHtml: getPlaceholderHtml,
getPageBreakClass: getPageBreakClass
};
var register = function (editor) {
editor.addCommand('mcePageBreak', function () {
if (editor.settings.pagebreak_split_block) {
editor.insertContent('<p>' + $_55pzfihkjh8lpvdh.getPlaceholderHtml() + '</p>');
} else {
editor.insertContent($_55pzfihkjh8lpvdh.getPlaceholderHtml());
}
});
};
var $_2aoouchjjh8lpvdf = { register: register };
var setup$1 = function (editor) {
editor.on('ResolveName', function (e) {
if (e.target.nodeName === 'IMG' && editor.dom.hasClass(e.target, $_55pzfihkjh8lpvdh.getPageBreakClass())) {
e.name = 'pagebreak';
}
});
};
var $_2mwcs9hnjh8lpvdj = { setup: setup$1 };
var register$1 = function (editor) {
editor.addButton('pagebreak', {
title: 'Page break',
cmd: 'mcePageBreak'
});
editor.addMenuItem('pagebreak', {
text: 'Page break',
icon: 'pagebreak',
cmd: 'mcePageBreak',
context: 'insert'
});
};
var $_61u3l1hojh8lpvdk = { register: register$1 };
global.add('pagebreak', function (editor) {
$_2aoouchjjh8lpvdf.register(editor);
$_61u3l1hojh8lpvdk.register(editor);
$_55pzfihkjh8lpvdh.setup(editor);
$_2mwcs9hnjh8lpvdj.setup(editor);
});
function Plugin () {
}
return Plugin;
}());
})();
| DigitalMomentum/BlogMomentum | UmbracoWebsite/umbraco/lib/tinymce/plugins/pagebreak/plugin.js | JavaScript | mit | 3,427 |
export { default } from './src'
| Dess-Li/vue-el-datatables | index.js | JavaScript | mit | 32 |
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <[email protected]>
* MIT Licensed
*/
/**
* Test dependencies.
*/
var sio = require('../index')
, http = require('http')
, should = require('./common')
, ports = 15100;
/**
* Test.
*/
module.exports = {
'test setting and getting a configuration flag': function (done) {
var port = ++ports
, io = sio.listen(http.createServer());
io.set('a', 'b');
io.get('a').should.eql('b');
var port = ++ports
, io = sio.listen(http.createServer());
io.configure(function () {
io.set('a', 'b');
io.enable('tobi');
});
io.get('a').should.eql('b');
done();
},
'test enabling and disabling a configuration flag': function (done) {
var port = ++ports
, io = sio.listen(http.createServer());
io.enable('flag');
io.enabled('flag').should.be.true;
io.disabled('flag').should.be.false;
io.disable('flag');
var port = ++ports
, io = sio.listen(http.createServer());
io.configure(function () {
io.enable('tobi');
});
io.enabled('tobi').should.be.true;
done();
},
'test configuration callbacks with envs': function (done) {
var port = ++ports
, io = sio.listen(http.createServer());
process.env.NODE_ENV = 'development';
io.configure('production', function () {
io.set('ferret', 'tobi');
});
io.configure('development', function () {
io.set('ferret', 'jane');
});
io.get('ferret').should.eql('jane');
done();
},
'test configuration callbacks conserve scope': function (done) {
var port = ++ports
, io = sio.listen(http.createServer())
, calls = 0;
process.env.NODE_ENV = 'development';
io.configure(function () {
this.should.eql(io);
calls++;
});
io.configure('development', function () {
this.should.eql(io);
calls++;
});
calls.should.eql(2);
done();
},
'test configuration update notifications': function (done) {
var port = ++ports
, io = sio.listen(http.createServer())
, calls = 0;
io.on('set:foo', function () {
calls++;
});
io.set('foo', 'bar');
io.set('baz', 'bar');
calls.should.eql(1);
io.enable('foo');
io.disable('foo');
calls.should.eql(3);
done();
},
'test that normal requests are still served': function (done) {
var server = http.createServer(function (req, res) {
res.writeHead(200);
res.end('woot');
});
var io = sio.listen(server)
, port = ++ports
, cl = client(port);
server.listen(ports);
cl.get('/socket.io', function (res, data) {
res.statusCode.should.eql(200);
data.should.eql('Welcome to socket.io.');
cl.get('/woot', function (res, data) {
res.statusCode.should.eql(200);
data.should.eql('woot');
cl.end();
server.close();
done();
});
});
},
'test that you can disable clients': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.disable('browser client');
});
cl.get('/socket.io/socket.io.js', function (res, data) {
res.statusCode.should.eql(200);
data.should.eql('Welcome to socket.io.');
cl.end();
io.server.close();
done();
});
},
'test handshake': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(200);
data.should.match(/([^:]+):([0-9]+)?:([0-9]+)?:(.+)/);
cl.end();
io.server.close();
done();
});
},
'test handshake with unsupported protocol version': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
cl.get('/socket.io/-1/', function (res, data) {
res.statusCode.should.eql(500);
data.should.match(/Protocol version not supported/);
cl.end();
io.server.close();
done();
});
},
'test authorization failure in handshake': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
function auth (data, fn) {
fn(null, false);
};
io.set('authorization', auth);
});
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(403);
data.should.match(/handshake unauthorized/);
cl.end();
io.server.close();
done();
});
},
'test a handshake error': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
function auth (data, fn) {
fn(new Error);
};
io.set('authorization', auth);
});
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(500);
data.should.match(/handshake error/);
cl.end();
io.server.close();
done();
});
},
'test that a referer is accepted for *:* origin': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('origins', '*:*');
});
cl.get('/socket.io/{protocol}', { headers: { referer: 'http://foo.bar.com:82/something' } }, function (res, data) {
res.statusCode.should.eql(200);
cl.end();
io.server.close();
done();
});
},
'test that valid referer is accepted for addr:* origin': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('origins', 'foo.bar.com:*');
});
cl.get('/socket.io/{protocol}', { headers: { referer: 'http://foo.bar.com/something' } }, function (res, data) {
res.statusCode.should.eql(200);
cl.end();
io.server.close();
done();
});
},
'test that a referer with implicit port 80 is accepted for foo.bar.com:80 origin': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('origins', 'foo.bar.com:80');
});
cl.get('/socket.io/{protocol}', { headers: { referer: 'http://foo.bar.com/something' } }, function (res, data) {
res.statusCode.should.eql(200);
cl.end();
io.server.close();
done();
});
},
'test that erroneous referer is denied for addr:* origin': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('origins', 'foo.bar.com:*');
});
cl.get('/socket.io/{protocol}', { headers: { referer: 'http://baz.bar.com/something' } }, function (res, data) {
res.statusCode.should.eql(403);
cl.end();
io.server.close();
done();
});
},
'test that valid referer port is accepted for addr:port origin': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('origins', 'foo.bar.com:81');
});
cl.get('/socket.io/{protocol}', { headers: { referer: 'http://foo.bar.com:81/something' } }, function (res, data) {
res.statusCode.should.eql(200);
cl.end();
io.server.close();
done();
});
},
'test that erroneous referer port is denied for addr:port origin': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('origins', 'foo.bar.com:81');
});
cl.get('/socket.io/{protocol}', { headers: { referer: 'http://foo.bar.com/something' } }, function (res, data) {
res.statusCode.should.eql(403);
cl.end();
io.server.close();
done();
});
},
'test handshake cross domain access control': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port)
, headers = {
Origin: 'http://example.org:1337'
, Cookie: 'name=value'
};
cl.get('/socket.io/{protocol}/', { headers:headers }, function (res, data) {
res.statusCode.should.eql(200);
res.headers['access-control-allow-origin'].should.eql('http://example.org:1337');
res.headers['access-control-allow-credentials'].should.eql('true');
cl.end();
io.server.close();
done();
});
},
'test limiting the supported transports for a manager': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('transports', ['tobi', 'jane']);
});
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(200);
data.should.match(/([^:]+):([0-9]+)?:([0-9]+)?:tobi,jane/);
cl.end();
io.server.close();
done();
});
},
'test setting a custom close timeout': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('close timeout', 66);
});
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(200);
data.should.match(/([^:]+):([0-9]+)?:66?:(.*)/);
cl.end();
io.server.close();
done();
});
},
'test setting a custom heartbeat timeout': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('heartbeat timeout', 33);
});
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(200);
data.should.match(/([^:]+):33:([0-9]+)?:(.*)/);
cl.end();
io.server.close();
done();
});
},
'test disabling timeouts': function (done) {
var port = ++ports
, io = sio.listen(port)
, cl = client(port);
io.configure(function () {
io.set('heartbeat timeout', null);
io.set('close timeout', '');
});
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(200);
data.should.match(/([^:]+)::?:(.*)/);
cl.end();
io.server.close();
done();
});
},
'test disabling heartbeats': function (done) {
var port = ++ports
, cl = client(port)
, io = create(cl)
, messages = 0
, beat = false
, ws;
io.configure(function () {
io.disable('heartbeats');
io.set('heartbeat interval', .05);
io.set('heartbeat timeout', .05);
io.set('close timeout', .05);
});
io.sockets.on('connection', function (socket) {
setTimeout(function () {
socket.disconnect();
}, io.get('heartbeat timeout') * 1000 + 100);
socket.on('disconnect', function (reason) {
beat.should.be.false;
ws.finishClose();
cl.end();
io.server.close();
done();
});
});
cl.get('/socket.io/{protocol}/', function (res, data) {
res.statusCode.should.eql(200);
data.should.match(/([^:]+)::[\.0-9]+:(.*)/);
cl.handshake(function (sid) {
ws = websocket(cl, sid);
ws.on('message', function (packet) {
if (++messages == 1) {
packet.type.should.eql('connect');
} else if (packet.type == 'heartbeat'){
beat = true;
}
});
});
});
},
'no duplicate room members': function (done) {
var port = ++ports
, io = sio.listen(port);
Object.keys(io.rooms).length.should.equal(0);
io.onJoin(123, 'foo');
io.rooms.foo.length.should.equal(1);
io.onJoin(123, 'foo');
io.rooms.foo.length.should.equal(1);
io.onJoin(124, 'foo');
io.rooms.foo.length.should.equal(2);
io.onJoin(124, 'foo');
io.rooms.foo.length.should.equal(2);
io.onJoin(123, 'bar');
io.rooms.foo.length.should.equal(2);
io.rooms.bar.length.should.equal(1);
io.onJoin(123, 'bar');
io.rooms.foo.length.should.equal(2);
io.rooms.bar.length.should.equal(1);
io.onJoin(124, 'bar');
io.rooms.foo.length.should.equal(2);
io.rooms.bar.length.should.equal(2);
io.onJoin(124, 'bar');
io.rooms.foo.length.should.equal(2);
io.rooms.bar.length.should.equal(2);
process.nextTick(function() {
io.server.close();
done();
});
},
'test passing options directly to the Manager through listen': function (done) {
var port = ++ports
, io = sio.listen(port, { resource: '/my resource', custom: 'opt' });
io.get('resource').should.equal('/my resource');
io.get('custom').should.equal('opt');
process.nextTick(function() {
io.server.close();
done();
});
},
'test disabling the log': function (done) {
var port = ++ports
, io = sio.listen(port, { log: false })
, _console = console.log
, calls = 0;
// the logger uses console.log to output data, override it to see if get's
// used
console.log = function () { ++calls };
io.log.debug('test');
io.log.log('testing');
console.log = _console;
calls.should.equal(0);
process.nextTick(function() {
io.server.close();
done();
});
},
'test disabling logging with colors': function (done) {
var port = ++ports
, io = sio.listen(port, { 'log colors': false })
, _console = console.log
, calls = 0;
// the logger uses console.log to output data, override it to see if get's
// used
console.log = function (data) {
++calls;
data.indexOf('\033').should.equal(-1);
};
io.log.debug('test');
io.log.log('testing');
console.log = _console;
calls.should.equal(2);
process.nextTick(function() {
io.server.close();
done();
});
}
};
| Ronll/chatnow | client/app/bower_components/socket.io/test/manager.test.js | JavaScript | mit | 13,949 |
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _boom = require('boom');
var _boom2 = _interopRequireDefault(_boom);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
var _elasticsearch = require('elasticsearch');
module.exports = function handleESError(error) {
if (!(error instanceof Error)) {
throw new Error('Expected an instance of Error');
}
if (error instanceof _elasticsearch.errors.ConnectionFault || error instanceof _elasticsearch.errors.ServiceUnavailable || error instanceof _elasticsearch.errors.NoConnections || error instanceof _elasticsearch.errors.RequestTimeout) {
return _boom2['default'].serverTimeout(error);
} else if (error instanceof _elasticsearch.errors.Conflict || _lodash2['default'].contains(error.message, 'index_template_already_exists')) {
return _boom2['default'].conflict(error);
} else if (error instanceof _elasticsearch.errors[403]) {
return _boom2['default'].forbidden(error);
} else if (error instanceof _elasticsearch.errors.NotFound) {
return _boom2['default'].notFound(error);
} else if (error instanceof _elasticsearch.errors.BadRequest) {
return _boom2['default'].badRequest(error);
} else {
return error;
}
};
| phupn1510/ELK | kibana/kibana/src/core_plugins/kibana/server/lib/handle_es_error.js | JavaScript | mit | 1,309 |
/**
* @module BaseModel.js
* @author Joe Groseclose <@benderTheCrime>
* @date 8/23/2015
*/
// System Modules
import {cyan} from 'chalk';
import $LogProvider from 'angie-log';
// Angie Modules
import AngieDatabaseRouter from '../databases/AngieDatabaseRouter';
import {
$$InvalidModelFieldReferenceError
} from '../util/$ExceptionsProvider';
const IGNORE_KEYS = [
'database',
'$$database',
'model',
'name',
'fields',
'rows',
'update',
'first',
'last'
];
class BaseModel {
constructor(name) {
this.name = this.name || name;
}
all(args = {}) {
args.model = this;
// Returns all of the rows
return this.$$prep.apply(this, arguments).all(args);
}
fetch(args = {}) {
args.model = this;
// Returns a subset of rows specified with an int and a head/tail argument
return this.$$prep.apply(
this,
arguments
).fetch(args);
}
filter(args = {}) {
args.model = this;
// Returns a filtered subset of rows
return this.$$prep.apply(
this,
arguments
).filter(args);
}
exists(args = {}) {
args.model = args.model || this;
return this.filter.apply(this, arguments).then(function(queryset) {
return !!queryset[0];
});
}
create(args = {}) {
args.model = this;
this.database = this.$$prep.apply(this, arguments);
// Make sure all of our fields are resolved
let createObj = {},
me = this;
this.$fields().forEach(function(field) {
let val = args[ field ] || args.model[ field ].default || null;
if (typeof val === 'function') {
val = val.call(this, args);
}
if (
me[ field ] &&
me[ field ].validate &&
me[ field ].validate(val)
) {
createObj[ field ] = val;
} else {
throw new $$InvalidModelFieldReferenceError(me.name, field);
}
});
// Once that is settled, we can call our create
return this.database.create(args);
}
$createUnlessExists(args = {}) {
args.model = this;
// Check to see if a matching record exists and if not create it
let me = this;
return this.exists(args).then((v) =>
me[ v ? 'fetch' : 'create' ](args)
);
}
delete(args = {}) {
args.model = this;
// Delete a record/set of records
return this.$$prep.apply(
this,
arguments
).delete(args);
}
query(query, args = {}) {
if (typeof query !== 'string') {
return new Promise(function() {
arguments[1](new Error('Invalid Query String'));
});
}
return this.$$prep.apply(this, args).raw(query, this);
}
$fields() {
this.fields = [];
for (let key in this) {
if (
typeof this[ key ] === 'object' &&
IGNORE_KEYS.indexOf(key) === -1
) {
this.fields.push(key);
}
}
return this.fields;
}
$$prep(args = {}) {
const database = typeof args === 'object' && args.hasOwnProperty('database') ?
args.database : null;
// This forces the router to use a specific database, DB can also be
// forced at a model level by using this.database
this.$$database = AngieDatabaseRouter(
database || this.database || 'default'
);
return this.$$database;
}
}
class $$InvalidRelationCrossReferenceError extends RangeError {
constructor(method, field) {
$LogProvider.error(
`Cannot ${method} reference on ${cyan(field.name)}: ` +
'No such existing record.'
);
super();
}
}
export default BaseModel; | benderTheCrime/angie-orm | src/models/BaseModel.js | JavaScript | mit | 4,087 |
var server = require('./server')
, events = require('events')
, stream = require('stream')
, assert = require('assert')
, fs = require('fs')
, request = require('../index')
, path = require('path')
, util = require('util')
;
var port = 6768
, called = false
, proxiedHost = 'google.com'
;
var s = server.createServer(port)
s.listen(port, function () {
s.on('http://google.com/', function (req, res) {
called = true
assert.equal(req.headers.host, proxiedHost)
res.writeHeader(200)
res.end()
})
request ({
url: 'http://'+proxiedHost,
proxy: 'http://127.0.0.1:'+port
/*
//should behave as if these arguments where passed:
url: 'http://127.0.0.1:'+port,
headers: {host: proxiedHost}
//*/
}, function (err, res, body) {
s.close()
})
})
process.on('exit', function () {
assert.ok(called, 'the request must be made to the proxy server')
})
| ethannguyen93/POS | node_modules/forever/node_modules/winston/node_modules/request/tests/test-proxy.js | JavaScript | mit | 918 |
module.exports = {
parser: 'babel-eslint',
extends: ['formidable/configurations/es6'],
globals: {
Promise: true
},
env: {
node: true
},
ecmaFeatures: {
modules: true
},
rules: {
'no-unused-vars': [
'error',
{
vars: 'all',
args: 'after-used',
ignoreRestSiblings: false,
argsIgnorePattern: '^_'
}
],
'no-magic-numbers': 'off',
'no-invalid-this': 'off',
'no-unused-expressions': 'off',
'no-console': 'off',
quotes: ['error', 'single', { avoidEscape: true }],
indent: [
'error',
2,
{
SwitchCase: 1
}
],
'new-cap': 'off',
'func-style': 'off',
'generator-star-spacing': 'off',
'max-len': ['error', 100, { ignoreUrls: true }],
'max-params': 'off',
'comma-dangle': ['error', 'never'],
'arrow-parens': ['error', 'as-needed'],
eqeqeq: ['error', 'smart'],
'filenames/match-regex': 'off',
'filenames/match-exported': 'off',
'filenames/no-index': 'off'
}
};
| anyjunk/redux-offline | .eslintrc.js | JavaScript | mit | 1,039 |
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v21.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var columnController_1 = require("./columnController/columnController");
var eventService_1 = require("./eventService");
var logger_1 = require("./logger");
var events_1 = require("./events");
var context_1 = require("./context/context");
var context_2 = require("./context/context");
var context_3 = require("./context/context");
var context_4 = require("./context/context");
var AlignedGridsService = /** @class */ (function () {
function AlignedGridsService() {
// flag to mark if we are consuming. to avoid cyclic events (ie other grid firing back to master
// while processing a master event) we mark this if consuming an event, and if we are, then
// we don't fire back any events.
this.consuming = false;
}
AlignedGridsService.prototype.setBeans = function (loggerFactory) {
this.logger = loggerFactory.create('AlignedGridsService');
};
AlignedGridsService.prototype.registerGridComp = function (gridPanel) {
this.gridPanel = gridPanel;
};
AlignedGridsService.prototype.init = function () {
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_MOVED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_VISIBLE, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_PINNED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_GROUP_OPENED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_RESIZED, this.fireColumnEvent.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_BODY_SCROLL, this.fireScrollEvent.bind(this));
};
// common logic across all the fire methods
AlignedGridsService.prototype.fireEvent = function (callback) {
// if we are already consuming, then we are acting on an event from a master,
// so we don't cause a cyclic firing of events
if (this.consuming) {
return;
}
// iterate through the aligned grids, and pass each aligned grid service to the callback
var otherGrids = this.gridOptionsWrapper.getAlignedGrids();
if (otherGrids) {
otherGrids.forEach(function (otherGridOptions) {
if (otherGridOptions.api) {
var alignedGridService = otherGridOptions.api.__getAlignedGridService();
callback(alignedGridService);
}
});
}
};
// common logic across all consume methods. very little common logic, however extracting
// guarantees consistency across the methods.
AlignedGridsService.prototype.onEvent = function (callback) {
this.consuming = true;
callback();
this.consuming = false;
};
AlignedGridsService.prototype.fireColumnEvent = function (event) {
this.fireEvent(function (alignedGridsService) {
alignedGridsService.onColumnEvent(event);
});
};
AlignedGridsService.prototype.fireScrollEvent = function (event) {
if (event.direction !== 'horizontal') {
return;
}
this.fireEvent(function (alignedGridsService) {
alignedGridsService.onScrollEvent(event);
});
};
AlignedGridsService.prototype.onScrollEvent = function (event) {
var _this = this;
this.onEvent(function () {
_this.gridPanel.setHorizontalScrollPosition(event.left);
});
};
AlignedGridsService.prototype.getMasterColumns = function (event) {
var result = [];
if (event.columns) {
event.columns.forEach(function (column) {
result.push(column);
});
}
else if (event.column) {
result.push(event.column);
}
return result;
};
AlignedGridsService.prototype.getColumnIds = function (event) {
var result = [];
if (event.columns) {
event.columns.forEach(function (column) {
result.push(column.getColId());
});
}
else if (event.column) {
result.push(event.column.getColId());
}
return result;
};
AlignedGridsService.prototype.onColumnEvent = function (event) {
var _this = this;
this.onEvent(function () {
switch (event.type) {
case events_1.Events.EVENT_COLUMN_MOVED:
case events_1.Events.EVENT_COLUMN_VISIBLE:
case events_1.Events.EVENT_COLUMN_PINNED:
case events_1.Events.EVENT_COLUMN_RESIZED:
var colEvent = event;
_this.processColumnEvent(colEvent);
break;
case events_1.Events.EVENT_COLUMN_GROUP_OPENED:
var groupOpenedEvent = event;
_this.processGroupOpenedEvent(groupOpenedEvent);
break;
case events_1.Events.EVENT_COLUMN_PIVOT_CHANGED:
// we cannot support pivoting with aligned grids as the columns will be out of sync as the
// grids will have columns created based on the row data of the grid.
console.warn('ag-Grid: pivoting is not supported with aligned grids. ' +
'You can only use one of these features at a time in a grid.');
break;
}
});
};
AlignedGridsService.prototype.processGroupOpenedEvent = function (groupOpenedEvent) {
// likewise for column group
var masterColumnGroup = groupOpenedEvent.columnGroup;
var otherColumnGroup;
if (masterColumnGroup) {
var groupId = masterColumnGroup.getGroupId();
otherColumnGroup = this.columnController.getOriginalColumnGroup(groupId);
}
if (masterColumnGroup && !otherColumnGroup) {
return;
}
this.logger.log('onColumnEvent-> processing ' + groupOpenedEvent + ' expanded = ' + masterColumnGroup.isExpanded());
this.columnController.setColumnGroupOpened(otherColumnGroup, masterColumnGroup.isExpanded(), "alignedGridChanged");
};
AlignedGridsService.prototype.processColumnEvent = function (colEvent) {
var _this = this;
// the column in the event is from the master grid. need to
// look up the equivalent from this (other) grid
var masterColumn = colEvent.column;
var otherColumn;
if (masterColumn) {
otherColumn = this.columnController.getPrimaryColumn(masterColumn.getColId());
}
// if event was with respect to a master column, that is not present in this
// grid, then we ignore the event
if (masterColumn && !otherColumn) {
return;
}
// in time, all the methods below should use the column ids, it's a more generic way
// of handling columns, and also allows for single or multi column events
var columnIds = this.getColumnIds(colEvent);
var masterColumns = this.getMasterColumns(colEvent);
switch (colEvent.type) {
case events_1.Events.EVENT_COLUMN_MOVED:
var movedEvent = colEvent;
this.logger.log("onColumnEvent-> processing " + colEvent.type + " toIndex = " + movedEvent.toIndex);
this.columnController.moveColumns(columnIds, movedEvent.toIndex, "alignedGridChanged");
break;
case events_1.Events.EVENT_COLUMN_VISIBLE:
var visibleEvent = colEvent;
this.logger.log("onColumnEvent-> processing " + colEvent.type + " visible = " + visibleEvent.visible);
this.columnController.setColumnsVisible(columnIds, visibleEvent.visible, "alignedGridChanged");
break;
case events_1.Events.EVENT_COLUMN_PINNED:
var pinnedEvent = colEvent;
this.logger.log("onColumnEvent-> processing " + colEvent.type + " pinned = " + pinnedEvent.pinned);
this.columnController.setColumnsPinned(columnIds, pinnedEvent.pinned, "alignedGridChanged");
break;
case events_1.Events.EVENT_COLUMN_RESIZED:
var resizedEvent_1 = colEvent;
masterColumns.forEach(function (column) {
_this.logger.log("onColumnEvent-> processing " + colEvent.type + " actualWidth = " + column.getActualWidth());
_this.columnController.setColumnWidth(column.getColId(), column.getActualWidth(), false, resizedEvent_1.finished, "alignedGridChanged");
});
break;
}
var isVerticalScrollShowing = this.gridPanel.isVerticalScrollShowing();
var alignedGrids = this.gridOptionsWrapper.getAlignedGrids();
alignedGrids.forEach(function (grid) {
grid.api.setAlwaysShowVerticalScroll(isVerticalScrollShowing);
});
};
__decorate([
context_3.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], AlignedGridsService.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_3.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], AlignedGridsService.prototype, "columnController", void 0);
__decorate([
context_3.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], AlignedGridsService.prototype, "eventService", void 0);
__decorate([
__param(0, context_2.Qualifier('loggerFactory')),
__metadata("design:type", Function),
__metadata("design:paramtypes", [logger_1.LoggerFactory]),
__metadata("design:returntype", void 0)
], AlignedGridsService.prototype, "setBeans", null);
__decorate([
context_4.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], AlignedGridsService.prototype, "init", null);
AlignedGridsService = __decorate([
context_1.Bean('alignedGridsService')
], AlignedGridsService);
return AlignedGridsService;
}());
exports.AlignedGridsService = AlignedGridsService;
| extend1994/cdnjs | ajax/libs/ag-grid/21.1.0/lib/alignedGridsService.js | JavaScript | mit | 11,635 |
var $ = require("../dom")
var parser = require("../parser")
module.exports = {
bind: function(ele, attr, component) {
this.update(ele, attr, component)
},
update: function(ele, attr, component) {
var tokensAndPaths = parser.parseTokensAndPaths(attr.value)
var isShow = parser.exec({
exp: attr.value,
tokens: tokensAndPaths.tokens,
paths: tokensAndPaths.paths
}, component.scope)
var $el = $(ele)
if (isShow) {
$el.show()
} else {
$el.hide()
}
}
}
| livoras/wet.js | src/directives/show.js | JavaScript | mit | 524 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"am",
"pm"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "dd MMMM y",
"medium": "dd MMM y HH:mm:ss",
"mediumDate": "dd MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-mt",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| mikec/angular.js | src/ngLocale/angular-locale_en-mt.js | JavaScript | mit | 2,354 |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('./turn-order-8e019db0.js');
require('immer');
require('./plugin-random-7425844d.js');
require('lodash.isplainobject');
var reducer = require('./reducer-943f1bac.js');
require('rfc6902');
var initialize = require('./initialize-45c7e6ee.js');
var transport = require('./transport-b1874dfa.js');
var util = require('./util-047daabc.js');
var filterPlayerView = require('./filter-player-view-0fd577a7.js');
exports.CreateGameReducer = reducer.CreateGameReducer;
exports.ProcessGameConfig = reducer.ProcessGameConfig;
exports.InitializeGame = initialize.InitializeGame;
exports.Transport = transport.Transport;
exports.Async = util.Async;
exports.Sync = util.Sync;
exports.createMatch = util.createMatch;
exports.getFilterPlayerView = filterPlayerView.getFilterPlayerView;
| cdnjs/cdnjs | ajax/libs/boardgame-io/0.49.9/cjs/internal.js | JavaScript | mit | 859 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var control_usuario_list = function(path) {
//contexto privado
var prefijo_div = "#usuario_list ";
function cargaBotoneraMantenimiento() {
var botonera = [
{"class": "btn btn-mini action05", "icon": "", "text": "entradas"},
{"class": "btn btn-mini action01", "icon": "icon-eye-open", "text": ""},
{"class": "btn btn-mini action02", "icon": "icon-zoom-in", "text": ""},
{"class": "btn btn-mini action03", "icon": "icon-pencil", "text": ""},
{"class": "btn btn-mini action04", "icon": "icon-remove", "text": ""}
];
return botonera;
}
function cargaBotoneraBuscando() {
var botonera = [
{"class": "btn btn-mini action01", "icon": "icon-ok", "text": ""}
];
return botonera;
}
function loadDivView(view, place, id) {
$(prefijo_div + place).empty().append((view.getObjectTable(id))
+ '<button class="btn btn-primary" id="limpiar">Limpiar</button>');
$(prefijo_div + '#limpiar').click(function() {
$(prefijo_div + place).empty();
});
}
function loadModalForm(view, place, id, action) {
cabecera = '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>';
if (action == "edit") {
cabecera += '<h3 id="myModalLabel">Edición de ' + view.getObject().getName() + "</h3>";
} else {
cabecera += '<h3 id="myModalLabel">Alta de ' + view.getObject().getName() + "</h3>";
}
pie = '<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Cerrar</button>';
loadForm(place, cabecera, view.getEmptyForm(), pie, false);
if (action == "edit") {
view.doFillForm(id);
} else {
$(prefijo_div + '#id').val('0').attr("disabled", true);
$(prefijo_div + '#nombre').focus();
}
//http://jqueryvalidation.org/documentation/
$('#formulario').validate({
rules: {
login: {
required: true,
maxlength: 20
},
password: {
required: true,
maxlength: 25
},
passwordRepite: {
required: true,
maxlength: 25,
equalTo: "#password"
}
},
messages: {
login: {
required: "Introduce un login",
maxlength: "Tiene que ser menos de 20 caracteres"
},
password: {
required: "Introduce una contraseña",
maxlength: "Tiene que ser menos de 25 caracteres"
},
passwordRepite: {
required: "Repite la contraseña",
date: "Tiene que ser menos de 25 caracteres",
equalTo: "Las contraseñas no concuerdan"
}
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
$(prefijo_div + '#submitForm').unbind('click');
$(prefijo_div + '#submitForm').click(function() {
if ($("#formulario").valid()) {
enviarDatosUpdateForm(view, prefijo_div);
}
return false;
});
}
function removeConfirmationModalForm(view, place, id) {
cabecera = "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>" +
"<h3 id=\"myModalLabel\">Borrado de " + view.getObject().getName() + "</h3>";
pie = "<div id=\"result\">¿Seguro que desea borrar el registro?</div>" +
'<button id="btnBorrarSi" class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Sí</button>' +
'<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">No</button>';
loadForm(place, cabecera, view.getObjectTable(id), pie, false);
$(prefijo_div + '#btnBorrarSi').unbind('click');
$(prefijo_div + '#btnBorrarSi').click(function() {
resultado = view.getObject().removeOne(id);
cabecera = "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>" + "<h3 id=\"myModalLabel\">Respuesta del servidor</h3>";
pie = "<button class=\"btn btn-primary\" data-dismiss=\"modal\" aria-hidden=\"true\">Cerrar</button>";
loadForm('#modal02', cabecera, "Código: " + resultado["status"] + "<br />" + resultado["message"] + "<br />", pie, true);
});
}
function loadModalView(view, place, id) {
cabecera = "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>" +
"<h3 id=\"myModalLabel\">Detalle de " + view.getObject().getName() + "</h3>";
pie = "<button class=\"btn btn-primary\" data-dismiss=\"modal\" aria-hidden=\"true\">Cerrar</button>";
loadForm(place, cabecera, view.getObjectTable(id), pie, true);
}
function cargaEntradas(id) {
var entrada = objeto('entrada', path);
var entradaView = vista(entrada, path);
$('#indexContenidoJsp').empty();
$('#indexContenido').empty().append(entradaView.getEmptyList());
var entradaControl = control_entrada_list(path);
entradaControl.inicia(entradaView, 1, null, null, 10, null, null, null, null, "id_usuario", "equals", id);
return false;
}
return {
inicia: function(view, pag, order, ordervalue, rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue) {
var thisObject = this;
//controlar que no estemos en una página fuera de órbita
if (parseInt(pag) > parseInt(view.getObject().getPages(rpp, filter, filteroperator, filtervalue))) {
pag = view.getObject().getPages(rpp, filter, filteroperator, filtervalue);
}
//muestra la botonera de páginas
$(prefijo_div + "#pagination").empty().append(view.getLoading()).html(view.getPageLinks(pag, rpp, filter, filteroperator, filtervalue, systemfilter, systemfilteroperator, systemfiltervalue));
//muestra el listado principal
if (callback) {
$(prefijo_div + "#datos").empty().append(view.getLoading()).html(view.getPageTable(pag, order, ordervalue, rpp, filter, filteroperator, filtervalue, systemfilter, systemfilteroperator, systemfiltervalue, cargaBotoneraBuscando()));
} else {
$(prefijo_div + "#datos").empty().append(view.getLoading()).html(view.getPageTable(pag, order, ordervalue, rpp, filter, filteroperator, filtervalue, systemfilter, systemfilteroperator, systemfiltervalue, cargaBotoneraMantenimiento()));
}
//muestra la frase con el número de registros de la consulta
$(prefijo_div + "#registers").empty().append(view.getLoading()).html(view.getRegistersInfo(filter, filteroperator, filtervalue, systemfilter, systemfilteroperator, systemfiltervalue));
//muestra la frase de estado de la ordenación de la tabla
$(prefijo_div + "#order").empty().append(view.getLoading()).html(view.getOrderInfo(order, ordervalue));
//muestra la frase de estado del filtro de la tabla aplicado
$(prefijo_div + "#filter").empty().append(view.getLoading()).html(view.getFilterInfo(filter, filteroperator, filtervalue));
//asignación eventos de la botonera de cada línea del listado principal
if (callback) {
$(prefijo_div + '.btn.btn-mini.action01').unbind('click');
$(prefijo_div + '.btn.btn-mini.action01').click(callback);
} else {
$(prefijo_div + '.btn.btn-mini.action01').unbind('click');
$(prefijo_div + '.btn.btn-mini.action01').click(function() {
loadDivView(view, '#datos2', $(this).attr('id'));
});
$(prefijo_div + '.btn.btn-mini.action02').unbind('click');
$(prefijo_div + '.btn.btn-mini.action02').click(function() {
loadModalView(view, '#modal01', $(this).attr('id'));
});
$(prefijo_div + '.btn.btn-mini.action03').unbind('click');
$(prefijo_div + '.btn.btn-mini.action03').click(function() {
loadModalForm(view, '#modal01', $(this).attr('id'), "edit");
});
$(prefijo_div + '.btn.btn-mini.action04').unbind('click');
$(prefijo_div + '.btn.btn-mini.action04').click(function() {
removeConfirmationModalForm(view, '#modal01', $(this).attr('id'));
});
$(prefijo_div + '.btn.btn-mini.action05').unbind('click');
$(prefijo_div + '.btn.btn-mini.action05').click(function() {
cargaEntradas($(this).attr('id'));
});
}
//asignación de evento del enlace para quitar el orden en el listado principal
$(prefijo_div + '#linkQuitarOrden').unbind('click');
$(prefijo_div + '#linkQuitarOrden').click(function() {
thisObject.inicia(view, pag, null, null, rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue);
});
//asignación de evento del enlace para quitar el filtro en el listado principal
$(prefijo_div + '#linkQuitarFiltro').unbind('click');
$(prefijo_div + '#linkQuitarFiltro').click(function() {
thisObject.inicia(view, pag, order, ordervalue, rpp, null, null, null, callback, systemfilter, systemfilteroperator, systemfiltervalue);
});
//asignación de eventos de la ordenación por columnas del listado principal
$.each(view.getObject().getFieldNames(), function(index, valor) {
$(prefijo_div + '.orderAsc').unbind('click');
$(prefijo_div + '.orderAsc' + index).click(function() {
rpp = $(prefijo_div + "#rpp option:selected").text();
thisObject.inicia(view, pag, valor, "asc", rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue);
});
$(prefijo_div + '.orderDesc').unbind('click');
$(prefijo_div + '.orderDesc' + index).click(function() {
rpp = $(prefijo_div + "#rpp option:selected").text();
thisObject.inicia(view, pag, valor, "desc", rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue);
});
});
//asignación del evento de click para cambiar de página en la botonera de paginación
$(prefijo_div + '.pagination_link').unbind('click');
$(prefijo_div + '.pagination_link').click(function() {
var id = $(this).attr('id');
rpp = $(prefijo_div + "#rpp option:selected").text();
thisObject.inicia(view, id, order, ordervalue, rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue);
return false;
});
//boton de crear un nuevo elemento
if (callback) {
$(prefijo_div + '#crear').css("display", "none");
} else {
$(prefijo_div + '#crear').unbind('click');
$(prefijo_div + '#crear').click(function() {
loadModalForm(view, prefijo_div + '#modal01', $(this).attr('id'));
});
}
//asignación del evento de filtrado al boton
$(prefijo_div + '#btnFiltrar').unbind('click');
$(prefijo_div + "#btnFiltrar").click(function() {
filter = $(prefijo_div + "#selectFilter option:selected").text();
filteroperator = $(prefijo_div + "#selectFilteroperator option:selected").text();
filtervalue = $(prefijo_div + "#inputFiltervalue").val();
thisObject.inicia(view, pag, order, ordervalue, rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue);
return false;
});
//asigación de evento de refresco de la tabla cuando volvemos de una operación en ventana modal
$(prefijo_div + '#modal01').unbind('hidden');
$(prefijo_div + '#modal01').on('hidden', function() {
rpp = $(prefijo_div + "#rpp option:selected").text();
thisObject.inicia(view, pag, order, ordervalue, rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue);
});
//asignación del evento de cambio del numero de regs por página
$(prefijo_div + '#rpp').unbind('change');
$(prefijo_div + '#rpp').on('change', function() {
rpp = $(prefijo_div + "#rpp option:selected").text();
thisObject.inicia(view, pag, order, ordervalue, rpp, filter, filteroperator, filtervalue, callback, systemfilter, systemfilteroperator, systemfiltervalue);
});
}
};
};
| jpgodesart/GestionTareas | src/main/webapp/js/control/usuario.js | JavaScript | gpl-2.0 | 14,050 |
// Jquery
(function($){
/*
// ALL WEBSITE
*/
$("button.open-menu").on( "click", function() {
$("nav.main-nav").toggleClass("active");
});
//Overlay
function activeOverlay() {
$("#overlay").toggleClass("active");
}
$( "#overlay" ).on( "click", "#button-close", function() {
activeOverlay();
});
/*
// Get current url and mark active item in menu
var a_active;
function activeMenu() {
var currentURL = document.URL;
currentURL = currentURL.split("#").pop();
$( "ol.menu ol li a" ).each( function() {
var a_url = $(this).attr("href");
a_url = a_url.split("#").pop();
if ( currentURL === a_url ) {
a_active = $(this);
a_active.addClass("active");
}
});
}
activeMenu();
$( "ol.menu ol li a" ).on( "click", function() {
a_active.removeClass("active");
a_active = $(this);
a_active.addClass("active");
$("button.open-menu").trigger("click");
});
*/
/*
// HOME
*/
if( $("body").hasClass("home") ){
// Passes href value from child a to parent
$( "section.matrix" ).on( "click", "article", function() {
var url = $("a", $(this)).attr("href");
if ( url !== undefined ) {
document.location = url;
}
});
}//is home
/*
// PAGE
*/
if( $("body").hasClass("page") || $("body").hasClass("single") ){
//Auto resise commentform textarea
autosize( $("#comment") );
//Change class to comment form when replying to a comment
$( ".comment" ).on( "click", "a.comment-reply-link", function() {
$("#respond").addClass("to-reply");
});
$( "#cancel-comment-reply-link" ).on( "click", function() {
$("#respond").removeClass("to-reply");
});
//Activate overlay
$( "#button-plus" ).on( "click", function() {
$("#post-meta").toggleClass("active");
$(this).toggleClass("active");
});
//
$( "#post-meta .cta-box input" ).on( "focus", function() {
$(this).select();
});
$( "#post-meta .cta-box.share" ).on( "click", "button.share", function() {
$( "#post-meta .cta-box input" ).trigger( "focus" );
document.execCommand("copy");
alert("Link copied to clipboard. Now go share :)");
});
/*
// Article sidebar
$("aside.sidebar").on( "click", "button.open-sidebar", function() {
var sidebar = $(this).parent();
var button = $(this);
sidebar.toggleClass("open");
if ( sidebar.hasClass("open") ){
// clicking out of sidebar triggers click
$(document).on( "click", function (e) {
// if the target of the click isn't the sidebar nor a descendant of the sidebar
if (!sidebar.is(e.target) && sidebar.has(e.target).length === 0) {
button.trigger("click");
// turn off event so it only triggers once
$(document).off(e);
}
});
} else {
// turn off document click event if closed
$(document).off();
}
});
*/
/*
// ScrollMagic
// init controller
var controller = new ScrollMagic.Controller();
var pin = "#page-header";
// create a scene
var scene = new ScrollMagic.Scene({
offset: $(pin).height()
})
.setPin( pin, {pushFollowers: false} )
.addTo(controller)
.on( "progress", function (event) {
var st1;
var st2;
if ( event.progress === 1 ) {
clearTimeout(st2);
$(pin).children().fadeOut(100);
st1 = setTimeout(function(){
$(pin).addClass("fixed").children().fadeIn(400);
}, 300);
} else if ( event.progress === 0 ) {
clearTimeout(st1);
$(pin).children().fadeOut(100);
st2 = setTimeout(function(){
$(pin).removeClass("fixed").children().fadeIn(400);
}, 300);
}
});
scene.on("progress", function (event) {
window.console.log("Scene progress changed to " + event.progress);
});
scene.on("start", function (event) {
window.console.log("Hit start point of scene.");
});
scene.on("end", function (event) {
event.scrollDirection = "REVERSE";
window.console.log("Hit end point of scene.");
});
//
*/
}//isPage
})( jQuery );
| colab-at/colab-website | js/main.js | JavaScript | gpl-2.0 | 3,966 |
// Gather used gulp plugins
var gulp = require('gulp');
rename = require('gulp-rename');
watch = require('gulp-watch');
sass = require('gulp-sass');
autoprefixer = require('gulp-autoprefixer');
jsmin = require('gulp-jsmin');
imagemin = require('gulp-imagemin');
styleguide = require('sc5-styleguide');
mustache = require('gulp-mustache');
deleteLines = require('gulp-delete-lines');
server = require('gulp-server-livereload');
imageminJpegRecompress = require('imagemin-jpeg-recompress');
vfs = require('vinyl-fs');
// Set paths
var paths = {
sass: {
input: 'src/sass/app.sass',
allfiles: 'src/sass/**/*.+(scss|sass)',
output: 'dist/css',
outputDev: '.dev/css'
},
js: {
input: 'src/js/**/*.+(js|json)',
output: 'dist/js',
outputDev: '.dev/js'
},
mustache: {
input: './src/*.html',
allfiles: './src/**/*.{html,mustache}',
output: './dist',
outputDev: './.dev'
},
fonts: {
input: './src/fonts/**/*',
output: './dist/fonts',
outputDev: './.dev/fonts'
},
images: {
input: './src/images/**/*',
output: './dist/images',
outputDev: './.dev/images'
},
devScripts: {
input: './src/dev-scripts/**/*',
output: './.dev/dev-scripts',
},
styleguide: {
sass: [
'src/sass/**/*.+(scss|sass)',
'src/!sass/_*.+(scss|sass)'
],
html: 'src/sass/**/*.html',
output: 'styleguide',
}
};
// Define SASS compiling and minifying
gulp.task('sass', function () {
gulp.src(paths.sass.input)
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(rename('style.bundle.css'))
.pipe(autoprefixer({
browsers: ['last 10 versions'],
cascade: false
}))
.pipe(gulp.dest(paths.sass.output))
});
// Define SASS compiling
gulp.task('sass-dev', function () {
gulp.src(paths.sass.input)
.pipe(sass().on('error', sass.logError))
.pipe(rename('style.bundle.css'))
.pipe(autoprefixer({
browsers: ['last 10 versions'],
cascade: false
}))
.pipe(gulp.dest(paths.sass.outputDev))
});
// Define JS copying and minifying
gulp.task('js', function () {
gulp.src(paths.js.input)
.pipe(jsmin())
.pipe(gulp.dest(paths.js.output));
});
// Define JS copying
gulp.task('js-dev', function () {
gulp.src(paths.js.input)
.pipe(gulp.dest(paths.js.outputDev));
});
// Define development files copying
gulp.task('dev-scripts', function () {
gulp.src(paths.devScripts.input)
.pipe(gulp.dest(paths.devScripts.output));
});
// Define Mustache compiling and removing dev scripts
gulp.task('mustache', function() {
gulp.src(paths.mustache.input)
.pipe(mustache())
.pipe(deleteLines({
'filters': [
/<!-- Development script|src="dev-scripts\/fronthack-dev.js"/i
]
}))
.pipe(gulp.dest(paths.mustache.output));
});
// Define Mustache compiling
gulp.task('mustache-dev', function() {
gulp.src(paths.mustache.input)
.pipe(mustache())
.pipe(gulp.dest(paths.mustache.outputDev));
});
// Define Font files copying
gulp.task('fonts', function() {
gulp.src(paths.fonts.input)
.pipe(gulp.dest(paths.fonts.output));
});
// Define Font files copying.
gulp.task('fonts-dev', function() {
gulp.src(paths.fonts.input)
.pipe(gulp.dest(paths.fonts.outputDev));
});
// Define Assets compiling and minifying.
gulp.task('images', function() {
gulp.src(paths.images.input)
.pipe(imagemin([
imageminJpegRecompress({method: 'mpe', max: 85}),
imagemin.optipng({optimizationLevel: 5})
], {
verbose: true
}))
.pipe(gulp.dest(paths.images.output));
});
// Define Assets copying.
gulp.task('images-dev', function() {
gulp.src(paths.images.input)
.pipe(gulp.dest(paths.images.outputDev));
});
// Define creating of symlink to designs
gulp.task('designs', function() {
vfs.src('src/designs', {followSymlinks: false})
.pipe(vfs.symlink('.dev'));
});
// Define localhost server
gulp.task('devserver', function() {
gulp.src('.dev')
.pipe(server({
livereload: true
}));
});
// GULP DEV - compiles .dev and dist directories, run local server.
gulp.task('dev', [
'sass-dev',
'js-dev',
'mustache-dev',
'fonts-dev',
'images-dev',
'designs',
'dev-scripts',
'devserver'
], function() {
gulp.watch([
paths.sass.allfiles,
paths.mustache.allfiles,
paths.images.input,
paths.js.input,
paths.devScripts.input
], [
'sass-dev',
'js-dev',
'mustache-dev',
'fonts-dev',
'images-dev',
'designs',
'dev-scripts'
]);
});
// GULP BUILD - compiles dist directory.
gulp.task('build', [
'sass',
'js',
'mustache',
'fonts',
'images'
]);
// Styleguide start
// --------------------------------------------------
// Everything below is for rendering a styleguide.
// Define rendering styleguide task
// https://github.com/SC5/sc5-styleguide#build-options
gulp.task('styleguide-main:generate', function() {
return gulp.src(paths.styleguide.sass)
.pipe(styleguide.generate({
title: 'Fronthack styleguide',
server: true,
sideNav: true,
rootPath: paths.styleguide.output,
overviewPath: 'README.md',
commonClass: 'body',
extraHead: [
'<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>',
'<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.0/owl.carousel.min.js"></script>',
'<script src="/js/owl-carousel.js"></script>',
],
disableEncapsulation: true,
disableHtml5Mode: true
}))
.pipe(gulp.dest(paths.styleguide.output));
});
gulp.task('styleguide-main:applystyles', function() {
return gulp.src([
'src/sass/app.sass',
'src/sass/styleguide-overrides.sass'
])
.pipe(sass({
errLogToConsole: true
}))
.pipe(styleguide.applyStyles())
.pipe(gulp.dest(paths.styleguide.output));
});
gulp.task('styleguide-main', ['styleguide-main:generate', 'styleguide-main:applystyles']);
// Define copying images for styleguide task
gulp.task('styleguide-images', function() {
gulp.src(['src/images/**'])
.pipe(gulp.dest(paths.styleguide.output + '/images'));
});
// Define copying javascript for styleguide task
gulp.task('styleguide-js', function() {
gulp.src(['src/js/components/**'])
.pipe(gulp.dest(paths.styleguide.output + '/js/components'));
});
// Define copying fonts for styleguide task
gulp.task('styleguide-fonts', function() {
gulp.src(['src/fonts/**'])
.pipe(gulp.dest(paths.styleguide.output + '/fonts'));
});
// GULP STYLEGUIDE - compiles Stylguide.
gulp.task('styleguide', [
'styleguide-main',
'styleguide-images',
'styleguide-js',
'styleguide-fonts'
], function() {
gulp.watch([paths.sass.allfiles, paths.styleguide.html, paths.mustache.allfiles], [
'styleguide-main',
'styleguide-images',
'styleguide-js',
'styleguide-fonts'
]);
});
// Styleguide end
| frontcraft/bootsmacss | gulpfile.js | JavaScript | gpl-2.0 | 7,022 |
/**
* Utility functions for handling gradients
*/
PIE.GradientUtil = {
getGradientMetrics: function( el, width, height, gradientInfo ) {
var angle = gradientInfo.angle,
startPos = gradientInfo.gradientStart,
startX, startY,
endX, endY,
startCornerX, startCornerY,
endCornerX, endCornerY,
deltaX, deltaY,
p, UNDEF;
// Find the "start" and "end" corners; these are the corners furthest along the gradient line.
// This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding
// the total length of the VML rendered gradient-line corner to corner.
function findCorners() {
startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0;
startCornerY = angle < 180 ? height : 0;
endCornerX = width - startCornerX;
endCornerY = height - startCornerY;
}
// Normalize the angle to a value between [0, 360)
function normalizeAngle() {
while( angle < 0 ) {
angle += 360;
}
angle = angle % 360;
}
// Find the start and end points of the gradient
if( startPos ) {
startPos = startPos.coords( el, width, height );
startX = startPos.x;
startY = startPos.y;
}
if( angle ) {
angle = angle.degrees();
normalizeAngle();
findCorners();
// If no start position was specified, then choose a corner as the starting point.
if( !startPos ) {
startX = startCornerX;
startY = startCornerY;
}
// Find the end position by extending a perpendicular line from the gradient-line which
// intersects the corner opposite from the starting corner.
p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY );
endX = p[0];
endY = p[1];
}
else if( startPos ) {
// Start position but no angle specified: find the end point by rotating 180deg around the center
endX = width - startX;
endY = height - startY;
}
else {
// Neither position nor angle specified; create vertical gradient from top to bottom
startX = startY = endX = 0;
endY = height;
}
deltaX = endX - startX;
deltaY = endY - startY;
if( angle === UNDEF ) {
// Get the angle based on the change in x/y from start to end point. Checks first for horizontal
// or vertical angles so they get exact whole numbers rather than what atan2 gives.
angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) :
( !deltaY ? ( deltaX < 0 ? 180 : 0 ) :
-Math.atan2( deltaY, deltaX ) / Math.PI * 180
)
);
normalizeAngle();
findCorners();
}
return {
angle: angle,
startX: startX,
startY: startY,
endX: endX,
endY: endY,
startCornerX: startCornerX,
startCornerY: startCornerY,
endCornerX: endCornerX,
endCornerY: endCornerY,
deltaX: deltaX,
deltaY: deltaY,
lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
}
},
/**
* Find the point along a given line (defined by a starting point and an angle), at which
* that line is intersected by a perpendicular line extending through another point.
* @param x1 - x coord of the starting point
* @param y1 - y coord of the starting point
* @param angle - angle of the line extending from the starting point (in degrees)
* @param x2 - x coord of point along the perpendicular line
* @param y2 - y coord of point along the perpendicular line
* @return [ x, y ]
*/
perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
// Handle straight vertical and horizontal angles, for performance and to avoid
// divide-by-zero errors.
if( angle === 0 || angle === 180 ) {
return [ x2, y1 ];
}
else if( angle === 90 || angle === 270 ) {
return [ x1, y2 ];
}
else {
// General approach: determine the Ax+By=C formula for each line (the slope of the second
// line is the negative inverse of the first) and then solve for where both formulas have
// the same x/y values.
var a1 = Math.tan( -angle * Math.PI / 180 ),
c1 = a1 * x1 - y1,
a2 = -1 / a1,
c2 = a2 * x2 - y2,
d = a2 - a1,
endX = ( c2 - c1 ) / d,
endY = ( a1 * c2 - a2 * c1 ) / d;
return [ endX, endY ];
}
},
/**
* Find the distance between two points
* @param {Number} p1x
* @param {Number} p1y
* @param {Number} p2x
* @param {Number} p2y
* @return {Number} the distance
*/
distance: function( p1x, p1y, p2x, p2y ) {
var dx = p2x - p1x,
dy = p2y - p1y;
return Math.abs(
dx === 0 ? dy :
dy === 0 ? dx :
Math.sqrt( dx * dx + dy * dy )
);
}
}; | schnitzel25/pizza | sites/all/themes/pzz/libraries/pie/sources/GradientUtil.js | JavaScript | gpl-2.0 | 5,495 |
Locale.define("sv-SE","Number",{currency:{prefix:"SEK "}}).inherit("EU","Number"); | slackero/phpwcms | template/lib/mootools/more-1.4/Locale/Locale.sv-SE.Number.js | JavaScript | gpl-2.0 | 82 |
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
var gruntTasksPath = './grunt_tasks';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
autoprefixer: require(gruntTasksPath+'/autoprefixer'),
clean: require(gruntTasksPath+'/clean'),
cssmin: require(gruntTasksPath+'/cssmin'),
connect: require(gruntTasksPath+'/connect'),
copy: require(gruntTasksPath+'/copy'),
mkdir: require(gruntTasksPath+'/mkdir'),
jade: require(gruntTasksPath+'/jade'),
stylus: require(gruntTasksPath+'/stylus'),
uglify: require(gruntTasksPath+'/uglify'),
watch: require(gruntTasksPath+'/watch')
});
grunt.registerTask('init', ['mkdir:base']);
grunt.registerTask('default', ['clean', 'copy', 'uglify', 'jade', 'stylus', 'autoprefixer', 'cssmin', 'connect', 'watch']);
}; | zaundef/geolocation | Gruntfile.js | JavaScript | gpl-2.0 | 805 |
/*
* Copyright (c) 2008-2014 CoNWeT Lab., Universidad Politécnica de Madrid
*
* This file is part of Wirecloud Platform.
*
* Wirecloud Platform is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Wirecloud is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Wirecloud Platform. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
/*global Wirecloud */
(function () {
"use strict";
/**
* @class Represents a size in several units.
*/
var MultiValuedSize = function MultiValuedSize(inPixels, inLU) {
Object.defineProperties(this, {
inPixels: {value: inPixels},
inLU: {value: inLU}
});
};
Wirecloud.ui.MultiValuedSize = MultiValuedSize;
})();
| sixuanwang/SAMSaaS | wirecloud-develop/src/wirecloud/platform/static/js/wirecloud/ui/MultiValuedSize.js | JavaScript | gpl-2.0 | 1,252 |
ace.define("ace/snippets/batchfile",["require","exports","module"],function(e,i,t){i.snippetText="",i.scope="batchfile"}); | lealife/leanote-bin | public/member/js/ace/snippets/ck/batchfile-min.js | JavaScript | gpl-2.0 | 122 |
/* Authors:
* Adam Young <[email protected]>
*
* Copyright (C) 2010 Red Hat
* see file 'COPYING' for use and warranty information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
define([
'./ipa',
'./jquery',
'./phases',
'./reg',
'./details',
'./search',
'./association',
'./entity'],
function(IPA, $, phases, reg) {
var exp = {};
exp.pwpolicy = IPA.pwpolicy = {};
var make_pwpolicy_spec = function() {
return {
name: 'pwpolicy',
facets: [
{
$type: 'search',
sort_enabled: false,
columns:['cn','cospriority']
},
{
$type: 'details',
sections:[
{
name : 'identity',
fields:[
{
$type: 'link',
name: 'cn',
other_entity: 'group'
},
'krbmaxpwdlife',
'krbminpwdlife',
{
name: 'krbpwdhistorylength',
measurement_unit: 'number_of_passwords'
},
'krbpwdmindiffchars',
'krbpwdminlength',
'krbpwdmaxfailure',
{
name: 'krbpwdfailurecountinterval',
measurement_unit: 'seconds'
},
{
name: 'krbpwdlockoutduration',
measurement_unit: 'seconds'
},
{
name: 'cospriority',
required: true
}
]
}]
}
],
standard_association_facets: true,
adder_dialog: {
title: '@i18n:objects.pwpolicy.add',
fields: [
{
$type: 'entity_select',
name: 'cn',
other_entity: 'group',
other_field: 'cn',
required: true
},
{
name: 'cospriority',
required: true
}
],
height: 300
},
deleter_dialog: {
title: '@i18n:objects.pwpolicy.remove'
}
};};
exp.krbtpolicy = IPA.krbtpolicy = {};
var make_krbtpolicy_spec = function() {
return {
name: 'krbtpolicy',
facets: [
{
$type: 'details',
title: '@mo:krbtpolicy.label',
sections: [
{
name: 'identity',
fields: [
{
name: 'krbmaxrenewableage',
measurement_unit: 'seconds'
},
{
name: 'krbmaxticketlife',
measurement_unit: 'seconds'
}
]
},
{
name: 'auth_indicators',
label: '@i18n:authtype.auth_indicators',
fields: [
{
name: 'krbauthindmaxrenewableage_radius',
acl_param: 'krbauthindmaxrenewableage',
measurement_unit: 'seconds'
},
{
name: 'krbauthindmaxticketlife_radius',
acl_param: 'krbauthindmaxticketlife',
measurement_unit: 'seconds'
},
{
name: 'krbauthindmaxrenewableage_otp',
acl_param: 'krbauthindmaxrenewableage',
measurement_unit: 'seconds'
},
{
name: 'krbauthindmaxticketlife_otp',
acl_param: 'krbauthindmaxticketlife',
measurement_unit: 'seconds'
},
{
name: 'krbauthindmaxrenewableage_pkinit',
acl_param: 'krbauthindmaxrenewableage',
measurement_unit: 'seconds'
},
{
name: 'krbauthindmaxticketlife_pkinit',
acl_param: 'krbauthindmaxticketlife',
measurement_unit: 'seconds'
},
{
name: 'krbauthindmaxrenewableage_hardened',
acl_param: 'krbauthindmaxrenewableage',
measurement_unit: 'seconds'
},
{
name: 'krbauthindmaxticketlife_hardened',
acl_param: 'krbauthindmaxticketlife',
measurement_unit: 'seconds'
}
]
}
],
needs_update: true
}
]
};};
exp.pwpolicy_spec = make_pwpolicy_spec();
exp.krbtpolicy_spec = make_krbtpolicy_spec();
exp.register = function() {
var e = reg.entity;
e.register({type: 'pwpolicy', spec: exp.pwpolicy_spec});
e.register({type: 'krbtpolicy', spec: exp.krbtpolicy_spec});
};
phases.on('registration', exp.register);
return exp;
});
| encukou/freeipa | install/ui/src/freeipa/policy.js | JavaScript | gpl-3.0 | 6,306 |
import Ember from 'ember';
export default Ember.Mixin.create({
session: Ember.inject.service(),
defaultCapabilities: {
admin: [
'User Administrator',
'System Administrator',
'Quality'
],
add_allergy: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'System Administrator'
],
appointments: [
'Data Entry',
'Finance',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'Social Worker',
'System Administrator',
'Cashier'
],
add_appointment: [
'Data Entry',
'Finance',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'Social Worker',
'System Administrator',
'Cashier'
],
add_charge: [
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
add_billing_diagnosis: [
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
add_diagnosis: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'System Administrator'
],
add_medication: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Pharmacist',
'System Administrator'
],
add_operative_plan: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'System Administrator'
],
add_operation_report: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'System Administrator'
],
add_photo: [
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'Social Worker',
'System Administrator'
],
add_patient: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'Social Worker',
'System Administrator'
],
add_pricing: [
'Data Entry',
'Finance',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
add_pricing_profile: [
'Data Entry',
'Finance',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
add_lab: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Lab Technician',
'System Administrator'
],
add_imaging: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Imaging Technician',
'Medical Records Officer',
'System Administrator'
],
add_inventory_request: [
'Data Entry',
'Hospital Administrator',
'Inventory Manager',
'Medical Records Officer',
'Nurse Manager',
'Pharmacist',
'System Administrator'
],
add_inventory_item: [
'Data Entry',
'Hospital Administrator',
'Inventory Manager',
'Medical Records Officer',
'System Administrator'
],
add_inventory_purchase: [
'Data Entry',
'Hospital Administrator',
'Inventory Manager',
'Medical Records Officer',
'System Administrator'
],
add_invoice: [
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator',
'Cashier'
],
add_payment: [
'Hospital Administrator',
'Medical Records Officer',
'System Administrator',
'Cashier'
],
add_procedure: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'System Administrator'
],
add_socialwork: [
'Hospital Administrator',
'Medical Records Officer',
'Social Worker',
'System Administrator'
],
add_user: [
'User Administrator',
'System Administrator'
],
add_visit: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'Social Worker',
'System Administrator'
],
add_vitals: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'System Administrator'
],
add_report: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'System Administrator'
],
admit_patient: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'Social Worker',
'System Administrator'
],
adjust_inventory_location: [
'Hospital Administrator',
'Inventory Manager',
'Medical Records Officer',
'System Administrator'
],
billing: [
'Hospital Administrator',
'Finance',
'Finance Manager',
'System Administrator',
'Cashier'
],
cashier: [
'Cashier',
'System Administrator'
],
complete_imaging: [
'Imaging Technician',
'Medical Records Officer',
'System Administrator'
],
complete_lab: [
'Lab Technician',
'Medical Records Officer',
'System Administrator'
],
delete_appointment: [
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'Social Worker',
'System Administrator'
],
delete_diagnosis: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'System Administrator'
],
delete_inventory_item: [
'Hospital Administrator',
'Inventory Manager',
'Medical Records Officer',
'System Administrator'
],
delete_imaging: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
delete_invoice: [
'Hospital Administrator',
'System Administrator'
],
delete_lab: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
delete_medication: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
delete_photo: [
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'Social Worker',
'System Administrator'
],
delete_patient: [
'Hospital Administrator',
'Medical Records Officer',
'Patient Administration',
'System Administrator'
],
delete_pricing: [
'Finance',
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
delete_pricing_profile: [
'Finance',
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
delete_procedure: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'System Administrator'
],
delete_socialwork: [
'Hospital Administrator',
'Medical Records Officer',
'Social Worker',
'System Administrator'
],
delete_vitals: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'System Administrator'
],
delete_report: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'System Administrator'
],
delete_visit: [
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'Social Worker',
'System Administrator'
],
delete_user: [
'User Administrator',
'System Administrator'
],
discharge_patient: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'Social Worker',
'System Administrator'
],
edit_invoice: [
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
fulfill_inventory: [
'Hospital Administrator',
'Inventory Manager',
'Medical Records Officer',
'Pharmacist',
'System Administrator'
],
fulfill_medication: [
'Medical Records Officer',
'Pharmacist',
'System Administrator'
],
imaging: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Imaging Technician',
'Medical Records Officer',
'System Administrator'
],
invoices: [
'Hospital Administrator',
'Finance',
'Finance Manager',
'System Administrator',
'Cashier'
],
labs: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Lab Technician',
'Medical Records Officer',
'System Administrator'
],
list_paid_invoices: [
'Data Entry',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
medication: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Pharmacist',
'System Administrator'
],
inventory: [
'Data Entry',
'Hospital Administrator',
'Inventory Manager',
'Medical Records Officer',
'Nurse Manager',
'Pharmacist',
'System Administrator'
],
load_db: [
'System Administrator'
],
override_invoice: [
'Hospital Administrator',
'System Administrator',
'Cashier'
],
query_db: [
'System Administrator'
],
patients: [
'Data Entry',
'Doctor',
'Finance',
'Finance Manager',
'Hospital Administrator',
'Imaging Technician',
'Lab Technician',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'Social Worker',
'System Administrator'
],
patient_reports: [
'Hospital Administrator',
'Patient Administration',
'System Administrator'
],
pricing: [
'Data Entry',
'Finance',
'Hospital Administrator',
'Medical Records Officer',
'System Administrator'
],
print_invoice: [
'Cashier',
'System Adminstrator'
],
review_invoice: [
'Cashier',
'System Administrator'
],
visits: [
'Data Entry',
'Doctor',
'Hospital Administrator',
'Medical Records Officer',
'Nurse Manager',
'Nurse',
'Patient Administration',
'Social Worker',
'System Administrator'
],
incident: [
'Hospital Staff',
'User Administrator',
'Quality',
'System Administrator'
],
add_incident: [
'Hospital Staff',
'User Administrator',
'Quality',
'System Administrator'
],
delete_incident: [
'Quality',
'System Administrator'
],
generate_incident_report: [
'User Administrator',
'Quality',
'System Administrator'
],
add_incident_category: [
'User Administrator',
'Quality',
'System Administrator'
],
delete_incident_category: [
'Quality',
'System Administrator'
],
manage_incidents: [
'Quality',
'System Administrator'
],
update_config: [
'System Administrator'
],
users: [
'User Administrator',
'System Administrator',
'Quality'
],
add_note: [
'Doctor',
'Medical Records Officer',
'Nurse',
'Nurse Manager',
'Patient Administration',
'System Administrator'
],
delete_note: [
'Medical Records Officer',
'Nurse Manager',
'Patient Administration',
'System Administrator'
],
'define_user_roles': [
'System Administrator'
]
},
_getUserSessionVars() {
let session = this.get('session');
if (!Ember.isEmpty(session) && session.get('isAuthenticated')) {
return session.get('data.authenticated');
}
},
currentUserRole() {
let sessionVars = this._getUserSessionVars();
if (!Ember.isEmpty(sessionVars) && !Ember.isEmpty(sessionVars.role)) {
return sessionVars.role;
}
return null;
},
currentUserCan(capability) {
let sessionVars = this._getUserSessionVars();
if (!Ember.isEmpty(sessionVars) && !Ember.isEmpty(sessionVars.role)) {
let userCaps = this.get('session').get('data.authenticated.userCaps');
if (Ember.isEmpty(userCaps)) {
let capabilities = this.get('defaultCapabilities');
let supportedRoles = capabilities[capability];
if (!Ember.isEmpty(supportedRoles)) {
return supportedRoles.includes(sessionVars.role);
}
} else {
return userCaps.includes(capability.camelize()); // User defined capabilities are camelcased.
}
}
return false;
},
/**
* Returns the display name of the user or the username if
* the display name is not set or if the username is explictly requested.
* @param {boolean} returnUserName if true, always return the username instead
* of the display name even if the display name is set.
*/
getUserName(returnUserName) {
let returnName;
let sessionVars = this._getUserSessionVars();
if (!Ember.isEmpty(sessionVars)) {
if (returnUserName) {
returnName = sessionVars.name;
} else if (!Ember.isEmpty(sessionVars.displayName)) {
returnName = sessionVars.displayName;
} else if (!Ember.isEmpty(sessionVars.name)) {
returnName = sessionVars.name;
}
}
return returnName;
}
});
| tsaron/dariya | app/mixins/user-session.js | JavaScript | gpl-3.0 | 14,503 |
'use strict';
(function () {
let logoutTimer = 0;
let logoutMessage;
function startLogoutTimer() {
if (app.config.adminReloginDuration <= 0) {
return;
}
if (logoutTimer) {
clearTimeout(logoutTimer);
}
// pre-translate language string gh#9046
if (!logoutMessage) {
require(['translator'], function (translator) {
translator.translate('[[login:logged-out-due-to-inactivity]]', function (translated) {
logoutMessage = translated;
});
});
}
logoutTimer = setTimeout(function () {
require(['bootbox'], function (bootbox) {
bootbox.alert({
closeButton: false,
message: logoutMessage,
callback: function () {
window.location.reload();
},
});
});
}, 3600000);
}
require(['hooks'], (hooks) => {
hooks.on('action:ajaxify.end', () => {
showCorrectNavTab();
startLogoutTimer();
});
});
function showCorrectNavTab() {
// show correct tab if url has #
if (window.location.hash) {
$('.nav-pills a[href="' + window.location.hash + '"]').tab('show');
}
}
$(document).ready(function () {
if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
require(['admin/modules/search'], function (search) {
search.init();
});
}
$('[component="logout"]').on('click', function () {
require(['logout'], function (logout) {
logout();
});
return false;
});
configureSlidemenu();
setupNProgress();
});
$(window).on('action:ajaxify.contentLoaded', function (ev, data) {
selectMenuItem(data.url);
setupRestartLinks();
componentHandler.upgradeDom();
});
function setupNProgress() {
require(['nprogress', 'hooks'], function (NProgress, hooks) {
$(window).on('action:ajaxify.start', function () {
NProgress.set(0.7);
});
hooks.on('action:ajaxify.end', function () {
NProgress.done();
});
});
}
function selectMenuItem(url) {
require(['translator'], function (translator) {
url = url
.replace(/\/\d+$/, '')
.split('/').slice(0, 3).join('/')
.split(/[?#]/)[0].replace(/(\/+$)|(^\/+)/, '');
// If index is requested, load the dashboard
if (url === 'admin') {
url = 'admin/dashboard';
}
url = [config.relative_path, url].join('/');
let fallback;
$('#main-menu li').removeClass('active');
$('#main-menu a').removeClass('active').filter('[href="' + url + '"]').each(function () {
const menu = $(this);
if (menu.parent().attr('data-link')) {
return;
}
menu
.parent().addClass('active')
.parents('.menu-item').addClass('active');
fallback = menu.text();
});
let mainTitle;
let pageTitle;
if (/admin\/plugins\//.test(url)) {
mainTitle = fallback;
pageTitle = '[[admin/menu:section-plugins]] > ' + mainTitle;
} else {
const matches = url.match(/admin\/(.+?)\/(.+?)$/);
if (matches) {
mainTitle = '[[admin/menu:' + matches[1] + '/' + matches[2] + ']]';
pageTitle = '[[admin/menu:section-' +
(matches[1] === 'development' ? 'advanced' : matches[1]) +
']]' + (matches[2] ? (' > ' + mainTitle) : '');
if (matches[2] === 'settings') {
mainTitle = translator.compile('admin/menu:settings.page-title', mainTitle);
}
} else {
mainTitle = '[[admin/menu:section-dashboard]]';
pageTitle = '[[admin/menu:section-dashboard]]';
}
}
pageTitle = translator.compile('admin/admin:acp-title', pageTitle);
translator.translate(pageTitle, function (title) {
document.title = title.replace(/>/g, '>');
});
translator.translate(mainTitle, function (text) {
$('#main-page-title').text(text);
});
});
}
function setupRestartLinks() {
$('.rebuild-and-restart').off('click').on('click', function () {
require(['bootbox'], function (bootbox) {
bootbox.confirm('[[admin/admin:alert.confirm-rebuild-and-restart]]', function (confirm) {
if (confirm) {
require(['admin/modules/instance'], function (instance) {
instance.rebuildAndRestart();
});
}
});
});
});
$('.restart').off('click').on('click', function () {
require(['bootbox'], function (bootbox) {
bootbox.confirm('[[admin/admin:alert.confirm-restart]]', function (confirm) {
if (confirm) {
require(['admin/modules/instance'], function (instance) {
instance.restart();
});
}
});
});
});
}
function configureSlidemenu() {
require(['slideout'], function (Slideout) {
let env = utils.findBootstrapEnvironment();
const slideout = new Slideout({
panel: document.getElementById('panel'),
menu: document.getElementById('menu'),
padding: 256,
tolerance: 70,
});
if (env === 'md' || env === 'lg') {
slideout.disableTouch();
}
$('#mobile-menu').on('click', function () {
slideout.toggle();
});
$('#menu a').on('click', function () {
slideout.close();
});
$(window).on('resize', function () {
slideout.close();
env = utils.findBootstrapEnvironment();
if (env === 'md' || env === 'lg') {
slideout.disableTouch();
$('#header').css({
position: 'relative',
});
} else {
slideout.enableTouch();
$('#header').css({
position: 'fixed',
});
}
});
function onOpeningMenu() {
$('#header').css({
top: ($('#panel').position().top * -1) + 'px',
position: 'absolute',
});
}
slideout.on('open', onOpeningMenu);
slideout.on('close', function () {
$('#header').css({
top: '0px',
position: 'fixed',
});
});
});
}
// tell ace to use the right paths when requiring modules
require(['ace/ace'], function (ace) {
ace.config.set('packaged', true);
ace.config.set('basePath', config.relative_path + '/assets/src/modules/ace/');
});
}());
| MicroWorldwide/NodeBB | public/src/admin/admin.js | JavaScript | gpl-3.0 | 5,815 |
var Modeler = require("../Modeler.js");
var className = 'ElementDescribeNetworkInterfaces';
var ElementDescribeNetworkInterfaces = function(json, parentObj) {
parentObj = parentObj || this;
// Class property definitions here:
Modeler.extend(className, {
DescribeNetworkInterfaces: {
type: "TypeDescribeNetworkInterfacesType",
wsdlDefinition: {
name: "DescribeNetworkInterfaces",
type: "tns:DescribeNetworkInterfacesType"
},
mask: Modeler.GET | Modeler.SET,
required: false
}
}, parentObj, json);
};
module.exports = ElementDescribeNetworkInterfaces;
Modeler.register(ElementDescribeNetworkInterfaces, "ElementDescribeNetworkInterfaces");
| holidayextras/wsdl2.js | example/EC2/Element/DescribeNetworkInterfaces.js | JavaScript | gpl-3.0 | 702 |
/*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dijit._Templated"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit._Templated"] = true;
dojo.provide("dijit._Templated");
dojo.require("dijit._Widget");
dojo.require("dojo.string");
dojo.require("dojo.parser");
dojo.declare("dijit._Templated",
null,
{
// summary:
// Mixin for widgets that are instantiated from a template
//
// templateNode: DomNode
// a node that represents the widget template. Pre-empts both templateString and templatePath.
templateNode: null,
// templateString: String
// a string that represents the widget template. Pre-empts the
// templatePath. In builds that have their strings "interned", the
// templatePath is converted to an inline templateString, thereby
// preventing a synchronous network call.
templateString: null,
// templatePath: String
// Path to template (HTML file) for this widget relative to dojo.baseUrl
templatePath: null,
// widgetsInTemplate: Boolean
// should we parse the template to find widgets that might be
// declared in markup inside it? false by default.
widgetsInTemplate: false,
// skipNodeCache: Boolean
// if using a cached widget template node poses issues for a
// particular widget class, it can set this property to ensure
// that its template is always re-built from a string
_skipNodeCache: false,
_stringRepl: function(tmpl){
var className = this.declaredClass, _this = this;
// Cache contains a string because we need to do property replacement
// do the property replacement
return dojo.string.substitute(tmpl, this, function(value, key){
if(key.charAt(0) == '!'){ value = _this[key.substr(1)]; }
if(typeof value == "undefined"){ throw new Error(className+" template:"+key); } // a debugging aide
if(value == null){ return ""; }
// Substitution keys beginning with ! will skip the transform step,
// in case a user wishes to insert unescaped markup, e.g. ${!foo}
return key.charAt(0) == "!" ? value :
// Safer substitution, see heading "Attribute values" in
// http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2
value.toString().replace(/"/g,"""); //TODO: add &? use encodeXML method?
}, this);
},
// method over-ride
buildRendering: function(){
// summary:
// Construct the UI for this widget from a template, setting this.domNode.
// Lookup cached version of template, and download to cache if it
// isn't there already. Returns either a DomNode or a string, depending on
// whether or not the template contains ${foo} replacement parameters.
var cached = dijit._Templated.getCachedTemplate(this.templatePath, this.templateString, this._skipNodeCache);
var node;
if(dojo.isString(cached)){
node = dijit._Templated._createNodesFromText(this._stringRepl(cached))[0];
}else{
// if it's a node, all we have to do is clone it
node = cached.cloneNode(true);
}
this.domNode = node;
// recurse through the node, looking for, and attaching to, our
// attachment points and events, which should be defined on the template node.
this._attachTemplateNodes(node);
var source = this.srcNodeRef;
if(source && source.parentNode){
source.parentNode.replaceChild(node, source);
}
if(this.widgetsInTemplate){
var cw = (this._supportingWidgets = dojo.parser.parse(node));
this._attachTemplateNodes(cw, function(n,p){
return n[p];
});
}
this._fillContent(source);
},
_fillContent: function(/*DomNode*/ source){
// summary:
// relocate source contents to templated container node
// this.containerNode must be able to receive children, or exceptions will be thrown
var dest = this.containerNode;
if(source && dest){
while(source.hasChildNodes()){
dest.appendChild(source.firstChild);
}
}
},
_attachTemplateNodes: function(rootNode, getAttrFunc){
// summary: Iterate through the template and attach functions and nodes accordingly.
// description:
// Map widget properties and functions to the handlers specified in
// the dom node and it's descendants. This function iterates over all
// nodes and looks for these properties:
// * dojoAttachPoint
// * dojoAttachEvent
// * waiRole
// * waiState
// rootNode: DomNode|Array[Widgets]
// the node to search for properties. All children will be searched.
// getAttrFunc: function?
// a function which will be used to obtain property for a given
// DomNode/Widget
getAttrFunc = getAttrFunc || function(n,p){ return n.getAttribute(p); };
var nodes = dojo.isArray(rootNode) ? rootNode : (rootNode.all || rootNode.getElementsByTagName("*"));
var x = dojo.isArray(rootNode) ? 0 : -1;
var attrs = {};
for(; x<nodes.length; x++){
var baseNode = (x == -1) ? rootNode : nodes[x];
if(this.widgetsInTemplate && getAttrFunc(baseNode, "dojoType")){
continue;
}
// Process dojoAttachPoint
var attachPoint = getAttrFunc(baseNode, "dojoAttachPoint");
if(attachPoint){
var point, points = attachPoint.split(/\s*,\s*/);
while((point = points.shift())){
if(dojo.isArray(this[point])){
this[point].push(baseNode);
}else{
this[point]=baseNode;
}
}
}
// Process dojoAttachEvent
var attachEvent = getAttrFunc(baseNode, "dojoAttachEvent");
if(attachEvent){
// NOTE: we want to support attributes that have the form
// "domEvent: nativeEvent; ..."
var event, events = attachEvent.split(/\s*,\s*/);
var trim = dojo.trim;
while((event = events.shift())){
if(event){
var thisFunc = null;
if(event.indexOf(":") != -1){
// oh, if only JS had tuple assignment
var funcNameArr = event.split(":");
event = trim(funcNameArr[0]);
thisFunc = trim(funcNameArr[1]);
}else{
event = trim(event);
}
if(!thisFunc){
thisFunc = event;
}
this.connect(baseNode, event, thisFunc);
}
}
}
// waiRole, waiState
var role = getAttrFunc(baseNode, "waiRole");
if(role){
dijit.setWaiRole(baseNode, role);
}
var values = getAttrFunc(baseNode, "waiState");
if(values){
dojo.forEach(values.split(/\s*,\s*/), function(stateValue){
if(stateValue.indexOf('-') != -1){
var pair = stateValue.split('-');
dijit.setWaiState(baseNode, pair[0], pair[1]);
}
});
}
}
}
}
);
// key is either templatePath or templateString; object is either string or DOM tree
dijit._Templated._templateCache = {};
dijit._Templated.getCachedTemplate = function(templatePath, templateString, alwaysUseString){
// summary:
// Static method to get a template based on the templatePath or
// templateString key
// templatePath: String
// The URL to get the template from. dojo.uri.Uri is often passed as well.
// templateString: String?
// a string to use in lieu of fetching the template from a URL. Takes precedence
// over templatePath
// Returns: Mixed
// Either string (if there are ${} variables that need to be replaced) or just
// a DOM tree (if the node can be cloned directly)
// is it already cached?
var tmplts = dijit._Templated._templateCache;
var key = templateString || templatePath;
var cached = tmplts[key];
if(cached){
if(!cached.ownerDocument || cached.ownerDocument == dojo.doc){
// string or node of the same document
return cached;
}
// destroy the old cached node of a different document
dojo._destroyElement(cached);
}
// If necessary, load template string from template path
if(!templateString){
templateString = dijit._Templated._sanitizeTemplateString(dojo._getText(templatePath));
}
templateString = dojo.string.trim(templateString);
if(alwaysUseString || templateString.match(/\$\{([^\}]+)\}/g)){
// there are variables in the template so all we can do is cache the string
return (tmplts[key] = templateString); //String
}else{
// there are no variables in the template so we can cache the DOM tree
return (tmplts[key] = dijit._Templated._createNodesFromText(templateString)[0]); //Node
}
};
dijit._Templated._sanitizeTemplateString = function(/*String*/tString){
// summary:
// Strips <?xml ...?> declarations so that external SVG and XML
// documents can be added to a document without worry. Also, if the string
// is an HTML document, only the part inside the body tag is returned.
if(tString){
tString = tString.replace(/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, "");
var matches = tString.match(/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im);
if(matches){
tString = matches[1];
}
}else{
tString = "";
}
return tString; //String
};
if(dojo.isIE){
dojo.addOnWindowUnload(function(){
var cache = dijit._Templated._templateCache;
for(var key in cache){
var value = cache[key];
if(!isNaN(value.nodeType)){ // isNode equivalent
dojo._destroyElement(value);
}
delete cache[key];
}
});
}
(function(){
var tagMap = {
cell: {re: /^<t[dh][\s\r\n>]/i, pre: "<table><tbody><tr>", post: "</tr></tbody></table>"},
row: {re: /^<tr[\s\r\n>]/i, pre: "<table><tbody>", post: "</tbody></table>"},
section: {re: /^<(thead|tbody|tfoot)[\s\r\n>]/i, pre: "<table>", post: "</table>"}
};
// dummy container node used temporarily to hold nodes being created
var tn;
dijit._Templated._createNodesFromText = function(/*String*/text){
// summary:
// Attempts to create a set of nodes based on the structure of the passed text.
if(tn && tn.ownerDocument != dojo.doc){
// destroy dummy container of a different document
dojo._destroyElement(tn);
tn = undefined;
}
if(!tn){
tn = dojo.doc.createElement("div");
tn.style.display="none";
dojo.body().appendChild(tn);
}
var tableType = "none";
var rtext = text.replace(/^\s+/, "");
for(var type in tagMap){
var map = tagMap[type];
if(map.re.test(rtext)){
tableType = type;
text = map.pre + text + map.post;
break;
}
}
tn.innerHTML = text;
if(tn.normalize){
tn.normalize();
}
var tag = { cell: "tr", row: "tbody", section: "table" }[tableType];
var _parent = (typeof tag != "undefined") ?
tn.getElementsByTagName(tag)[0] :
tn;
var nodes = [];
while(_parent.firstChild){
nodes.push(_parent.removeChild(_parent.firstChild));
}
tn.innerHTML="";
return nodes; // Array
}
})();
// These arguments can be specified for widgets which are used in templates.
// Since any widget can be specified as sub widgets in template, mix it
// into the base widget class. (This is a hack, but it's effective.)
dojo.extend(dijit._Widget,{
dojoAttachEvent: "",
dojoAttachPoint: "",
waiRole: "",
waiState:""
})
}
| emogames-gbr/syndicates | src/public/php/dojo/dijit/_Templated.js | JavaScript | gpl-3.0 | 11,057 |
/* eslint-env node, es6 */
const { registerSuite } = intern.getPlugin("interface.object");
const { requireRoot } = require("./util");
const buildUtil = requireRoot("scripts/build-util");
const assert = require("assert");
// const { assert } = intern.getPlugin("chai");
registerSuite("build-util", {
tests: {
/**
* Test requireAmd on our build utils.
* @returns {Promise} resolved when done.
*/
testRequireAmd: function () {
return new Promise(function (win) {
buildUtil.requireAmd(["wc/global"], function(global) {
assert.strictEqual(global, this);
win();
});
});
}
}
});
| BorderTech/wcomponents | wcomponents-theme/src/test/unit/build-util.test.js | JavaScript | gpl-3.0 | 615 |
module.exports = {
book: {
assets: './assets',
css: [
'plugin.css'
]
},
blocks: {
em: {
process: function(block) {
var type = block.kwargs.type || 'yellow';
var color = block.kwargs.color;
var style = '';
if (color) {
style = 'background: '+color+';';
}
var body = ('<span class="pg-emphasize pg-emphasize-'+type+'" style="'+style+'">'
+ (block.body)
+ '</span>');
return {
body: body,
parse: true
};
}
}
}
};
| WaysonKong/blog | node_modules/gitbook-plugin-emphasize/index.js | JavaScript | gpl-3.0 | 734 |
/*
* (c) Copyright The SIMILE Project 2006. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Note: JQuery, www.jquery.com is included in the Ajax section of this
* distribution. It is covered by its own license:
*
* Copyright (c) 2008 John Resig (jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
/*!
* Copyright 2002 - 2015 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/*==================================================
* Common localization strings
*==================================================
*/
Timeline.strings["it"] = {
wikiLinkLabel: "Discuti"
};
| krivera-pentaho/cdf | core-js/src/main/javascript/lib/simile/timeline/scripts/l10n/it/timeline.js | JavaScript | mpl-2.0 | 2,646 |
// META: global=window,worker,jsshell
// META: script=../resources/test-utils.js
// META: script=../resources/recording-streams.js
'use strict';
function interceptThen() {
const intercepted = [];
const callCount = 0;
Object.prototype.then = function(resolver) {
if (!this.done) {
intercepted.push(this.value);
}
const retval = Object.create(null);
retval.done = ++callCount === 3;
retval.value = callCount;
resolver(retval);
if (retval.done) {
delete Object.prototype.then;
}
}
return intercepted;
}
promise_test(async () => {
const rs = new ReadableStream({
start(controller) {
controller.enqueue('a');
controller.close();
}
});
const ws = recordingWritableStream();
const intercepted = interceptThen();
await rs.pipeTo(ws);
delete Object.prototype.then;
assert_array_equals(intercepted, [], 'nothing should have been intercepted');
assert_array_equals(ws.events, ['write', 'a', 'close'], 'written chunk should be "a"');
}, 'piping should not be observable');
promise_test(async () => {
const rs = new ReadableStream({
start(controller) {
controller.enqueue('a');
controller.close();
}
});
const ws = recordingWritableStream();
const [ branch1, branch2 ] = rs.tee();
const intercepted = interceptThen();
await branch1.pipeTo(ws);
delete Object.prototype.then;
branch2.cancel();
assert_array_equals(intercepted, [], 'nothing should have been intercepted');
assert_array_equals(ws.events, ['write', 'a', 'close'], 'written chunk should be "a"');
}, 'tee should not be observable');
| Acidburn0zzz/servo | tests/wpt/web-platform-tests/streams/piping/then-interception.any.js | JavaScript | mpl-2.0 | 1,622 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Owner: [email protected]
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
define(function(require, exports, module) {
var Constraint = require('./Constraint');
var Wall = require('./Wall');
var Vector = require('../../math/Vector');
/**
* Walls combines one or more Wall primitives and exposes a simple API to
* interact with several walls at once. A common use case would be to set up
* a bounding box for a physics body, that would collide with each side.
*
* @class Walls
* @constructor
* @extends Constraint
* @uses Wall
* @param {Options} [options] An object of configurable options.
* @param {Array} [options.sides] An array of sides e.g., [Walls.LEFT, Walls.TOP]
* @param {Array} [options.size] The size of the bounding box of the walls.
* @param {Array} [options.origin] The center of the wall relative to the size.
* @param {Array} [options.drift] Baumgarte stabilization parameter. Makes constraints "loosely" (0) or "tightly" (1) enforced. Range : [0, 1]
* @param {Array} [options.slop] Amount of penetration in pixels to ignore before collision event triggers.
* @param {Array} [options.restitution] The energy ratio lost in a collision (0 = stick, 1 = elastic) The energy ratio lost in a collision (0 = stick, 1 = elastic)
* @param {Array} [options.onContact] How to handle collision against the wall.
*/
function Walls(options) {
this.options = Object.create(Walls.DEFAULT_OPTIONS);
if (options) this.setOptions(options);
_createComponents.call(this, options.sides || this.options.sides);
Constraint.call(this);
}
Walls.prototype = Object.create(Constraint.prototype);
Walls.prototype.constructor = Walls;
/**
* @property Walls.ON_CONTACT
* @type Object
* @extends Wall.ON_CONTACT
* @static
*/
Walls.ON_CONTACT = Wall.ON_CONTACT;
/**
* An enumeration of common types of walls
* LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK
* TWO_DIMENSIONAL, THREE_DIMENSIONAL
*
* @property Walls.SIDES
* @type Object
* @final
* @static
*/
Walls.SIDES = {
LEFT : 0,
RIGHT : 1,
TOP : 2,
BOTTOM : 3,
FRONT : 4,
BACK : 5,
TWO_DIMENSIONAL : [0, 1, 2, 3],
THREE_DIMENSIONAL : [0, 1, 2, 3, 4, 5]
};
Walls.DEFAULT_OPTIONS = {
sides : Walls.SIDES.TWO_DIMENSIONAL,
size : [window.innerWidth, window.innerHeight, 0],
origin : [.5, .5, .5],
drift : 0.5,
slop : 0,
restitution : 0.5,
onContact : Walls.ON_CONTACT.REFLECT
};
var _SIDE_NORMALS = {
0 : new Vector(1, 0, 0),
1 : new Vector(-1, 0, 0),
2 : new Vector(0, 1, 0),
3 : new Vector(0,-1, 0),
4 : new Vector(0, 0, 1),
5 : new Vector(0, 0,-1)
};
function _getDistance(side, size, origin) {
var distance;
var SIDES = Walls.SIDES;
switch (parseInt(side)) {
case SIDES.LEFT:
distance = size[0] * origin[0];
break;
case SIDES.TOP:
distance = size[1] * origin[1];
break;
case SIDES.FRONT:
distance = size[2] * origin[2];
break;
case SIDES.RIGHT:
distance = size[0] * (1 - origin[0]);
break;
case SIDES.BOTTOM:
distance = size[1] * (1 - origin[1]);
break;
case SIDES.BACK:
distance = size[2] * (1 - origin[2]);
break;
}
return distance;
}
/*
* Setter for options.
*
* @method setOptions
* @param options {Objects}
*/
Walls.prototype.setOptions = function setOptions(options) {
var resizeFlag = false;
if (options.restitution !== undefined) _setOptionsForEach.call(this, {restitution : options.restitution});
if (options.drift !== undefined) _setOptionsForEach.call(this, {drift : options.drift});
if (options.slop !== undefined) _setOptionsForEach.call(this, {slop : options.slop});
if (options.onContact !== undefined) _setOptionsForEach.call(this, {onContact : options.onContact});
if (options.size !== undefined) resizeFlag = true;
if (options.sides !== undefined) this.options.sides = options.sides;
if (options.origin !== undefined) resizeFlag = true;
if (resizeFlag) this.setSize(options.size, options.origin);
};
function _createComponents(sides) {
this.components = {};
var components = this.components;
for (var i = 0; i < sides.length; i++) {
var side = sides[i];
components[i] = new Wall({
normal : _SIDE_NORMALS[side].clone(),
distance : _getDistance(side, this.options.size, this.options.origin)
});
}
}
/*
* Setter for size.
*
* @method setOptions
* @param options {Objects}
*/
Walls.prototype.setSize = function setSize(size, origin) {
origin = origin || this.options.origin;
if (origin.length < 3) origin[2] = 0.5;
this.forEach(function(wall, side) {
var d = _getDistance(side, size, origin);
wall.setOptions({distance : d});
});
this.options.size = size;
this.options.origin = origin;
};
function _setOptionsForEach(options) {
this.forEach(function(wall) {
wall.setOptions(options);
});
for (var key in options) this.options[key] = options[key];
}
/**
* Adds an impulse to a physics body's velocity due to the walls constraint
*
* @method applyConstraint
* @param targets {Array.Body} Array of bodies to apply the constraint to
* @param source {Body} The source of the constraint
* @param dt {Number} Delta time
*/
Walls.prototype.applyConstraint = function applyConstraint(targets, source, dt) {
this.forEach(function(wall) {
wall.applyConstraint(targets, source, dt);
});
};
/**
* Apply a method to each wall making up the walls
*
* @method applyConstraint
* @param fn {Function} Function that takes in a wall as its first parameter
*/
Walls.prototype.forEach = function forEach(fn) {
var sides = this.options.sides;
for (var key in this.sides) fn(sides[key], key);
};
/**
* Rotates the walls by an angle in the XY-plane
*
* @method applyConstraint
* @param angle {Function}
*/
Walls.prototype.rotateZ = function rotateZ(angle) {
this.forEach(function(wall) {
var n = wall.options.normal;
n.rotateZ(angle).put(n);
});
};
/**
* Rotates the walls by an angle in the YZ-plane
*
* @method applyConstraint
* @param angle {Function}
*/
Walls.prototype.rotateX = function rotateX(angle) {
this.forEach(function(wall) {
var n = wall.options.normal;
n.rotateX(angle).put(n);
});
};
/**
* Rotates the walls by an angle in the XZ-plane
*
* @method applyConstraint
* @param angle {Function}
*/
Walls.prototype.rotateY = function rotateY(angle) {
this.forEach(function(wall) {
var n = wall.options.normal;
n.rotateY(angle).put(n);
});
};
module.exports = Walls;
});
| blitzagency/rich | demos/src/static/js/vendor/famous/physics/constraints/Walls.js | JavaScript | mpl-2.0 | 7,862 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.