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
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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'; // MODULES // var Float32Array = require( '@stdlib/array/float32' ); var addon = require( './smin.native.js' ); // MAIN // /** * Computes the minimum value of a single-precision floating-point strided array. * * @param {PositiveInteger} N - number of indexed elements * @param {Float32Array} x - input array * @param {integer} stride - stride length * @param {NonNegativeInteger} offset - starting index * @returns {number} minimum value * * @example * var Float32Array = require( '@stdlib/array/float32' ); * var floor = require( '@stdlib/math/base/special/floor' ); * * var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] ); * var N = floor( x.length / 2 ); * * var v = smin( N, x, 2, 1 ); * // returns -2.0 */ function smin( N, x, stride, offset ) { var view; if ( stride < 0 ) { offset += (N-1) * stride; } view = new Float32Array( x.buffer, x.byteOffset+(x.BYTES_PER_ELEMENT*offset), x.length-offset ); // eslint-disable-line max-len return addon( N, view, stride ); } // EXPORTS // module.exports = smin;
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/smin/lib/ndarray.native.js
JavaScript
apache-2.0
1,677
/** * Test for LOOMIA TILE Token * * @author Pactum IO <[email protected]> */ import {getEvents, BigNumber} from './helpers/tools'; import expectThrow from './helpers/expectThrow'; const loomiaToken = artifacts.require('./TileToken'); const should = require('chai') // eslint-disable-line .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should(); /** * Tile Token Contract */ contract('TileToken', (accounts) => { const owner = accounts[0]; const tokenHolder1 = accounts[1]; const spendingAddress = accounts[2]; const recipient = accounts[3]; const anotherAccount = accounts[4]; const tokenHolder5 = accounts[5]; const zeroTokenHolder = accounts[6]; const zeroAddress = '0x0000000000000000000000000000000000000000'; const zero = new BigNumber(0); const tokenSupply = new BigNumber(1046000000000000000000000000); // Provide Tile Token instance for every test case let tileTokenInstance; beforeEach(async () => { tileTokenInstance = await loomiaToken.deployed(); }); it('should instantiate the token correctly', async () => { const name = await tileTokenInstance.NAME(); const symbol = await tileTokenInstance.SYMBOL(); const decimals = await tileTokenInstance.DECIMALS(); const totalSupply = await tileTokenInstance.totalSupply(); assert.equal(name, 'LOOMIA TILE', 'Name does not match'); assert.equal(symbol, 'TILE', 'Symbol does not match'); assert.equal(decimals, 18, 'Decimals does not match'); totalSupply.should.be.bignumber.equal(tokenSupply); }); describe('balanceOf', function () { describe('when the requested account has no tokens', function () { it('returns zero', async function () { const balance = await tileTokenInstance.balanceOf(zeroTokenHolder); balance.should.be.bignumber.equal(zero); }); }); describe('when the requested account has some tokens', function () { it('returns the total amount of tokens', async function () { const balance = await tileTokenInstance.balanceOf(owner); balance.should.be.bignumber.equal(tokenSupply); }); }); }); describe('transfer', function () { describe('when the recipient is not the zero address', function () { const to = tokenHolder1; describe('when the sender does not have enough balance', function () { const transferAmount = tokenSupply.add(1); it('reverts', async function () { await expectThrow(tileTokenInstance.transfer(to, transferAmount, { from: owner })); }); }); describe('when the sender has enough balance', function () { const transferAmount = new BigNumber(500 * 1e18); it('transfers the requested amount', async function () { await tileTokenInstance.transfer(to, transferAmount, { from: owner }); const senderBalance = await tileTokenInstance.balanceOf(owner); senderBalance.should.be.bignumber.equal(tokenSupply.sub(transferAmount)); const recipientBalance = await tileTokenInstance.balanceOf(to); recipientBalance.should.be.bignumber.equal(transferAmount); }); it('emits a transfer event', async function () { const tx = await tileTokenInstance.transfer(to, transferAmount, { from: owner }); // Test the event const events = getEvents(tx, 'Transfer'); assert.equal(events[0].from, owner, 'From address does not match'); assert.equal(events[0].to, to, 'To address does not match'); (events[0].value).should.be.bignumber.equal(transferAmount); }); }); }); describe('when the recipient is the zero address', function () { const to = zeroAddress; it('reverts', async function () { await expectThrow(tileTokenInstance.transfer(to, 100, { from: owner })); }); }); }); describe('approve', function () { describe('when the spender is not the zero address', function () { const spender = spendingAddress; describe('when the sender has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { await tileTokenInstance.approve(spender, 1, { from: owner }); }); it('approves the requested amount and replaces the previous one', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(101 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { await tileTokenInstance.approve(spender, 1, { from: owner }); }); it('approves the requested amount and replaces the previous one', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); }); }); describe('when the spender is the zero address', function () { const amount = new BigNumber(100 * 1e18); const spender = zeroAddress; it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); }); }); describe('transfer from', function () { const spender = recipient; describe('when the recipient is not the zero address', function () { const to = anotherAccount; describe('when the spender has enough approved balance', function () { beforeEach(async function () { const approvalAmount = new BigNumber(30000 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); await tileTokenInstance.approve(spender, approvalAmount, { from: zeroTokenHolder }); }); describe('when the owner has enough balance', function () { const amount = new BigNumber(30000 * 1e18); it('transfers the requested amount', async function () { const balanceBefore = await tileTokenInstance.balanceOf(owner); await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); const senderBalance = await tileTokenInstance.balanceOf(owner); senderBalance.should.be.bignumber.equal(balanceBefore.sub(amount)); const recipientBalance = await tileTokenInstance.balanceOf(to); recipientBalance.should.be.bignumber.equal(amount); }); it('decreases the spender allowance', async function () { await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); const allowance = await tileTokenInstance.allowance(owner, spender); assert(allowance.eq(0)); }); it('emits a transfer event', async function () { const tx = await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); // Test the event const events = getEvents(tx, 'Transfer'); assert.equal(events[0].from, owner, 'address does not match'); assert.equal(events[0].to, to, 'To address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); }); describe('when the owner does not have enough balance', function () { const amount = new BigNumber(1 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(zeroTokenHolder, to, amount, { from: spender })); }); }); }); describe('when the spender does not have enough approved balance', function () { beforeEach(async function () { const approvalAmount = new BigNumber(99 * 1e18); const bigApprovalAmount = new BigNumber(999 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); await tileTokenInstance.approve(spender, bigApprovalAmount, { from: tokenHolder1 }); }); describe('when the owner has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(owner, to, amount, { from: spender })); }); }); describe('when the owner does not have enough balance', function () { const amount = new BigNumber(1001 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(tokenHolder1, to, amount, { from: spender })); }); }); }); }); describe('when the recipient is the zero address', function () { const amount = new BigNumber(100 * 1e18); const to = zeroAddress; beforeEach(async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); }); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(owner, to, amount, { from: spender })); }); }); }); describe('decrease approval', function () { describe('when the spender is not the zero address', function () { const spender = recipient; describe('when the sender has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); describe('when there was no approved amount before', function () { it('keeps the allowance to zero', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1000 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('decreases the spender allowance subtracting the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const approvalAmount = new BigNumber(1000 * 1e18); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(approvalAmount.sub(amount)); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(1000 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); describe('when there was no approved amount before', function () { it('keeps the allowance to zero', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1001 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('decreases the spender allowance subtracting the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(1 * 1e18); }); }); }); }); describe('when the spender is the zero address', function () { const amount = new BigNumber(100 * 1e18); const spender = zeroAddress; it('decreases the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); }); }); describe('increase approval', function () { const amount = new BigNumber(100 * 1e18); describe('when the spender is not the zero address', function () { const spender = recipient; describe('when the sender has enough balance', function () { it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount.add(oldAllowance)); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount.add(oldAllowance)); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('increases the spender allowance adding the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(2 * 1e18); it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(tokenHolder1, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder1 }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, tokenHolder1, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(oldAllowance.add(amount)); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder5 }); const allowance = await tileTokenInstance.allowance(tokenHolder5, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: tokenHolder5 }); }); it('increases the spender allowance adding the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(tokenHolder5, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder5 }); const allowance = await tileTokenInstance.allowance(tokenHolder5, spender); allowance.should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); }); describe('when the spender is the zero address', function () { const spender = zeroAddress; it('approves the requested amount', async function () { await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); });
LOOMIA/loomia
tiletoken/test/contracts/0_TileToken.js
JavaScript
apache-2.0
26,410
import props from './props'; import './view.html'; class NoteClab { beforeRegister() { this.is = 'note-clab'; this.properties = props; } computeClasses(type) { var arr = ['input-note']; if (type != undefined) arr.push(type); return arr.join(' '); } } Polymer(NoteClab);
contactlab/contactlab-ui-components
src/note/index.js
JavaScript
apache-2.0
301
Ext.define('TaxRate', { extend: 'Ext.data.Model', fields: [{name: "id"}, {name: "date",type: 'date',dateFormat: 'Y-m-d'}, {name: "rate"}, {name: "remark"}, {name: "create_time",type: 'date',dateFormat: 'timestamp'}, {name: "update_time",type: 'date',dateFormat: 'timestamp'}, {name: "creater"}, {name: "updater"}] }); var taxRateStore = Ext.create('Ext.data.Store', { model: 'TaxRate', proxy: { type: 'ajax', reader: 'json', url: homePath+'/public/erp/setting_tax/gettaxrate/option/data' } }); var taxRateRowEditing = Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 }); // 税率管理窗口 var taxRateWin = Ext.create('Ext.window.Window', { title: '税率管理', border: 0, height: 300, width: 600, modal: true, constrain: true, closeAction: 'hide', layout: 'fit', tools: [{ type: 'refresh', tooltip: 'Refresh', scope: this, handler: function(){taxRateStore.reload();} }], items: [{ xtype: 'gridpanel', id: 'taxRateGrid', columnLines: true, store: taxRateStore, selType: 'checkboxmodel', tbar: [{ xtype: 'hiddenfield', id: 'tax_id_to_rate' }, { text: '添加税率', iconCls: 'icon-add', scope: this, handler: function(){ taxRateRowEditing.cancelEdit(); var r = Ext.create('TaxRate', { date: Ext.util.Format.date(new Date(), 'Y-m-d'), rate: 1 }); taxRateStore.insert(0, r); taxRateRowEditing.startEdit(0, 0); } }, { text: '删除税率', iconCls: 'icon-delete', scope: this, handler: function(){ var selection = Ext.getCmp('taxRateGrid').getView().getSelectionModel().getSelection(); if(selection.length > 0){ taxRateStore.remove(selection); }else{ Ext.MessageBox.alert('错误', '没有选择删除对象!'); } } }, { text: '保存修改', iconCls: 'icon-save', scope: this, handler: function(){ var updateRecords = taxRateStore.getUpdatedRecords(); var insertRecords = taxRateStore.getNewRecords(); var deleteRecords = taxRateStore.getRemovedRecords(); // 判断是否有修改数据 if(updateRecords.length + insertRecords.length + deleteRecords.length > 0){ var changeRows = { updated: [], inserted: [], deleted: [] } for(var i = 0; i < updateRecords.length; i++){ var data = updateRecords[i].data; changeRows.updated.push(data) } for(var i = 0; i < insertRecords.length; i++){ var data = insertRecords[i].data; changeRows.inserted.push(data) } for(var i = 0; i < deleteRecords.length; i++){ changeRows.deleted.push(deleteRecords[i].data) } Ext.MessageBox.confirm('确认', '确定保存修改内容?', function(button, text){ if(button == 'yes'){ var json = Ext.JSON.encode(changeRows); var selection = Ext.getCmp('taxGrid').getView().getSelectionModel().getSelection(); Ext.Msg.wait('提交中,请稍后...', '提示'); Ext.Ajax.request({ url: homePath+'/public/erp/setting_tax/edittaxrate', params: {json: json, tax_id: Ext.getCmp('tax_id_to_rate').value}, method: 'POST', success: function(response, options) { var data = Ext.JSON.decode(response.responseText); if(data.success){ Ext.MessageBox.alert('提示', data.info); taxRateStore.reload(); taxStore.reload(); }else{ Ext.MessageBox.alert('错误', data.info); } }, failure: function(response){ Ext.MessageBox.alert('错误', '保存提交失败'); } }); } }); }else{ Ext.MessageBox.alert('提示', '没有修改任何数据!'); } } }, '->', { text: '刷新', iconCls: 'icon-refresh', handler: function(){ taxRateStore.reload(); } }], plugins: taxRateRowEditing, columns: [{ xtype: 'rownumberer' }, { text: 'ID', dataIndex: 'id', hidden: true, flex: 1 }, { text: '生效日期', dataIndex: 'date', renderer: Ext.util.Format.dateRenderer('Y-m-d'), editor: { xtype: 'datefield', editable: false, format: 'Y-m-d' }, flex: 3 }, { text: '税率', dataIndex: 'rate', editor: 'numberfield', flex: 2 }, { text: '备注', dataIndex: 'remark', editor: 'textfield', flex: 5 }, { text: '创建人', hidden: true, dataIndex: 'creater', flex: 2 }, { text: '创建时间', hidden: true, dataIndex: 'create_time', renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'), flex: 3 }, { text: '更新人', hidden: true, dataIndex: 'updater', flex: 2 }, { text: '更新时间', hidden: true, dataIndex: 'update_time', renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s'), flex: 3 }] }] });
eoasoft/evolve
application/modules/erp/views/scripts/setting/js/tax_rate.js
JavaScript
apache-2.0
6,462
/** * Created by dmitry on 21.11.16. */ import React, { Component } from 'react'; import { Container, Content, Spinner } from 'native-base'; // TODO: Рядом лежат спиннеры, поди можно прикрячить export default class Loading extends Component { render() { return ( <Container> <Content contentContainerStyle={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}> <Spinner color="blue"/> </Content> </Container> ); } }
dima11221122/63pokupki-react-native
js/components/loading/index.js
JavaScript
apache-2.0
551
//main javascript (function init() { // If we need to load requirejs before loading butter, make it so if (typeof define === "undefined") { var rscript = document.createElement("script"); rscript.onload = function () { init(); }; rscript.src = "require.js"; document.head.appendChild(rscript); return; } require.config({ baseUrl: 'js/', paths: { // the left side is the module ID, // the right side is the path to // the jQuery file, relative to baseUrl. // Also, the path should NOT include // the '.js' file extension. This example // is using jQuery 1.8.2 located at // js/jquery-1.8.2.js, relative to // the HTML page. jquery: 'lib/jquery-2.1.3.min', namedwebsockets: 'lib/namedwebsockets', qrcode: 'lib/qrcode.min', webcodecam:'lib/WebCodeCam.min', qrcodelib:'lib/qrcodelib', socketio: '/socket.io/socket.io', shake: 'lib/shake' } }); // Start the main app logic. define("mediascape", ["mediascape/Agentcontext/agentcontext", "mediascape/Association/association", "mediascape/Discovery/discovery", "mediascape/DiscoveryAgentContext/discoveryagentcontext", "mediascape/Sharedstate/sharedstate", "mediascape/Mappingservice/mappingservice", "mediascape/Applicationcontext/applicationcontext"], function ($, Modules) { //jQuery, modules and the discovery/modules module are all. //loaded and can be used here now. //creation of mediascape and discovery objects. var mediascape = {}; var moduleList = Array.prototype.slice.apply(arguments); mediascape.init = function (options) { mediascapeOptions = {}; _this = Object.create(mediascape); for (var i = 0; i < moduleList.length; i++) { var name = moduleList[i].__moduleName; var dontCall = ['sharedState', 'mappingService', 'applicationContext']; if (dontCall.indexOf(name) === -1) { mediascape[name] = new moduleList[i](mediascape, "gq" + i, mediascape); } else { mediascape[name] = moduleList[i]; } } return _this; }; mediascape.version = "0.0.1"; // See if we have any waiting init calls that happened before we loaded require. if (window.mediascape) { var args = window.mediascape.__waiting; delete window.mediascape; if (args) { mediascape.init.apply(this, args); } } window.mediascape = mediascape; //return of mediascape object with discovery and features objects and its functions return mediascape; }); require(["mediascape"], function (mediascape) { mediascape.init(); /** * * Polyfill for custonevents */ (function () { function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }; CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })(); var event = new CustomEvent("mediascape-ready", { "detail": { "loaded": true } }); document.dispatchEvent(event); }); }());
martinangel/association
helloworld/Triggers/js/mediascape/mediascape.js
JavaScript
apache-2.0
3,983
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ define(function(require) { /* DEPENDENCIES */ // require('foundation.tab'); var BaseFormPanel = require('utils/form-panels/form-panel'); var Sunstone = require('sunstone'); var Locale = require('utils/locale'); //var Tips = require('utils/tips'); var TemplateUtils = require('utils/template-utils'); var WizardFields = require('utils/wizard-fields'); var RoleTab = require('tabs/vmgroup-tab/utils/role-tab'); var AffinityRoleTab = require('tabs/vmgroup-tab/utils/affinity-role-tab'); var Notifier = require('utils/notifier'); var Utils = require('../utils/common'); /* TEMPLATES */ var TemplateWizardHTML = require('hbs!./create/wizard'); var TemplateAdvancedHTML = require('hbs!./create/advanced'); /* CONSTANTS */ var FORM_PANEL_ID = require('./create/formPanelId'); var TAB_ID = require('../tabId'); /* CONSTRUCTOR */ function FormPanel() { this.formPanelId = FORM_PANEL_ID; this.tabId = TAB_ID; this.affinity_role_tab = new AffinityRoleTab([]); this.actions = { 'create': { 'title': Locale.tr("Create Virtual Machine Group"), 'buttonText': Locale.tr("Create"), 'resetButton': true }, 'update': { 'title': Locale.tr("Update Virtual Machine Group"), 'buttonText': Locale.tr("Update"), 'resetButton': false } }; BaseFormPanel.call(this); } FormPanel.FORM_PANEL_ID = FORM_PANEL_ID; FormPanel.prototype = Object.create(BaseFormPanel.prototype); FormPanel.prototype.constructor = FormPanel; FormPanel.prototype.htmlWizard = _htmlWizard; FormPanel.prototype.htmlAdvanced = _htmlAdvanced; FormPanel.prototype.submitWizard = _submitWizard; FormPanel.prototype.submitAdvanced = _submitAdvanced; FormPanel.prototype.onShow = _onShow; FormPanel.prototype.fill = _fill; FormPanel.prototype.setup = _setup; FormPanel.prototype.addRoleTab = _add_role_tab; return FormPanel; /* FUNCTION DEFINITIONS */ function _htmlWizard() { var opts = { info: false, select: true }; return TemplateWizardHTML({ 'affinity-role-tab': this.affinity_role_tab.html(), 'formPanelId': this.formPanelId }); } function _htmlAdvanced() { return TemplateAdvancedHTML({formPanelId: this.formPanelId}); } function _setup(context) { this.roleTabObjects = {}; var that = this; var roles_index = 0; this.affinity_role_tab.setup(context); // Fill parents table // Each time a tab is clicked the table is filled with existing tabs (roles) // Selected roles are kept // TODO If the name of a role is changed and is selected, selection will be lost $("#roles_tabs", context).on("click", "a", function() { var tab_id = "#"+this.id+"Tab"; var str = ""; $(tab_id+" .parent_roles").hide(); var parent_role_available = false; $("#roles_tabs_content #role_name", context).each(function(){ if ($(this).val() != "" && ($(this).val() != $(tab_id+" #role_name", context).val())) { parent_role_available = true; str += "<tr>\ <td style='width:10%'>\ <input class='check_item' type='checkbox' value='"+$(this).val()+"' id='"+$(this).val()+"'/>\ </td>\ <td>"+$(this).val()+"</td>\ </tr>"; } }); if (parent_role_available) { $(tab_id+" .parent_roles", context).show(); } var selected_parents = []; $(tab_id+" .parent_roles_body input:checked", context).each(function(){ selected_parents.push($(this).val()); }); $(tab_id+" .parent_roles_body", context).html(str); $.each(selected_parents, function(){ $(tab_id+" .parent_roles_body #"+this, context).attr('checked', true); }); }); $("#tf_btn_roles", context).bind("click", function(){ that.addRoleTab(roles_index, context); roles_index++; return false; }); /*$("#btn_refresh_roles", context).bind("click", function(){ $("#btn_refresh_roles", context).html("<i class='fa fa-angle-double-down'></i> "+Locale.tr("Refresh roles")); that.affinity_role_tab.refresh(context, that.roleTabObjects); });*/ //---------btn_group_vm_roles Foundation.reflow(context, 'tabs'); // Add first role $("#tf_btn_roles", context).trigger("click"); //Tips.setup(); return false; } function _submitWizard(context) { that = this; var name = WizardFields.retrieveInput($('#vm_group_name', context)); var description = WizardFields.retrieveInput($('#vm_group_description', context)); var role = []; $('.role_content', context).each(function() { var role_id = $(this).attr("role_id"); role.push(that.roleTabObjects[role_id].retrieve($(this))); }); //call to role-tab.js for retrieve data var roles_affinity = this.affinity_role_tab.retrieve(context); var vm_group_json = { "NAME" : name, "DESCRIPTION": description, "ROLE" : role, }; vm_group_json = $.extend(vm_group_json, roles_affinity); if (this.action == "create") { vm_group_json = { "vm_group" : vm_group_json }; Sunstone.runAction("VMGroup.create",JSON.parse(JSON.stringify(vm_group_json))); return false; } else if (this.action == "update") { delete vm_group_json["NAME"]; Sunstone.runAction( "VMGroup.update", this.resourceId, TemplateUtils.templateToString(vm_group_json)); return false; } } function _submitAdvanced(context) { if (this.action == "create") { var template = $('textarea#template', context).val(); var vm_group_json = {vm_group: {vm_group_raw: template}}; Sunstone.runAction("VMGroup.create",vm_group_json); return false; } else if (this.action == "update") { var template_raw = $('textarea#template', context).val(); Sunstone.runAction("VMGroup.update_template", this.resourceId, template_raw); return false; } } function _onShow(context) { var that = this; $('.role_content', context).each(function() { var role_id = $(this).attr("role_id"); that.roleTabObjects[role_id].onShow(); }); } function _fill(context, element) { $("#new_role", context)[0].parentElement.remove(); var that = this; this.setHeader(element); this.resourceId = element.ID; $('#template', context).val(TemplateUtils.templateToString(element.TEMPLATE)); WizardFields.fillInput($('#vm_group_name',context), element.NAME); $('#vm_group_name',context).prop("disabled", true); WizardFields.fillInput($('#vm_group_description', context), element.TEMPLATE.DESCRIPTION ); //Remove row of roles----------------------------------------------------------------- $.each(element.ROLES.ROLE, function(index, value){ var name = value.NAME; if(name){ var html = "<option id='" + name + "' class='roles' value=" + name + "> " + name + "</option>"; $("#list_roles_select").append(html); $("select #" + name).mousedown(function(e) { e.preventDefault(); $(this).prop('selected', !$(this).prop('selected')); return false; }); } }); this.affinity_role_tab.fill(context, element); $("#btn_refresh_roles", context).remove(); $("#affinity",context).show(); //Remove row of roles------------------------------------------------------------------ /*var role_context_first = $('.role_content', context).first(); var role_id_first = $(role_context_first).attr("role_id"); delete that.roleTabObjects[role_id_first]; // Populates the Avanced mode Tab var roles_names = []; var data = []; if(Array.isArray(element.ROLES.ROLE)) data = element.ROLES.ROLE; else data.push(element.ROLES.ROLE); $.each(data, function(index, value){ roles_names.push(value.NAME); $("#tf_btn_roles", context).click(); var role_context = $('.role_content', context).last(); var role_id = $(role_context).attr("role_id"); that.roleTabObjects[role_id].fill(role_context, value,element); }); $.each(data, function(index, value){ var role_context = $('.role_content', context)[index]; var str = ""; $.each(roles_names, function(){ if (this != value.NAME) { str += "<tr>\ <td style='width:10%'>\ <input class='check_item' type='checkbox' value='"+this+"' id='"+this+"'/>\ </td>\ <td>"+this+"</td>\ </tr>"; } }); $(".parent_roles_body", role_context).html(str); if (value.parents) { $.each(value.parents, function(index, value){ $(".parent_roles_body #"+this, role_context).attr('checked', true); }); } });*/ //Remove first tab role, is empty. //$('i.remove-tab', context).first().click(); //$("#tf_btn_roles", context).click(); } function _add_role_tab(role_id, dialog) { var that = this; var html_role_id = 'role' + role_id; var role_tab = new RoleTab(html_role_id); that.roleTabObjects[role_id] = role_tab; // Append the new div containing the tab and add the tab to the list var role_section = $('<div id="'+html_role_id+'Tab" class="tabs-panel role_content wizard_internal_tab" role_id="'+role_id+'">'+ role_tab.html() + '</div>').appendTo($("#roles_tabs_content", dialog)); _redo_service_vmgroup_selector_role(dialog, role_section); role_section.on("change", "#role_name", function(){ var val = true; var chars = ['/','*','&','|',':', String.fromCharCode(92),'"', ';', '/',String.fromCharCode(39),'#','{','}','$','<','>','*']; var newName = $(this).val(); $.each(chars, function(index, value){ if(newName.indexOf(value) != -1 && val){ val = false; } }); if(val){ that.affinity_role_tab.refresh($(this).val(), role_tab.oldName()); role_tab.changeNameTab(newName); } else { Notifier.notifyError(Locale.tr("The new role name contains invalid characters.")); } }); //Tips.setup(role_section); var a = $("<li class='tabs-title'>\ <a class='text-center' id='"+html_role_id+"' href='#"+html_role_id+"Tab'>\ <span>\ <i class='off-color fa fa-cube fa-3x'/>\ <br>\ <span id='role_name_text'>"+Locale.tr("Role ")+role_id+"</span>\ </span>\ <i class='fa fa-times-circle remove-tab'></i>\ </a>\ </li>").appendTo($("ul#roles_tabs", dialog)); Foundation.reInit($("ul#roles_tabs", dialog)); $("a", a).trigger("click"); // close icon: removing the tab on click a.on("click", "i.remove-tab", function() { var target = $(this).parent().attr("href"); var li = $(this).closest('li'); var ul = $(this).closest('ul'); var content = $(target); var role_id = content.attr("role_id"); li.remove(); content.remove(); if (li.hasClass('is-active')) { $('a', ul.children('li').last()).click(); } that.affinity_role_tab.removeRole(role_tab.oldName()); delete that.roleTabObjects[role_id]; return false; }); role_tab.setup(role_section); role_tab.onShow(); } function _redo_service_vmgroup_selector_role(dialog, role_section){ $('#roles_tabs_content .role_content', dialog).each(function(){ var role_section = this; var role_tab_id = $(role_section).attr('id'); }); } });
goberle/one
src/sunstone/public/app/tabs/vmgroup-tab/form-panels/create.js
JavaScript
apache-2.0
12,941
function Controller() { function __alloyId24() { __alloyId24.opts || {}; var models = __alloyId23.models; var len = models.length; var rows = []; for (var i = 0; len > i; i++) { var __alloyId9 = models[i]; __alloyId9.__transform = {}; var __alloyId10 = Ti.UI.createTableViewRow({ layout: "vertical", font: { fontSize: "16dp" }, height: "auto", title: "undefined" != typeof __alloyId9.__transform["nome"] ? __alloyId9.__transform["nome"] : __alloyId9.get("nome"), model: "undefined" != typeof __alloyId9.__transform["alloy_id"] ? __alloyId9.__transform["alloy_id"] : __alloyId9.get("alloy_id"), editable: "true" }); rows.push(__alloyId10); var __alloyId12 = Ti.UI.createView({ layout: "vertical" }); __alloyId10.add(__alloyId12); var __alloyId14 = Ti.UI.createLabel({ width: Ti.UI.SIZE, height: Ti.UI.SIZE, right: "10dp", color: "blue", font: { fontSize: "16dp" }, text: "undefined" != typeof __alloyId9.__transform["nome"] ? __alloyId9.__transform["nome"] : __alloyId9.get("nome") }); __alloyId12.add(__alloyId14); var __alloyId16 = Ti.UI.createView({ height: Ti.UI.SIZE, width: Ti.UI.FILL }); __alloyId12.add(__alloyId16); var __alloyId18 = Ti.UI.createScrollView({ scrollType: "horizontal", layout: "horizontal", horizontalWrap: "false" }); __alloyId16.add(__alloyId18); var __alloyId20 = Ti.UI.createImageView({ top: "15dp", image: "undefined" != typeof __alloyId9.__transform["foto1"] ? __alloyId9.__transform["foto1"] : __alloyId9.get("foto1"), height: "180dp", width: "320dp" }); __alloyId18.add(__alloyId20); var __alloyId22 = Ti.UI.createImageView({ top: "15dp", image: "undefined" != typeof __alloyId9.__transform["foto2"] ? __alloyId9.__transform["foto2"] : __alloyId9.get("foto2"), height: "180dp", width: "320dp" }); __alloyId18.add(__alloyId22); } $.__views.tableviewContatos.setData(rows); } function openAdd1() { var add1 = Alloy.createController("add1"); add1.getView().open({ modal: true }); } function maisDetalhes(e) { var contato = Alloy.Collections.contato.get(e.rowData.model); var ctrl = Alloy.createController("detalhesContato", contato); $.homeTab.open(ctrl.getView()); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "home"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; var __defers = {}; $.__views.homeWindow = Ti.UI.createWindow({ backgroundColor: "white", layout: "vertical", id: "homeWindow", titleid: "home" }); $.__views.contatosSearch = Ti.UI.createSearchBar({ hinttextid: "procurarText", height: "50dp", id: "contatosSearch", showCancel: "false" }); $.__views.homeWindow.add($.__views.contatosSearch); $.__views.Btadd = Ti.UI.createButton({ top: "10dp", width: "200dp", height: "auto", borderRadius: "10dp", font: { fontSize: "17dp" }, title: L("adicionar"), id: "Btadd" }); $.__views.homeWindow.add($.__views.Btadd); openAdd1 ? $.__views.Btadd.addEventListener("click", openAdd1) : __defers["$.__views.Btadd!click!openAdd1"] = true; $.__views.tableviewContatos = Ti.UI.createTableView({ id: "tableviewContatos" }); $.__views.homeWindow.add($.__views.tableviewContatos); var __alloyId23 = Alloy.Collections["contato"] || contato; __alloyId23.on("fetch destroy change add remove reset", __alloyId24); maisDetalhes ? $.__views.tableviewContatos.addEventListener("click", maisDetalhes) : __defers["$.__views.tableviewContatos!click!maisDetalhes"] = true; $.__views.homeTab = Ti.UI.createTab({ backgroundSelectedColor: "#C8C8C8 ", backgroundFocusedColor: "#999", icon: "/images/ic_home.png", window: $.__views.homeWindow, id: "homeTab", titleid: "home" }); $.__views.homeTab && $.addTopLevelView($.__views.homeTab); exports.destroy = function() { __alloyId23.off("fetch destroy change add remove reset", __alloyId24); }; _.extend($, $.__views); Alloy.Collections.contato.fetch(); var contatos = Alloy.Collections.contato; contatos.fetch(); $.tableviewContatos.search = $.contatosSearch; __defers["$.__views.Btadd!click!openAdd1"] && $.__views.Btadd.addEventListener("click", openAdd1); __defers["$.__views.tableviewContatos!click!maisDetalhes"] && $.__views.tableviewContatos.addEventListener("click", maisDetalhes); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
Geeosp/SnapContacts
Resources/alloy/controllers/home.js
JavaScript
apache-2.0
5,638
/** * @license Copyright 2017 Google Inc. 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'; /** * Expected Lighthouse audit values for redirects tests */ const cacheBuster = Number(new Date()); module.exports = [ { initialUrl: `http://localhost:10200/online-only.html?delay=500&redirect=%2Foffline-only.html%3Fcb=${cacheBuster}%26delay=500%26redirect%3D%2Fredirects-final.html`, url: 'http://localhost:10200/redirects-final.html', audits: { 'redirects': { score: '<100', rawValue: '>=500', details: { items: { length: 3, }, }, }, }, }, { initialUrl: `http://localhost:10200/online-only.html?delay=300&redirect=%2Fredirects-final.html`, url: 'http://localhost:10200/redirects-final.html', audits: { 'redirects': { score: 100, rawValue: '>=250', details: { items: { length: 2, }, }, }, }, }, ];
tkadlec/lighthouse
lighthouse-cli/test/smokehouse/redirects/expectations.js
JavaScript
apache-2.0
1,503
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-example60/index.html"); }); it('should check ng-bind', function() { var nameInput = element(by.model('name')); expect(element(by.binding('name')).getText()).toBe('Whirled'); nameInput.clear(); nameInput.sendKeys('world'); expect(element(by.binding('name')).getText()).toBe('world'); }); });
LADOSSIFPB/nutrif
nutrif-web/lib/angular/docs/ptore2e/example-example60/default_test.js
JavaScript
apache-2.0
461
import React from 'react'; import { action } from '@storybook/addon-actions'; import Checkbox from '.'; const onChange = action('onChange'); const defaultProps = { id: 'id1', onChange, }; const intermediate = { id: 'id2', onChange, intermediate: true, }; const checked = { id: 'id3', onChange, checked: true, }; const disabled = { id: 'id4', onChange, disabled: true, }; const withLabel = { id: 'id5', onChange, label: 'Some label', }; export default { title: 'Form/Controls/Checkbox', }; export const Default = () => ( <div style={{ padding: 30 }}> <h1>Checkbox</h1> <h2>Definition</h2> <p>The Checkbox component is basically a fancy checkbox like you have in your iphone</p> <h2>Examples</h2> <form> <h3>Default Checkbox</h3> <Checkbox {...defaultProps} /> <h3> Checkbox with <code>intermediate: true</code> </h3> <Checkbox {...intermediate} /> <h3> Checkbox with <code>checked: true</code> </h3> <Checkbox {...checked} /> <h3> Checkbox with <code>disabled: true</code> </h3> <Checkbox {...disabled} /> <h3> Checkbox with <code>label: Some label</code> </h3> <Checkbox {...withLabel} /> </form> </div> );
Talend/ui
packages/components/src/Checkbox/Checkbox.stories.js
JavaScript
apache-2.0
1,203
var editMode = portal.request.mode == 'edit'; var content = portal.content; var component = portal.component; var layoutRegions = portal.layoutRegions; var body = system.thymeleaf.render('view/layout-70-30.html', { title: content.displayName, path: content.path, name: content.name, editable: editMode, resourcesPath: portal.url.createResourceUrl(''), component: component, leftRegion: layoutRegions.getRegion("left"), rightRegion: layoutRegions.getRegion("right") }); portal.response.body = body; portal.response.contentType = 'text/html'; portal.response.status = 200;
RF0/wem-sample-package
modules/xeon-1.0.0/component/layout-70-30/get.js
JavaScript
apache-2.0
607
/** * Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ Ext.define("seava.ad.ui.extjs.frame.DateFormatMask_Ui", { extend: "e4e.ui.AbstractUi", alias: "widget.DateFormatMask_Ui", /** * Data-controls definition */ _defineDcs_: function() { this._getBuilder_().addDc("mask", Ext.create(seava.ad.ui.extjs.dc.DateFormatMask_Dc,{multiEdit: true})) ; }, /** * Components definition */ _defineElements_: function() { this._getBuilder_() .addDcFilterFormView("mask", {name:"maskFilter", xtype:"ad_DateFormatMask_Dc$Filter"}) .addDcEditGridView("mask", {name:"maskEditList", xtype:"ad_DateFormatMask_Dc$EditList", frame:true}) .addPanel({name:"main", layout:"border", defaults:{split:true}}); }, /** * Combine the components */ _linkElements_: function() { this._getBuilder_() .addChildrenTo("main", ["maskFilter", "maskEditList"], ["north", "center"]) .addToolbarTo("main", "tlbMaskList"); }, /** * Create toolbars */ _defineToolbars_: function() { this._getBuilder_() .beginToolbar("tlbMaskList", {dc: "mask"}) .addTitle().addSeparator().addSeparator() .addQuery().addSave().addCancel() .addReports() .end(); } });
seava/seava.mod.ad
seava.mod.ad.ui.extjs/src/main/resources/webapp/seava/ad/ui/extjs/frame/DateFormatMask_Ui.js
JavaScript
apache-2.0
1,296
// modules are defined as an array // [ module function, map of requireuires ] // // map of requireuires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the requireuire for previous bundles (function outer (modules, cache, entry) { // Save the require from previous bundle to this closure if any var previousRequire = typeof require == "function" && require; function findProxyquireifyName() { var deps = Object.keys(modules) .map(function (k) { return modules[k][1]; }); for (var i = 0; i < deps.length; i++) { var pq = deps[i]['proxyquireify']; if (pq) return pq; } } var proxyquireifyName = findProxyquireifyName(); function newRequire(name, jumped){ // Find the proxyquireify module, if present var pqify = (proxyquireifyName != null) && cache[proxyquireifyName]; // Proxyquireify provides a separate cache that is used when inside // a proxyquire call, and is set to null outside a proxyquire call. // This allows the regular caching semantics to work correctly both // inside and outside proxyquire calls while keeping the cached // modules isolated. // When switching from one proxyquire call to another, it clears // the cache to prevent contamination between different sets // of stubs. var currentCache = (pqify && pqify.exports._cache) || cache; if(!currentCache[name]) { if(!modules[name]) { // if we cannot find the the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. var currentRequire = typeof require == "function" && require; if (!jumped && currentRequire) return currentRequire(name, true); // If there are other bundles on this page the require from the // previous one is saved to 'previousRequire'. Repeat this as // many times as there are bundles until the module is found or // we exhaust the require chain. if (previousRequire) return previousRequire(name, true); var err = new Error('Cannot find module \'' + name + '\''); err.code = 'MODULE_NOT_FOUND'; throw err; } var m = currentCache[name] = {exports:{}}; // The normal browserify require function var req = function(x){ var id = modules[name][1][x]; return newRequire(id ? id : x); }; // The require function substituted for proxyquireify var moduleRequire = function(x){ var pqify = (proxyquireifyName != null) && cache[proxyquireifyName]; // Only try to use the proxyquireify version if it has been `require`d if (pqify && pqify.exports._proxy) { return pqify.exports._proxy(req, x); } else { return req(x); } }; modules[name][0].call(m.exports,moduleRequire,m,m.exports,outer,modules,currentCache,entry); } return currentCache[name].exports; } for(var i=0;i<entry.length;i++) newRequire(entry[i]); // Override the current require with this new one return newRequire; }) ({1:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Float32Array === 'function' ) ? Float32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],2:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of single-precision floating-point numbers in the platform byte order. * * @module @stdlib/array/float32 * * @example * var ctor = require( '@stdlib/array/float32' ); * * var arr = new ctor( 10 ); * // returns <Float32Array> */ // MODULES // var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' ); var builtin = require( './float32array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasFloat32ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./float32array.js":1,"./polyfill.js":3,"@stdlib/assert/has-float32array-support":29}],3:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of single-precision floating-point numbers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],4:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Float64Array === 'function' ) ? Float64Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],5:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order. * * @module @stdlib/array/float64 * * @example * var ctor = require( '@stdlib/array/float64' ); * * var arr = new ctor( 10 ); * // returns <Float64Array> */ // MODULES // var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); var builtin = require( './float64array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasFloat64ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./float64array.js":4,"./polyfill.js":6,"@stdlib/assert/has-float64array-support":32}],6:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of double-precision floating-point numbers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],7:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of twos-complement 16-bit signed integers in the platform byte order. * * @module @stdlib/array/int16 * * @example * var ctor = require( '@stdlib/array/int16' ); * * var arr = new ctor( 10 ); * // returns <Int16Array> */ // MODULES // var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' ); var builtin = require( './int16array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasInt16ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./int16array.js":8,"./polyfill.js":9,"@stdlib/assert/has-int16array-support":34}],8:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Int16Array === 'function' ) ? Int16Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],9:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of twos-complement 16-bit signed integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],10:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order. * * @module @stdlib/array/int32 * * @example * var ctor = require( '@stdlib/array/int32' ); * * var arr = new ctor( 10 ); * // returns <Int32Array> */ // MODULES // var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' ); var builtin = require( './int32array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasInt32ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./int32array.js":11,"./polyfill.js":12,"@stdlib/assert/has-int32array-support":37}],11:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Int32Array === 'function' ) ? Int32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],12:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of twos-complement 32-bit signed integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],13:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of twos-complement 8-bit signed integers in the platform byte order. * * @module @stdlib/array/int8 * * @example * var ctor = require( '@stdlib/array/int8' ); * * var arr = new ctor( 10 ); * // returns <Int8Array> */ // MODULES // var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' ); var builtin = require( './int8array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasInt8ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./int8array.js":14,"./polyfill.js":15,"@stdlib/assert/has-int8array-support":40}],14:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Int8Array === 'function' ) ? Int8Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],15:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of twos-complement 8-bit signed integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],16:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of 16-bit unsigned integers in the platform byte order. * * @module @stdlib/array/uint16 * * @example * var ctor = require( '@stdlib/array/uint16' ); * * var arr = new ctor( 10 ); * // returns <Uint16Array> */ // MODULES // var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' ); var builtin = require( './uint16array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint16ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":17,"./uint16array.js":18,"@stdlib/assert/has-uint16array-support":52}],17:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 16-bit unsigned integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],18:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],19:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of 32-bit unsigned integers in the platform byte order. * * @module @stdlib/array/uint32 * * @example * var ctor = require( '@stdlib/array/uint32' ); * * var arr = new ctor( 10 ); * // returns <Uint32Array> */ // MODULES // var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' ); var builtin = require( './uint32array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint32ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":20,"./uint32array.js":21,"@stdlib/assert/has-uint32array-support":55}],20:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 32-bit unsigned integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],21:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],22:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order. * * @module @stdlib/array/uint8 * * @example * var ctor = require( '@stdlib/array/uint8' ); * * var arr = new ctor( 10 ); * // returns <Uint8Array> */ // MODULES // var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' ); var builtin = require( './uint8array.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint8ArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":23,"./uint8array.js":24,"@stdlib/assert/has-uint8array-support":58}],23:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 8-bit unsigned integers in the platform byte order. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],24:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],25:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Typed array constructor which returns a typed array representing an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. * * @module @stdlib/array/uint8c * * @example * var ctor = require( '@stdlib/array/uint8c' ); * * var arr = new ctor( 10 ); * // returns <Uint8ClampedArray> */ // MODULES // var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); // eslint-disable-line id-length var builtin = require( './uint8clampedarray.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasUint8ClampedArraySupport() ) { ctor = builtin; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./polyfill.js":26,"./uint8clampedarray.js":27,"@stdlib/assert/has-uint8clampedarray-support":61}],26:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write polyfill // MAIN // /** * Typed array which represents an array of 8-bit unsigned integers in the platform byte order clamped to 0-255. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],27:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],28:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],29:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Float32Array` support. * * @module @stdlib/assert/has-float32array-support * * @example * var hasFloat32ArraySupport = require( '@stdlib/assert/has-float32array-support' ); * * var bool = hasFloat32ArraySupport(); * // returns <boolean> */ // MODULES // var hasFloat32ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasFloat32ArraySupport; },{"./main.js":30}],30:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isFloat32Array = require( '@stdlib/assert/is-float32array' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var GlobalFloat32Array = require( './float32array.js' ); // MAIN // /** * Tests for native `Float32Array` support. * * @returns {boolean} boolean indicating if an environment has `Float32Array` support * * @example * var bool = hasFloat32ArraySupport(); * // returns <boolean> */ function hasFloat32ArraySupport() { var bool; var arr; if ( typeof GlobalFloat32Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalFloat32Array( [ 1.0, 3.14, -3.14, 5.0e40 ] ); bool = ( isFloat32Array( arr ) && arr[ 0 ] === 1.0 && arr[ 1 ] === 3.140000104904175 && arr[ 2 ] === -3.140000104904175 && arr[ 3 ] === PINF ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasFloat32ArraySupport; },{"./float32array.js":28,"@stdlib/assert/is-float32array":89,"@stdlib/constants/float64/pinf":225}],31:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Float64Array === 'function' ) ? Float64Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],32:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Float64Array` support. * * @module @stdlib/assert/has-float64array-support * * @example * var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); * * var bool = hasFloat64ArraySupport(); * // returns <boolean> */ // MODULES // var hasFloat64ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasFloat64ArraySupport; },{"./main.js":33}],33:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isFloat64Array = require( '@stdlib/assert/is-float64array' ); var GlobalFloat64Array = require( './float64array.js' ); // MAIN // /** * Tests for native `Float64Array` support. * * @returns {boolean} boolean indicating if an environment has `Float64Array` support * * @example * var bool = hasFloat64ArraySupport(); * // returns <boolean> */ function hasFloat64ArraySupport() { var bool; var arr; if ( typeof GlobalFloat64Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalFloat64Array( [ 1.0, 3.14, -3.14, NaN ] ); bool = ( isFloat64Array( arr ) && arr[ 0 ] === 1.0 && arr[ 1 ] === 3.14 && arr[ 2 ] === -3.14 && arr[ 3 ] !== arr[ 3 ] ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasFloat64ArraySupport; },{"./float64array.js":31,"@stdlib/assert/is-float64array":91}],34:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Int16Array` support. * * @module @stdlib/assert/has-int16array-support * * @example * var hasInt16ArraySupport = require( '@stdlib/assert/has-int16array-support' ); * * var bool = hasInt16ArraySupport(); * // returns <boolean> */ // MODULES // var hasInt16ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasInt16ArraySupport; },{"./main.js":36}],35:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],36:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInt16Array = require( '@stdlib/assert/is-int16array' ); var INT16_MAX = require( '@stdlib/constants/int16/max' ); var INT16_MIN = require( '@stdlib/constants/int16/min' ); var GlobalInt16Array = require( './int16array.js' ); // MAIN // /** * Tests for native `Int16Array` support. * * @returns {boolean} boolean indicating if an environment has `Int16Array` support * * @example * var bool = hasInt16ArraySupport(); * // returns <boolean> */ function hasInt16ArraySupport() { var bool; var arr; if ( typeof GlobalInt16Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalInt16Array( [ 1, 3.14, -3.14, INT16_MAX+1 ] ); bool = ( isInt16Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === -3 && // truncation arr[ 3 ] === INT16_MIN // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasInt16ArraySupport; },{"./int16array.js":35,"@stdlib/assert/is-int16array":95,"@stdlib/constants/int16/max":226,"@stdlib/constants/int16/min":227}],37:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Int32Array` support. * * @module @stdlib/assert/has-int32array-support * * @example * var hasInt32ArraySupport = require( '@stdlib/assert/has-int32array-support' ); * * var bool = hasInt32ArraySupport(); * // returns <boolean> */ // MODULES // var hasInt32ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasInt32ArraySupport; },{"./main.js":39}],38:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],39:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInt32Array = require( '@stdlib/assert/is-int32array' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var INT32_MIN = require( '@stdlib/constants/int32/min' ); var GlobalInt32Array = require( './int32array.js' ); // MAIN // /** * Tests for native `Int32Array` support. * * @returns {boolean} boolean indicating if an environment has `Int32Array` support * * @example * var bool = hasInt32ArraySupport(); * // returns <boolean> */ function hasInt32ArraySupport() { var bool; var arr; if ( typeof GlobalInt32Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalInt32Array( [ 1, 3.14, -3.14, INT32_MAX+1 ] ); bool = ( isInt32Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === -3 && // truncation arr[ 3 ] === INT32_MIN // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasInt32ArraySupport; },{"./int32array.js":38,"@stdlib/assert/is-int32array":97,"@stdlib/constants/int32/max":228,"@stdlib/constants/int32/min":229}],40:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Int8Array` support. * * @module @stdlib/assert/has-int8array-support * * @example * var hasInt8ArraySupport = require( '@stdlib/assert/has-int8array-support' ); * * var bool = hasInt8ArraySupport(); * // returns <boolean> */ // MODULES // var hasInt8ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasInt8ArraySupport; },{"./main.js":42}],41:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],42:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInt8Array = require( '@stdlib/assert/is-int8array' ); var INT8_MAX = require( '@stdlib/constants/int8/max' ); var INT8_MIN = require( '@stdlib/constants/int8/min' ); var GlobalInt8Array = require( './int8array.js' ); // MAIN // /** * Tests for native `Int8Array` support. * * @returns {boolean} boolean indicating if an environment has `Int8Array` support * * @example * var bool = hasInt8ArraySupport(); * // returns <boolean> */ function hasInt8ArraySupport() { var bool; var arr; if ( typeof GlobalInt8Array !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalInt8Array( [ 1, 3.14, -3.14, INT8_MAX+1 ] ); bool = ( isInt8Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === -3 && // truncation arr[ 3 ] === INT8_MIN // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasInt8ArraySupport; },{"./int8array.js":41,"@stdlib/assert/is-int8array":99,"@stdlib/constants/int8/max":230,"@stdlib/constants/int8/min":231}],43:[function(require,module,exports){ (function (Buffer){(function (){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Buffer === 'function' ) ? Buffer : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; }).call(this)}).call(this,require("buffer").Buffer) },{"buffer":379}],44:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Buffer` support. * * @module @stdlib/assert/has-node-buffer-support * * @example * var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' ); * * var bool = hasNodeBufferSupport(); * // returns <boolean> */ // MODULES // var hasNodeBufferSupport = require( './main.js' ); // EXPORTS // module.exports = hasNodeBufferSupport; },{"./main.js":45}],45:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var GlobalBuffer = require( './buffer.js' ); // MAIN // /** * Tests for native `Buffer` support. * * @returns {boolean} boolean indicating if an environment has `Buffer` support * * @example * var bool = hasNodeBufferSupport(); * // returns <boolean> */ function hasNodeBufferSupport() { var bool; var b; if ( typeof GlobalBuffer !== 'function' ) { return false; } // Test basic support... try { if ( typeof GlobalBuffer.from === 'function' ) { b = GlobalBuffer.from( [ 1, 2, 3, 4 ] ); } else { b = new GlobalBuffer( [ 1, 2, 3, 4 ] ); // Note: this is deprecated behavior starting in Node v6 (see https://nodejs.org/api/buffer.html#buffer_new_buffer_array) } bool = ( isBuffer( b ) && b[ 0 ] === 1 && b[ 1 ] === 2 && b[ 2 ] === 3 && b[ 3 ] === 4 ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasNodeBufferSupport; },{"./buffer.js":43,"@stdlib/assert/is-buffer":79}],46:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test whether an object has a specified property. * * @module @stdlib/assert/has-own-property * * @example * var hasOwnProp = require( '@stdlib/assert/has-own-property' ); * * var beep = { * 'boop': true * }; * * var bool = hasOwnProp( beep, 'boop' ); * // returns true * * bool = hasOwnProp( beep, 'bop' ); * // returns false */ // MODULES // var hasOwnProp = require( './main.js' ); // EXPORTS // module.exports = hasOwnProp; },{"./main.js":47}],47:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // FUNCTIONS // var has = Object.prototype.hasOwnProperty; // MAIN // /** * Tests if an object has a specified property. * * @param {*} value - value to test * @param {*} property - property to test * @returns {boolean} boolean indicating if an object has a specified property * * @example * var beep = { * 'boop': true * }; * * var bool = hasOwnProp( beep, 'boop' ); * // returns true * * @example * var beep = { * 'boop': true * }; * * var bool = hasOwnProp( beep, 'bap' ); * // returns false */ function hasOwnProp( value, property ) { if ( value === void 0 || value === null ) { return false; } return has.call( value, property ); } // EXPORTS // module.exports = hasOwnProp; },{}],48:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Symbol` support. * * @module @stdlib/assert/has-symbol-support * * @example * var hasSymbolSupport = require( '@stdlib/assert/has-symbol-support' ); * * var bool = hasSymbolSupport(); * // returns <boolean> */ // MODULES // var hasSymbolSupport = require( './main.js' ); // EXPORTS // module.exports = hasSymbolSupport; },{"./main.js":49}],49:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Tests for native `Symbol` support. * * @returns {boolean} boolean indicating if an environment has `Symbol` support * * @example * var bool = hasSymbolSupport(); * // returns <boolean> */ function hasSymbolSupport() { return ( typeof Symbol === 'function' && typeof Symbol( 'foo' ) === 'symbol' ); } // EXPORTS // module.exports = hasSymbolSupport; },{}],50:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `toStringTag` support. * * @module @stdlib/assert/has-tostringtag-support * * @example * var hasToStringTagSupport = require( '@stdlib/assert/has-tostringtag-support' ); * * var bool = hasToStringTagSupport(); * // returns <boolean> */ // MODULES // var hasToStringTagSupport = require( './main.js' ); // EXPORTS // module.exports = hasToStringTagSupport; },{"./main.js":51}],51:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasSymbols = require( '@stdlib/assert/has-symbol-support' ); // VARIABLES // var FLG = hasSymbols(); // MAIN // /** * Tests for native `toStringTag` support. * * @returns {boolean} boolean indicating if an environment has `toStringTag` support * * @example * var bool = hasToStringTagSupport(); * // returns <boolean> */ function hasToStringTagSupport() { return ( FLG && typeof Symbol.toStringTag === 'symbol' ); } // EXPORTS // module.exports = hasToStringTagSupport; },{"@stdlib/assert/has-symbol-support":48}],52:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Uint16Array` support. * * @module @stdlib/assert/has-uint16array-support * * @example * var hasUint16ArraySupport = require( '@stdlib/assert/has-uint16array-support' ); * * var bool = hasUint16ArraySupport(); * // returns <boolean> */ // MODULES // var hasUint16ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint16ArraySupport; },{"./main.js":53}],53:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isUint16Array = require( '@stdlib/assert/is-uint16array' ); var UINT16_MAX = require( '@stdlib/constants/uint16/max' ); var GlobalUint16Array = require( './uint16array.js' ); // MAIN // /** * Tests for native `Uint16Array` support. * * @returns {boolean} boolean indicating if an environment has `Uint16Array` support * * @example * var bool = hasUint16ArraySupport(); * // returns <boolean> */ function hasUint16ArraySupport() { var bool; var arr; if ( typeof GlobalUint16Array !== 'function' ) { return false; } // Test basic support... try { arr = [ 1, 3.14, -3.14, UINT16_MAX+1, UINT16_MAX+2 ]; arr = new GlobalUint16Array( arr ); bool = ( isUint16Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === UINT16_MAX-2 && // truncation and wrap around arr[ 3 ] === 0 && // wrap around arr[ 4 ] === 1 // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint16ArraySupport; },{"./uint16array.js":54,"@stdlib/assert/is-uint16array":155,"@stdlib/constants/uint16/max":232}],54:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],55:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Uint32Array` support. * * @module @stdlib/assert/has-uint32array-support * * @example * var hasUint32ArraySupport = require( '@stdlib/assert/has-uint32array-support' ); * * var bool = hasUint32ArraySupport(); * // returns <boolean> */ // MODULES // var hasUint32ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint32ArraySupport; },{"./main.js":56}],56:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var GlobalUint32Array = require( './uint32array.js' ); // MAIN // /** * Tests for native `Uint32Array` support. * * @returns {boolean} boolean indicating if an environment has `Uint32Array` support * * @example * var bool = hasUint32ArraySupport(); * // returns <boolean> */ function hasUint32ArraySupport() { var bool; var arr; if ( typeof GlobalUint32Array !== 'function' ) { return false; } // Test basic support... try { arr = [ 1, 3.14, -3.14, UINT32_MAX+1, UINT32_MAX+2 ]; arr = new GlobalUint32Array( arr ); bool = ( isUint32Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === UINT32_MAX-2 && // truncation and wrap around arr[ 3 ] === 0 && // wrap around arr[ 4 ] === 1 // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint32ArraySupport; },{"./uint32array.js":57,"@stdlib/assert/is-uint32array":157,"@stdlib/constants/uint32/max":233}],57:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],58:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Uint8Array` support. * * @module @stdlib/assert/has-uint8array-support * * @example * var hasUint8ArraySupport = require( '@stdlib/assert/has-uint8array-support' ); * * var bool = hasUint8ArraySupport(); * // returns <boolean> */ // MODULES // var hasUint8ArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint8ArraySupport; },{"./main.js":59}],59:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isUint8Array = require( '@stdlib/assert/is-uint8array' ); var UINT8_MAX = require( '@stdlib/constants/uint8/max' ); var GlobalUint8Array = require( './uint8array.js' ); // MAIN // /** * Tests for native `Uint8Array` support. * * @returns {boolean} boolean indicating if an environment has `Uint8Array` support * * @example * var bool = hasUint8ArraySupport(); * // returns <boolean> */ function hasUint8ArraySupport() { var bool; var arr; if ( typeof GlobalUint8Array !== 'function' ) { return false; } // Test basic support... try { arr = [ 1, 3.14, -3.14, UINT8_MAX+1, UINT8_MAX+2 ]; arr = new GlobalUint8Array( arr ); bool = ( isUint8Array( arr ) && arr[ 0 ] === 1 && arr[ 1 ] === 3 && // truncation arr[ 2 ] === UINT8_MAX-2 && // truncation and wrap around arr[ 3 ] === 0 && // wrap around arr[ 4 ] === 1 // wrap around ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint8ArraySupport; },{"./uint8array.js":60,"@stdlib/assert/is-uint8array":159,"@stdlib/constants/uint8/max":234}],60:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],61:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test for native `Uint8ClampedArray` support. * * @module @stdlib/assert/has-uint8clampedarray-support * * @example * var hasUint8ClampedArraySupport = require( '@stdlib/assert/has-uint8clampedarray-support' ); * * var bool = hasUint8ClampedArraySupport(); * // returns <boolean> */ // MODULES // var hasUint8ClampedArraySupport = require( './main.js' ); // EXPORTS // module.exports = hasUint8ClampedArraySupport; },{"./main.js":62}],62:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); var GlobalUint8ClampedArray = require( './uint8clampedarray.js' ); // MAIN // /** * Tests for native `Uint8ClampedArray` support. * * @returns {boolean} boolean indicating if an environment has `Uint8ClampedArray` support * * @example * var bool = hasUint8ClampedArraySupport(); * // returns <boolean> */ function hasUint8ClampedArraySupport() { // eslint-disable-line id-length var bool; var arr; if ( typeof GlobalUint8ClampedArray !== 'function' ) { return false; } // Test basic support... try { arr = new GlobalUint8ClampedArray( [ -1, 0, 1, 3.14, 4.99, 255, 256 ] ); bool = ( isUint8ClampedArray( arr ) && arr[ 0 ] === 0 && // clamped arr[ 1 ] === 0 && arr[ 2 ] === 1 && arr[ 3 ] === 3 && // round to nearest arr[ 4 ] === 5 && // round to nearest arr[ 5 ] === 255 && arr[ 6 ] === 255 // clamped ); } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasUint8ClampedArraySupport; },{"./uint8clampedarray.js":63,"@stdlib/assert/is-uint8clampedarray":161}],63:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],64:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isArguments = require( './main.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Detects whether an environment returns the expected internal class of the `arguments` object. * * @private * @returns {boolean} boolean indicating whether an environment behaves as expected * * @example * var bool = detect(); * // returns <boolean> */ function detect() { return isArguments( arguments ); } // MAIN // bool = detect(); // EXPORTS // module.exports = bool; },{"./main.js":66}],65:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an `arguments` object. * * @module @stdlib/assert/is-arguments * * @example * var isArguments = require( '@stdlib/assert/is-arguments' ); * * function foo() { * return arguments; * } * * var bool = isArguments( foo() ); * // returns true * * bool = isArguments( [] ); * // returns false */ // MODULES // var hasArgumentsClass = require( './detect.js' ); var main = require( './main.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var isArguments; if ( hasArgumentsClass ) { isArguments = main; } else { isArguments = polyfill; } // EXPORTS // module.exports = isArguments; },{"./detect.js":64,"./main.js":66,"./polyfill.js":67}],66:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // MAIN // /** * Tests whether a value is an `arguments` object. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an `arguments` object * * @example * function foo() { * return arguments; * } * * var bool = isArguments( foo() ); * // returns true * * @example * var bool = isArguments( [] ); * // returns false */ function isArguments( value ) { return ( nativeClass( value ) === '[object Arguments]' ); } // EXPORTS // module.exports = isArguments; },{"@stdlib/utils/native-class":346}],67:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); var isArray = require( '@stdlib/assert/is-array' ); var isInteger = require( '@stdlib/math/base/assert/is-integer' ); var MAX_LENGTH = require( '@stdlib/constants/uint32/max' ); // MAIN // /** * Tests whether a value is an `arguments` object. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an `arguments` object * * @example * function foo() { * return arguments; * } * * var bool = isArguments( foo() ); * // returns true * * @example * var bool = isArguments( [] ); * // returns false */ function isArguments( value ) { return ( value !== null && typeof value === 'object' && !isArray( value ) && typeof value.length === 'number' && isInteger( value.length ) && value.length >= 0 && value.length <= MAX_LENGTH && hasOwnProp( value, 'callee' ) && !isEnumerableProperty( value, 'callee' ) ); } // EXPORTS // module.exports = isArguments; },{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-array":70,"@stdlib/assert/is-enumerable-property":84,"@stdlib/constants/uint32/max":233,"@stdlib/math/base/assert/is-integer":237}],68:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is array-like. * * @module @stdlib/assert/is-array-like * * @example * var isArrayLike = require( '@stdlib/assert/is-array-like' ); * * var bool = isArrayLike( [] ); * // returns true * * bool = isArrayLike( { 'length': 10 } ); * // returns true * * bool = isArrayLike( 'beep' ); * // returns true */ // MODULES // var isArrayLike = require( './main.js' ); // EXPORTS // module.exports = isArrayLike; },{"./main.js":69}],69:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInteger = require( '@stdlib/math/base/assert/is-integer' ); var MAX_LENGTH = require( '@stdlib/constants/array/max-array-length' ); // MAIN // /** * Tests if a value is array-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is array-like * * @example * var bool = isArrayLike( [] ); * // returns true * * @example * var bool = isArrayLike( {'length':10} ); * // returns true */ function isArrayLike( value ) { return ( value !== void 0 && value !== null && typeof value !== 'function' && typeof value.length === 'number' && isInteger( value.length ) && value.length >= 0 && value.length <= MAX_LENGTH ); } // EXPORTS // module.exports = isArrayLike; },{"@stdlib/constants/array/max-array-length":219,"@stdlib/math/base/assert/is-integer":237}],70:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an array. * * @module @stdlib/assert/is-array * * @example * var isArray = require( '@stdlib/assert/is-array' ); * * var bool = isArray( [] ); * // returns true * * bool = isArray( {} ); * // returns false */ // MODULES // var isArray = require( './main.js' ); // EXPORTS // module.exports = isArray; },{"./main.js":71}],71:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var f; // FUNCTIONS // /** * Tests if a value is an array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an array * * @example * var bool = isArray( [] ); * // returns true * * @example * var bool = isArray( {} ); * // returns false */ function isArray( value ) { return ( nativeClass( value ) === '[object Array]' ); } // MAIN // if ( Array.isArray ) { f = Array.isArray; } else { f = isArray; } // EXPORTS // module.exports = f; },{"@stdlib/utils/native-class":346}],72:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a boolean. * * @module @stdlib/assert/is-boolean * * @example * var isBoolean = require( '@stdlib/assert/is-boolean' ); * * var bool = isBoolean( false ); * // returns true * * bool = isBoolean( new Boolean( false ) ); * // returns true * * @example * // Use interface to check for boolean primitives... * var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; * * var bool = isBoolean( false ); * // returns true * * bool = isBoolean( new Boolean( true ) ); * // returns false * * @example * // Use interface to check for boolean objects... * var isBoolean = require( '@stdlib/assert/is-boolean' ).isObject; * * var bool = isBoolean( true ); * // returns false * * bool = isBoolean( new Boolean( false ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isBoolean = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isBoolean, 'isPrimitive', isPrimitive ); setReadOnly( isBoolean, 'isObject', isObject ); // EXPORTS // module.exports = isBoolean; },{"./main.js":73,"./object.js":74,"./primitive.js":75,"@stdlib/utils/define-nonenumerable-read-only-property":297}],73:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a boolean. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a boolean * * @example * var bool = isBoolean( false ); * // returns true * * @example * var bool = isBoolean( true ); * // returns true * * @example * var bool = isBoolean( new Boolean( false ) ); * // returns true * * @example * var bool = isBoolean( new Boolean( true ) ); * // returns true */ function isBoolean( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isBoolean; },{"./object.js":74,"./primitive.js":75}],74:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var test = require( './try2serialize.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a boolean object. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a boolean object * * @example * var bool = isBoolean( true ); * // returns false * * @example * var bool = isBoolean( new Boolean( false ) ); * // returns true */ function isBoolean( value ) { if ( typeof value === 'object' ) { if ( value instanceof Boolean ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object Boolean]' ); } return false; } // EXPORTS // module.exports = isBoolean; },{"./try2serialize.js":77,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/utils/native-class":346}],75:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Tests if a value is a boolean primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a boolean primitive * * @example * var bool = isBoolean( true ); * // returns true * * @example * var bool = isBoolean( false ); * // returns true * * @example * var bool = isBoolean( new Boolean( true ) ); * // returns false */ function isBoolean( value ) { return ( typeof value === 'boolean' ); } // EXPORTS // module.exports = isBoolean; },{}],76:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // eslint-disable-next-line stdlib/no-redeclare var toString = Boolean.prototype.toString; // non-generic // EXPORTS // module.exports = toString; },{}],77:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var toString = require( './tostring.js' ); // eslint-disable-line stdlib/no-redeclare // MAIN // /** * Attempts to serialize a value to a string. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if a value can be serialized */ function test( value ) { try { toString.call( value ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = test; },{"./tostring.js":76}],78:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // EXPORTS // module.exports = true; },{}],79:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a Buffer instance. * * @module @stdlib/assert/is-buffer * * @example * var isBuffer = require( '@stdlib/assert/is-buffer' ); * * var v = isBuffer( new Buffer( 'beep' ) ); * // returns true * * v = isBuffer( {} ); * // returns false */ // MODULES // var isBuffer = require( './main.js' ); // EXPORTS // module.exports = isBuffer; },{"./main.js":80}],80:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isObjectLike = require( '@stdlib/assert/is-object-like' ); // MAIN // /** * Tests if a value is a Buffer instance. * * @param {*} value - value to validate * @returns {boolean} boolean indicating if a value is a Buffer instance * * @example * var v = isBuffer( new Buffer( 'beep' ) ); * // returns true * * @example * var v = isBuffer( new Buffer( [1,2,3,4] ) ); * // returns true * * @example * var v = isBuffer( {} ); * // returns false * * @example * var v = isBuffer( [] ); * // returns false */ function isBuffer( value ) { return ( isObjectLike( value ) && ( // eslint-disable-next-line no-underscore-dangle value._isBuffer || // for envs missing Object.prototype.constructor (e.g., Safari 5-7) ( value.constructor && // WARNING: `typeof` is not a foolproof check, as certain envs consider RegExp and NodeList instances to be functions typeof value.constructor.isBuffer === 'function' && value.constructor.isBuffer( value ) ) ) ); } // EXPORTS // module.exports = isBuffer; },{"@stdlib/assert/is-object-like":134}],81:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a collection. * * @module @stdlib/assert/is-collection * * @example * var isCollection = require( '@stdlib/assert/is-collection' ); * * var bool = isCollection( [] ); * // returns true * * bool = isCollection( {} ); * // returns false */ // MODULES // var isCollection = require( './main.js' ); // EXPORTS // module.exports = isCollection; },{"./main.js":82}],82:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInteger = require( '@stdlib/math/base/assert/is-integer' ); var MAX_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' ); // MAIN // /** * Tests if a value is a collection. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is a collection * * @example * var bool = isCollection( [] ); * // returns true * * @example * var bool = isCollection( {} ); * // returns false */ function isCollection( value ) { return ( typeof value === 'object' && value !== null && typeof value.length === 'number' && isInteger( value.length ) && value.length >= 0 && value.length <= MAX_LENGTH ); } // EXPORTS // module.exports = isCollection; },{"@stdlib/constants/array/max-typed-array-length":220,"@stdlib/math/base/assert/is-integer":237}],83:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isEnum = require( './native.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Detects whether an environment has a bug where String indices are not detected as "enumerable" properties. Observed in Node v0.10. * * @private * @returns {boolean} boolean indicating whether an environment has the bug */ function detect() { return !isEnum.call( 'beep', '0' ); } // MAIN // bool = detect(); // EXPORTS // module.exports = bool; },{"./native.js":86}],84:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test whether an object's own property is enumerable. * * @module @stdlib/assert/is-enumerable-property * * @example * var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); * * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'boop' ); * // returns true * * bool = isEnumerableProperty( beep, 'hasOwnProperty' ); * // returns false */ // MODULES // var isEnumerableProperty = require( './main.js' ); // EXPORTS // module.exports = isEnumerableProperty; },{"./main.js":85}],85:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ); var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive; var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; var isEnum = require( './native.js' ); var hasStringEnumBug = require( './has_string_enumerability_bug.js' ); // MAIN // /** * Tests if an object's own property is enumerable. * * @param {*} value - value to test * @param {*} property - property to test * @returns {boolean} boolean indicating if an object property is enumerable * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'boop' ); * // returns true * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'hasOwnProperty' ); * // returns false */ function isEnumerableProperty( value, property ) { var bool; if ( value === void 0 || value === null ) { return false; } bool = isEnum.call( value, property ); if ( !bool && hasStringEnumBug && isString( value ) ) { // Note: we only check for indices, as properties attached to a `String` object are properly detected as enumerable above. property = +property; return ( !isnan( property ) && isInteger( property ) && property >= 0 && property < value.length ); } return bool; } // EXPORTS // module.exports = isEnumerableProperty; },{"./has_string_enumerability_bug.js":83,"./native.js":86,"@stdlib/assert/is-integer":101,"@stdlib/assert/is-nan":109,"@stdlib/assert/is-string":149}],86:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Tests if an object's own property is enumerable. * * @private * @name isEnumerableProperty * @type {Function} * @param {*} value - value to test * @param {*} property - property to test * @returns {boolean} boolean indicating if an object property is enumerable * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'boop' ); * // returns true * * @example * var beep = { * 'boop': true * }; * * var bool = isEnumerableProperty( beep, 'hasOwnProperty' ); * // returns false */ var isEnumerableProperty = Object.prototype.propertyIsEnumerable; // EXPORTS // module.exports = isEnumerableProperty; },{}],87:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an `Error` object. * * @module @stdlib/assert/is-error * * @example * var isError = require( '@stdlib/assert/is-error' ); * * var bool = isError( new Error( 'beep' ) ); * // returns true * * bool = isError( {} ); * // returns false */ // MODULES // var isError = require( './main.js' ); // EXPORTS // module.exports = isError; },{"./main.js":88}],88:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var nativeClass = require( '@stdlib/utils/native-class' ); // MAIN // /** * Tests if a value is an `Error` object. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an `Error` object * * @example * var bool = isError( new Error( 'beep' ) ); * // returns true * * @example * var bool = isError( {} ); * // returns false */ function isError( value ) { if ( typeof value !== 'object' || value === null ) { return false; } // Check for `Error` objects from the same realm (same Node.js `vm` or same `Window` object)... if ( value instanceof Error ) { return true; } // Walk the prototype tree until we find an object having the desired native class... while ( value ) { if ( nativeClass( value ) === '[object Error]' ) { return true; } value = getPrototypeOf( value ); } return false; } // EXPORTS // module.exports = isError; },{"@stdlib/utils/get-prototype-of":312,"@stdlib/utils/native-class":346}],89:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a Float32Array. * * @module @stdlib/assert/is-float32array * * @example * var isFloat32Array = require( '@stdlib/assert/is-float32array' ); * * var bool = isFloat32Array( new Float32Array( 10 ) ); * // returns true * * bool = isFloat32Array( [] ); * // returns false */ // MODULES // var isFloat32Array = require( './main.js' ); // EXPORTS // module.exports = isFloat32Array; },{"./main.js":90}],90:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasFloat32Array = ( typeof Float32Array === 'function' );// eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Float32Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Float32Array * * @example * var bool = isFloat32Array( new Float32Array( 10 ) ); * // returns true * * @example * var bool = isFloat32Array( [] ); * // returns false */ function isFloat32Array( value ) { return ( ( hasFloat32Array && value instanceof Float32Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Float32Array]' ); } // EXPORTS // module.exports = isFloat32Array; },{"@stdlib/utils/native-class":346}],91:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a Float64Array. * * @module @stdlib/assert/is-float64array * * @example * var isFloat64Array = require( '@stdlib/assert/is-float64array' ); * * var bool = isFloat64Array( new Float64Array( 10 ) ); * // returns true * * bool = isFloat64Array( [] ); * // returns false */ // MODULES // var isFloat64Array = require( './main.js' ); // EXPORTS // module.exports = isFloat64Array; },{"./main.js":92}],92:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasFloat64Array = ( typeof Float64Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Float64Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Float64Array * * @example * var bool = isFloat64Array( new Float64Array( 10 ) ); * // returns true * * @example * var bool = isFloat64Array( [] ); * // returns false */ function isFloat64Array( value ) { return ( ( hasFloat64Array && value instanceof Float64Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Float64Array]' ); } // EXPORTS // module.exports = isFloat64Array; },{"@stdlib/utils/native-class":346}],93:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a function. * * @module @stdlib/assert/is-function * * @example * var isFunction = require( '@stdlib/assert/is-function' ); * * function beep() { * return 'beep'; * } * * var bool = isFunction( beep ); * // returns true */ // MODULES // var isFunction = require( './main.js' ); // EXPORTS // module.exports = isFunction; },{"./main.js":94}],94:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var typeOf = require( '@stdlib/utils/type-of' ); // MAIN // /** * Tests if a value is a function. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a function * * @example * function beep() { * return 'beep'; * } * * var bool = isFunction( beep ); * // returns true */ function isFunction( value ) { // Note: cannot use `typeof` directly, as various browser engines incorrectly return `'function'` when operating on non-function objects, such as regular expressions and NodeLists. return ( typeOf( value ) === 'function' ); } // EXPORTS // module.exports = isFunction; },{"@stdlib/utils/type-of":373}],95:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an Int16Array. * * @module @stdlib/assert/is-int16array * * @example * var isInt16Array = require( '@stdlib/assert/is-int16array' ); * * var bool = isInt16Array( new Int16Array( 10 ) ); * // returns true * * bool = isInt16Array( [] ); * // returns false */ // MODULES // var isInt16Array = require( './main.js' ); // EXPORTS // module.exports = isInt16Array; },{"./main.js":96}],96:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasInt16Array = ( typeof Int16Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is an Int16Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an Int16Array * * @example * var bool = isInt16Array( new Int16Array( 10 ) ); * // returns true * * @example * var bool = isInt16Array( [] ); * // returns false */ function isInt16Array( value ) { return ( ( hasInt16Array && value instanceof Int16Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Int16Array]' ); } // EXPORTS // module.exports = isInt16Array; },{"@stdlib/utils/native-class":346}],97:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an Int32Array. * * @module @stdlib/assert/is-int32array * * @example * var isInt32Array = require( '@stdlib/assert/is-int32array' ); * * var bool = isInt32Array( new Int32Array( 10 ) ); * // returns true * * bool = isInt32Array( [] ); * // returns false */ // MODULES // var isInt32Array = require( './main.js' ); // EXPORTS // module.exports = isInt32Array; },{"./main.js":98}],98:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasInt32Array = ( typeof Int32Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is an Int32Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an Int32Array * * @example * var bool = isInt32Array( new Int32Array( 10 ) ); * // returns true * * @example * var bool = isInt32Array( [] ); * // returns false */ function isInt32Array( value ) { return ( ( hasInt32Array && value instanceof Int32Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Int32Array]' ); } // EXPORTS // module.exports = isInt32Array; },{"@stdlib/utils/native-class":346}],99:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an Int8Array. * * @module @stdlib/assert/is-int8array * * @example * var isInt8Array = require( '@stdlib/assert/is-int8array' ); * * var bool = isInt8Array( new Int8Array( 10 ) ); * // returns true * * bool = isInt8Array( [] ); * // returns false */ // MODULES // var isInt8Array = require( './main.js' ); // EXPORTS // module.exports = isInt8Array; },{"./main.js":100}],100:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasInt8Array = ( typeof Int8Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is an Int8Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an Int8Array * * @example * var bool = isInt8Array( new Int8Array( 10 ) ); * // returns true * * @example * var bool = isInt8Array( [] ); * // returns false */ function isInt8Array( value ) { return ( ( hasInt8Array && value instanceof Int8Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Int8Array]' ); } // EXPORTS // module.exports = isInt8Array; },{"@stdlib/utils/native-class":346}],101:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an integer. * * @module @stdlib/assert/is-integer * * @example * var isInteger = require( '@stdlib/assert/is-integer' ); * * var bool = isInteger( 5.0 ); * // returns true * * bool = isInteger( new Number( 5.0 ) ); * // returns true * * bool = isInteger( -3.14 ); * // returns false * * bool = isInteger( null ); * // returns false * * @example * // Use interface to check for integer primitives... * var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; * * var bool = isInteger( -3.0 ); * // returns true * * bool = isInteger( new Number( -3.0 ) ); * // returns false * * @example * // Use interface to check for integer objects... * var isInteger = require( '@stdlib/assert/is-integer' ).isObject; * * var bool = isInteger( 3.0 ); * // returns false * * bool = isInteger( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isInteger = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isInteger, 'isPrimitive', isPrimitive ); setReadOnly( isInteger, 'isObject', isObject ); // EXPORTS // module.exports = isInteger; },{"./main.js":103,"./object.js":104,"./primitive.js":105,"@stdlib/utils/define-nonenumerable-read-only-property":297}],102:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var PINF = require( '@stdlib/constants/float64/pinf' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var isInt = require( '@stdlib/math/base/assert/is-integer' ); // MAIN // /** * Tests if a number primitive is an integer value. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if a number primitive is an integer value */ function isInteger( value ) { return ( value < PINF && value > NINF && isInt( value ) ); } // EXPORTS // module.exports = isInteger; },{"@stdlib/constants/float64/ninf":224,"@stdlib/constants/float64/pinf":225,"@stdlib/math/base/assert/is-integer":237}],103:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is an integer. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an integer * * @example * var bool = isInteger( 5.0 ); * // returns true * * @example * var bool = isInteger( new Number( 5.0 ) ); * // returns true * * @example * var bool = isInteger( -3.14 ); * // returns false * * @example * var bool = isInteger( null ); * // returns false */ function isInteger( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isInteger; },{"./object.js":104,"./primitive.js":105}],104:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isObject; var isInt = require( './integer.js' ); // MAIN // /** * Tests if a value is a number object having an integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having an integer value * * @example * var bool = isInteger( 3.0 ); * // returns false * * @example * var bool = isInteger( new Number( 3.0 ) ); * // returns true */ function isInteger( value ) { return ( isNumber( value ) && isInt( value.valueOf() ) ); } // EXPORTS // module.exports = isInteger; },{"./integer.js":102,"@stdlib/assert/is-number":128}],105:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; var isInt = require( './integer.js' ); // MAIN // /** * Tests if a value is a number primitive having an integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having an integer value * * @example * var bool = isInteger( -3.0 ); * // returns true * * @example * var bool = isInteger( new Number( -3.0 ) ); * // returns false */ function isInteger( value ) { return ( isNumber( value ) && isInt( value ) ); } // EXPORTS // module.exports = isInteger; },{"./integer.js":102,"@stdlib/assert/is-number":128}],106:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var Uint8Array = require( '@stdlib/array/uint8' ); var Uint16Array = require( '@stdlib/array/uint16' ); // MAIN // var ctors = { 'uint16': Uint16Array, 'uint8': Uint8Array }; // EXPORTS // module.exports = ctors; },{"@stdlib/array/uint16":16,"@stdlib/array/uint8":22}],107:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a boolean indicating if an environment is little endian. * * @module @stdlib/assert/is-little-endian * * @example * var IS_LITTLE_ENDIAN = require( '@stdlib/assert/is-little-endian' ); * * var bool = IS_LITTLE_ENDIAN; * // returns <boolean> */ // MODULES // var IS_LITTLE_ENDIAN = require( './main.js' ); // EXPORTS // module.exports = IS_LITTLE_ENDIAN; },{"./main.js":108}],108:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var ctors = require( './ctors.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Returns a boolean indicating if an environment is little endian. * * @private * @returns {boolean} boolean indicating if an environment is little endian * * @example * var bool = isLittleEndian(); * // returns <boolean> */ function isLittleEndian() { var uint16view; var uint8view; uint16view = new ctors[ 'uint16' ]( 1 ); /* * Set the uint16 view to a value having distinguishable lower and higher order words. * * 4660 => 0x1234 => 0x12 0x34 => '00010010 00110100' => (0x12,0x34) == (18,52) */ uint16view[ 0 ] = 0x1234; // Create a uint8 view on top of the uint16 buffer: uint8view = new ctors[ 'uint8' ]( uint16view.buffer ); // If little endian, the least significant byte will be first... return ( uint8view[ 0 ] === 0x34 ); } // MAIN // bool = isLittleEndian(); // EXPORTS // module.exports = bool; },{"./ctors.js":106}],109:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is `NaN`. * * @module @stdlib/assert/is-nan * * @example * var isnan = require( '@stdlib/assert/is-nan' ); * * var bool = isnan( NaN ); * // returns true * * bool = isnan( new Number( NaN ) ); * // returns true * * bool = isnan( 3.14 ); * // returns false * * bool = isnan( null ); * // returns false * * @example * var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive; * * var bool = isnan( NaN ); * // returns true * * bool = isnan( 3.14 ); * // returns false * * bool = isnan( new Number( NaN ) ); * // returns false * * @example * var isnan = require( '@stdlib/assert/is-nan' ).isObject; * * var bool = isnan( NaN ); * // returns false * * bool = isnan( new Number( NaN ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isnan = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isnan, 'isPrimitive', isPrimitive ); setReadOnly( isnan, 'isObject', isObject ); // EXPORTS // module.exports = isnan; },{"./main.js":110,"./object.js":111,"./primitive.js":112,"@stdlib/utils/define-nonenumerable-read-only-property":297}],110:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is `NaN`. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is `NaN` * * @example * var bool = isnan( NaN ); * // returns true * * @example * var bool = isnan( new Number( NaN ) ); * // returns true * * @example * var bool = isnan( 3.14 ); * // returns false * * @example * var bool = isnan( null ); * // returns false */ function isnan( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isnan; },{"./object.js":111,"./primitive.js":112}],111:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isObject; var isNan = require( '@stdlib/math/base/assert/is-nan' ); // MAIN // /** * Tests if a value is a number object having a value of `NaN`. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a value of `NaN` * * @example * var bool = isnan( NaN ); * // returns false * * @example * var bool = isnan( new Number( NaN ) ); * // returns true */ function isnan( value ) { return ( isNumber( value ) && isNan( value.valueOf() ) ); } // EXPORTS // module.exports = isnan; },{"@stdlib/assert/is-number":128,"@stdlib/math/base/assert/is-nan":239}],112:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; var isNan = require( '@stdlib/math/base/assert/is-nan' ); // MAIN // /** * Tests if a value is a `NaN` number primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a `NaN` number primitive * * @example * var bool = isnan( NaN ); * // returns true * * @example * var bool = isnan( 3.14 ); * // returns false * * @example * var bool = isnan( new Number( NaN ) ); * // returns false */ function isnan( value ) { return ( isNumber( value ) && isNan( value ) ); } // EXPORTS // module.exports = isnan; },{"@stdlib/assert/is-number":128,"@stdlib/math/base/assert/is-nan":239}],113:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is Node stream-like. * * @module @stdlib/assert/is-node-stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' ); * * var stream = transformStream(); * * var bool = isNodeStreamLike( stream ); * // returns true * * bool = isNodeStreamLike( {} ); * // returns false */ // MODULES // var isNodeStreamLike = require( './main.js' ); // EXPORTS // module.exports = isNodeStreamLike; },{"./main.js":114}],114:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Tests if a value is Node stream-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is Node stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * * var stream = transformStream(); * * var bool = isNodeStreamLike( stream ); * // returns true * * bool = isNodeStreamLike( {} ); * // returns false */ function isNodeStreamLike( value ) { return ( // Must be an object: value !== null && typeof value === 'object' && // Should be an event emitter: typeof value.on === 'function' && typeof value.once === 'function' && typeof value.emit === 'function' && typeof value.addListener === 'function' && typeof value.removeListener === 'function' && typeof value.removeAllListeners === 'function' && // Should have a `pipe` method (Node streams inherit from `Stream`, including writable streams): typeof value.pipe === 'function' ); } // EXPORTS // module.exports = isNodeStreamLike; },{}],115:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is Node writable stream-like. * * @module @stdlib/assert/is-node-writable-stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' ); * * var stream = transformStream(); * * var bool = isNodeWritableStreamLike( stream ); * // returns true * * bool = isNodeWritableStreamLike( {} ); * // returns false */ // MODULES // var isNodeWritableStreamLike = require( './main.js' ); // EXPORTS // module.exports = isNodeWritableStreamLike; },{"./main.js":116}],116:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 no-underscore-dangle */ 'use strict'; // MODULES // var isNodeStreamLike = require( '@stdlib/assert/is-node-stream-like' ); // MAIN // /** * Tests if a value is Node writable stream-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is Node writable stream-like * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * * var stream = transformStream(); * * var bool = isNodeWritableStreamLike( stream ); * // returns true * * bool = isNodeWritableStreamLike( {} ); * // returns false */ function isNodeWritableStreamLike( value ) { return ( // Must be stream-like: isNodeStreamLike( value ) && // Should have writable stream methods: typeof value._write === 'function' && // Should have writable stream state: typeof value._writableState === 'object' ); } // EXPORTS // module.exports = isNodeWritableStreamLike; },{"@stdlib/assert/is-node-stream-like":113}],117:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an array-like object containing only nonnegative integers. * * @module @stdlib/assert/is-nonnegative-integer-array * * @example * var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ); * * var bool = isNonNegativeIntegerArray( [ 3.0, new Number(3.0) ] ); * // returns true * * bool = isNonNegativeIntegerArray( [ 3.0, '3.0' ] ); * // returns false * * @example * var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives; * * var bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] ); * // returns true * * bool = isNonNegativeIntegerArray( [ 3.0, new Number(1.0) ] ); * // returns false * * @example * var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).objects; * * var bool = isNonNegativeIntegerArray( [ new Number(3.0), new Number(1.0) ] ); * // returns true * * bool = isNonNegativeIntegerArray( [ 1.0, 0.0, 10.0 ] ); * // returns false */ // MODULES // var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ); var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var arrayfun = require( '@stdlib/assert/tools/array-like-function' ); // MAIN // var isNonNegativeIntegerArray = arrayfun( isNonNegativeInteger ); setReadOnly( isNonNegativeIntegerArray, 'primitives', arrayfun( isNonNegativeInteger.isPrimitive ) ); setReadOnly( isNonNegativeIntegerArray, 'objects', arrayfun( isNonNegativeInteger.isObject ) ); // EXPORTS // module.exports = isNonNegativeIntegerArray; },{"@stdlib/assert/is-nonnegative-integer":118,"@stdlib/assert/tools/array-like-function":166,"@stdlib/utils/define-nonenumerable-read-only-property":297}],118:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a nonnegative integer. * * @module @stdlib/assert/is-nonnegative-integer * * @example * var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ); * * var bool = isNonNegativeInteger( 5.0 ); * // returns true * * bool = isNonNegativeInteger( new Number( 5.0 ) ); * // returns true * * bool = isNonNegativeInteger( -5.0 ); * // returns false * * bool = isNonNegativeInteger( 3.14 ); * // returns false * * bool = isNonNegativeInteger( null ); * // returns false * * @example * var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; * * var bool = isNonNegativeInteger( 3.0 ); * // returns true * * bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns false * * @example * var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isObject; * * var bool = isNonNegativeInteger( 3.0 ); * // returns false * * bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isNonNegativeInteger = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isNonNegativeInteger, 'isPrimitive', isPrimitive ); setReadOnly( isNonNegativeInteger, 'isObject', isObject ); // EXPORTS // module.exports = isNonNegativeInteger; },{"./main.js":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":297}],119:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a nonnegative integer. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a nonnegative integer * * @example * var bool = isNonNegativeInteger( 5.0 ); * // returns true * * @example * var bool = isNonNegativeInteger( new Number( 5.0 ) ); * // returns true * * @example * var bool = isNonNegativeInteger( -5.0 ); * // returns false * * @example * var bool = isNonNegativeInteger( 3.14 ); * // returns false * * @example * var bool = isNonNegativeInteger( null ); * // returns false */ function isNonNegativeInteger( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isNonNegativeInteger; },{"./object.js":120,"./primitive.js":121}],120:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isObject; // MAIN // /** * Tests if a value is a number object having a nonnegative integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a nonnegative integer value * * @example * var bool = isNonNegativeInteger( 3.0 ); * // returns false * * @example * var bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns true */ function isNonNegativeInteger( value ) { return ( isInteger( value ) && value.valueOf() >= 0 ); } // EXPORTS // module.exports = isNonNegativeInteger; },{"@stdlib/assert/is-integer":101}],121:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // MAIN // /** * Tests if a value is a number primitive having a nonnegative integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative integer value * * @example * var bool = isNonNegativeInteger( 3.0 ); * // returns true * * @example * var bool = isNonNegativeInteger( new Number( 3.0 ) ); * // returns false */ function isNonNegativeInteger( value ) { return ( isInteger( value ) && value >= 0 ); } // EXPORTS // module.exports = isNonNegativeInteger; },{"@stdlib/assert/is-integer":101}],122:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a nonnegative number. * * @module @stdlib/assert/is-nonnegative-number * * @example * var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ); * * var bool = isNonNegativeNumber( 5.0 ); * // returns true * * bool = isNonNegativeNumber( new Number( 5.0 ) ); * // returns true * * bool = isNonNegativeNumber( 3.14 ); * // returns true * * bool = isNonNegativeNumber( -5.0 ); * // returns false * * bool = isNonNegativeNumber( null ); * // returns false * * @example * var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive; * * var bool = isNonNegativeNumber( 3.0 ); * // returns true * * bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns false * * @example * var isNonNegativeNumber = require( '@stdlib/assert/is-nonnegative-number' ).isObject; * * var bool = isNonNegativeNumber( 3.0 ); * // returns false * * bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isNonNegativeNumber = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isNonNegativeNumber, 'isPrimitive', isPrimitive ); setReadOnly( isNonNegativeNumber, 'isObject', isObject ); // EXPORTS // module.exports = isNonNegativeNumber; },{"./main.js":123,"./object.js":124,"./primitive.js":125,"@stdlib/utils/define-nonenumerable-read-only-property":297}],123:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a nonnegative number. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a nonnegative number * * @example * var bool = isNonNegativeNumber( 5.0 ); * // returns true * * @example * var bool = isNonNegativeNumber( new Number( 5.0 ) ); * // returns true * * @example * var bool = isNonNegativeNumber( 3.14 ); * // returns true * * @example * var bool = isNonNegativeNumber( -5.0 ); * // returns false * * @example * var bool = isNonNegativeNumber( null ); * // returns false */ function isNonNegativeNumber( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isNonNegativeNumber; },{"./object.js":124,"./primitive.js":125}],124:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isObject; // MAIN // /** * Tests if a value is a number object having a nonnegative value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a nonnegative number value * * @example * var bool = isNonNegativeNumber( 3.0 ); * // returns false * * @example * var bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns true */ function isNonNegativeNumber( value ) { return ( isNumber( value ) && value.valueOf() >= 0.0 ); } // EXPORTS // module.exports = isNonNegativeNumber; },{"@stdlib/assert/is-number":128}],125:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; // MAIN // /** * Tests if a value is a number primitive having a nonnegative value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having a nonnegative number value * * @example * var bool = isNonNegativeNumber( 3.0 ); * // returns true * * @example * var bool = isNonNegativeNumber( new Number( 3.0 ) ); * // returns false */ function isNonNegativeNumber( value ) { return ( isNumber( value ) && value >= 0.0 ); } // EXPORTS // module.exports = isNonNegativeNumber; },{"@stdlib/assert/is-number":128}],126:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is `null`. * * @module @stdlib/assert/is-null * * @example * var isNull = require( '@stdlib/assert/is-null' ); * * var value = null; * * var bool = isNull( value ); * // returns true */ // MODULES // var isNull = require( './main.js' ); // EXPORTS // module.exports = isNull; },{"./main.js":127}],127:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Tests if a value is `null`. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is null * * @example * var bool = isNull( null ); * // returns true * * bool = isNull( true ); * // returns false */ function isNull( value ) { return value === null; } // EXPORTS // module.exports = isNull; },{}],128:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a number. * * @module @stdlib/assert/is-number * * @example * var isNumber = require( '@stdlib/assert/is-number' ); * * var bool = isNumber( 3.14 ); * // returns true * * bool = isNumber( new Number( 3.14 ) ); * // returns true * * bool = isNumber( NaN ); * // returns true * * bool = isNumber( null ); * // returns false * * @example * var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive; * * var bool = isNumber( 3.14 ); * // returns true * * bool = isNumber( NaN ); * // returns true * * bool = isNumber( new Number( 3.14 ) ); * // returns false * * @example * var isNumber = require( '@stdlib/assert/is-number' ).isObject; * * var bool = isNumber( 3.14 ); * // returns false * * bool = isNumber( new Number( 3.14 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isNumber = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isNumber, 'isPrimitive', isPrimitive ); setReadOnly( isNumber, 'isObject', isObject ); // EXPORTS // module.exports = isNumber; },{"./main.js":129,"./object.js":130,"./primitive.js":131,"@stdlib/utils/define-nonenumerable-read-only-property":297}],129:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a number. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a number * * @example * var bool = isNumber( 3.14 ); * // returns true * * @example * var bool = isNumber( new Number( 3.14 ) ); * // returns true * * @example * var bool = isNumber( NaN ); * // returns true * * @example * var bool = isNumber( null ); * // returns false */ function isNumber( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isNumber; },{"./object.js":130,"./primitive.js":131}],130:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var Number = require( '@stdlib/number/ctor' ); var test = require( './try2serialize.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a number object. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object * * @example * var bool = isNumber( 3.14 ); * // returns false * * @example * var bool = isNumber( new Number( 3.14 ) ); * // returns true */ function isNumber( value ) { if ( typeof value === 'object' ) { if ( value instanceof Number ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object Number]' ); } return false; } // EXPORTS // module.exports = isNumber; },{"./try2serialize.js":133,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/number/ctor":248,"@stdlib/utils/native-class":346}],131:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Tests if a value is a number primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive * * @example * var bool = isNumber( 3.14 ); * // returns true * * @example * var bool = isNumber( NaN ); * // returns true * * @example * var bool = isNumber( new Number( 3.14 ) ); * // returns false */ function isNumber( value ) { return ( typeof value === 'number' ); } // EXPORTS // module.exports = isNumber; },{}],132:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var Number = require( '@stdlib/number/ctor' ); // MAIN // // eslint-disable-next-line stdlib/no-redeclare var toString = Number.prototype.toString; // non-generic // EXPORTS // module.exports = toString; },{"@stdlib/number/ctor":248}],133:[function(require,module,exports){ arguments[4][77][0].apply(exports,arguments) },{"./tostring.js":132,"dup":77}],134:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is object-like. * * @module @stdlib/assert/is-object-like * * @example * var isObjectLike = require( '@stdlib/assert/is-object-like' ); * * var bool = isObjectLike( {} ); * // returns true * * bool = isObjectLike( [] ); * // returns true * * bool = isObjectLike( null ); * // returns false * * @example * var isObjectLike = require( '@stdlib/assert/is-object-like' ).isObjectLikeArray; * * var bool = isObjectLike( [ {}, [] ] ); * // returns true * * bool = isObjectLike( [ {}, '3.0' ] ); * // returns false */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var arrayfun = require( '@stdlib/assert/tools/array-function' ); var isObjectLike = require( './main.js' ); // MAIN // setReadOnly( isObjectLike, 'isObjectLikeArray', arrayfun( isObjectLike ) ); // EXPORTS // module.exports = isObjectLike; },{"./main.js":135,"@stdlib/assert/tools/array-function":164,"@stdlib/utils/define-nonenumerable-read-only-property":297}],135:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Tests if a value is object-like. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is object-like * * @example * var bool = isObjectLike( {} ); * // returns true * * @example * var bool = isObjectLike( [] ); * // returns true * * @example * var bool = isObjectLike( null ); * // returns false */ function isObjectLike( value ) { return ( value !== null && typeof value === 'object' ); } // EXPORTS // module.exports = isObjectLike; },{}],136:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an object. * * @module @stdlib/assert/is-object * * @example * var isObject = require( '@stdlib/assert/is-object' ); * * var bool = isObject( {} ); * // returns true * * bool = isObject( true ); * // returns false */ // MODULES // var isObject = require( './main.js' ); // EXPORTS // module.exports = isObject; },{"./main.js":137}],137:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); // MAIN // /** * Tests if a value is an object; e.g., `{}`. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is an object * * @example * var bool = isObject( {} ); * // returns true * * @example * var bool = isObject( null ); * // returns false */ function isObject( value ) { return ( typeof value === 'object' && value !== null && !isArray( value ) ); } // EXPORTS // module.exports = isObject; },{"@stdlib/assert/is-array":70}],138:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a plain object. * * @module @stdlib/assert/is-plain-object * * @example * var isPlainObject = require( '@stdlib/assert/is-plain-object' ); * * var bool = isPlainObject( {} ); * // returns true * * bool = isPlainObject( null ); * // returns false */ // MODULES // var isPlainObject = require( './main.js' ); // EXPORTS // module.exports = isPlainObject; },{"./main.js":139}],139:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isObject = require( '@stdlib/assert/is-object' ); var isFunction = require( '@stdlib/assert/is-function' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var objectPrototype = Object.prototype; // FUNCTIONS // /** * Tests that an object only has own properties. * * @private * @param {Object} obj - value to test * @returns {boolean} boolean indicating if an object only has own properties */ function ownProps( obj ) { var key; // NOTE: possibility of perf boost if key enumeration order is known (see http://stackoverflow.com/questions/18531624/isplainobject-thing). for ( key in obj ) { if ( !hasOwnProp( obj, key ) ) { return false; } } return true; } // MAIN // /** * Tests if a value is a plain object. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a plain object * * @example * var bool = isPlainObject( {} ); * // returns true * * @example * var bool = isPlainObject( null ); * // returns false */ function isPlainObject( value ) { var proto; // Screen for obvious non-objects... if ( !isObject( value ) ) { return false; } // Objects with no prototype (e.g., `Object.create( null )`) are plain... proto = getPrototypeOf( value ); if ( !proto ) { return true; } // Objects having a prototype are plain if and only if they are constructed with a global `Object` function and the prototype points to the prototype of a plain object... return ( // Cannot have own `constructor` property: !hasOwnProp( value, 'constructor' ) && // Prototype `constructor` property must be a function (see also https://bugs.jquery.com/ticket/9897 and http://stackoverflow.com/questions/18531624/isplainobject-thing): hasOwnProp( proto, 'constructor' ) && isFunction( proto.constructor ) && nativeClass( proto.constructor ) === '[object Function]' && // Test for object-specific method: hasOwnProp( proto, 'isPrototypeOf' ) && isFunction( proto.isPrototypeOf ) && ( // Test if the prototype matches the global `Object` prototype (same realm): proto === objectPrototype || // Test that all properties are own properties (cross-realm; *most* likely a plain object): ownProps( value ) ) ); } // EXPORTS // module.exports = isPlainObject; },{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-function":93,"@stdlib/assert/is-object":136,"@stdlib/utils/get-prototype-of":312,"@stdlib/utils/native-class":346}],140:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a positive integer. * * @module @stdlib/assert/is-positive-integer * * @example * var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ); * * var bool = isPositiveInteger( 5.0 ); * // returns true * * bool = isPositiveInteger( new Number( 5.0 ) ); * // returns true * * bool = isPositiveInteger( -5.0 ); * // returns false * * bool = isPositiveInteger( 3.14 ); * // returns false * * bool = isPositiveInteger( null ); * // returns false * * @example * var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; * * var bool = isPositiveInteger( 3.0 ); * // returns true * * bool = isPositiveInteger( new Number( 3.0 ) ); * // returns false * * @example * var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isObject; * * var bool = isPositiveInteger( 3.0 ); * // returns false * * bool = isPositiveInteger( new Number( 3.0 ) ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isPositiveInteger = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isPositiveInteger, 'isPrimitive', isPrimitive ); setReadOnly( isPositiveInteger, 'isObject', isObject ); // EXPORTS // module.exports = isPositiveInteger; },{"./main.js":141,"./object.js":142,"./primitive.js":143,"@stdlib/utils/define-nonenumerable-read-only-property":297}],141:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a positive integer. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a positive integer * * @example * var bool = isPositiveInteger( 5.0 ); * // returns true * * @example * var bool = isPositiveInteger( new Number( 5.0 ) ); * // returns true * * @example * var bool = isPositiveInteger( 0.0 ); * // returns false * * @example * var bool = isPositiveInteger( -5.0 ); * // returns false * * @example * var bool = isPositiveInteger( 3.14 ); * // returns false * * @example * var bool = isPositiveInteger( null ); * // returns false */ function isPositiveInteger( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isPositiveInteger; },{"./object.js":142,"./primitive.js":143}],142:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isObject; // MAIN // /** * Tests if a value is a number object having a positive integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number object having a positive integer value * * @example * var bool = isPositiveInteger( 3.0 ); * // returns false * * @example * var bool = isPositiveInteger( new Number( 3.0 ) ); * // returns true */ function isPositiveInteger( value ) { return ( isInteger( value ) && value.valueOf() > 0.0 ); } // EXPORTS // module.exports = isPositiveInteger; },{"@stdlib/assert/is-integer":101}],143:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // MAIN // /** * Tests if a value is a number primitive having a positive integer value. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a number primitive having a positive integer value * * @example * var bool = isPositiveInteger( 3.0 ); * // returns true * * @example * var bool = isPositiveInteger( new Number( 3.0 ) ); * // returns false */ function isPositiveInteger( value ) { return ( isInteger( value ) && value > 0.0 ); } // EXPORTS // module.exports = isPositiveInteger; },{"@stdlib/assert/is-integer":101}],144:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; var exec = RegExp.prototype.exec; // non-generic // EXPORTS // module.exports = exec; },{}],145:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a regular expression. * * @module @stdlib/assert/is-regexp * * @example * var isRegExp = require( '@stdlib/assert/is-regexp' ); * * var bool = isRegExp( /\.+/ ); * // returns true * * bool = isRegExp( {} ); * // returns false */ // MODULES // var isRegExp = require( './main.js' ); // EXPORTS // module.exports = isRegExp; },{"./main.js":146}],146:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var test = require( './try2exec.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a regular expression. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a regular expression * * @example * var bool = isRegExp( /\.+/ ); * // returns true * * @example * var bool = isRegExp( {} ); * // returns false */ function isRegExp( value ) { if ( typeof value === 'object' ) { if ( value instanceof RegExp ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object RegExp]' ); } return false; } // EXPORTS // module.exports = isRegExp; },{"./try2exec.js":147,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/utils/native-class":346}],147:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var exec = require( './exec.js' ); // MAIN // /** * Attempts to call a `RegExp` method. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if able to call a `RegExp` method */ function test( value ) { try { exec.call( value ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = test; },{"./exec.js":144}],148:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is an array of strings. * * @module @stdlib/assert/is-string-array * * @example * var isStringArray = require( '@stdlib/assert/is-string-array' ); * * var bool = isStringArray( [ 'abc', 'def' ] ); * // returns true * * bool = isStringArray( [ 'abc', 123 ] ); * // returns false * * @example * var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; * * var bool = isStringArray( [ 'abc', 'def' ] ); * // returns true * * bool = isStringArray( [ 'abc', new String( 'def' ) ] ); * // returns false * * @example * var isStringArray = require( '@stdlib/assert/is-string-array' ).objects; * * var bool = isStringArray( [ new String( 'abc' ), new String( 'def' ) ] ); * // returns true * * bool = isStringArray( [ new String( 'abc' ), 'def' ] ); * // returns false */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var arrayfun = require( '@stdlib/assert/tools/array-function' ); var isString = require( '@stdlib/assert/is-string' ); // MAIN // var isStringArray = arrayfun( isString ); setReadOnly( isStringArray, 'primitives', arrayfun( isString.isPrimitive ) ); setReadOnly( isStringArray, 'objects', arrayfun( isString.isObject ) ); // EXPORTS // module.exports = isStringArray; },{"@stdlib/assert/is-string":149,"@stdlib/assert/tools/array-function":164,"@stdlib/utils/define-nonenumerable-read-only-property":297}],149:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a string. * * @module @stdlib/assert/is-string * * @example * var isString = require( '@stdlib/assert/is-string' ); * * var bool = isString( 'beep' ); * // returns true * * bool = isString( new String( 'beep' ) ); * // returns true * * bool = isString( 5 ); * // returns false * * @example * var isString = require( '@stdlib/assert/is-string' ).isObject; * * var bool = isString( new String( 'beep' ) ); * // returns true * * bool = isString( 'beep' ); * // returns false * * @example * var isString = require( '@stdlib/assert/is-string' ).isPrimitive; * * var bool = isString( 'beep' ); * // returns true * * bool = isString( new String( 'beep' ) ); * // returns false */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isString = require( './main.js' ); var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // setReadOnly( isString, 'isPrimitive', isPrimitive ); setReadOnly( isString, 'isObject', isObject ); // EXPORTS // module.exports = isString; },{"./main.js":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":297}],150:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isPrimitive = require( './primitive.js' ); var isObject = require( './object.js' ); // MAIN // /** * Tests if a value is a string. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a string * * @example * var bool = isString( new String( 'beep' ) ); * // returns true * * @example * var bool = isString( 'beep' ); * // returns true */ function isString( value ) { return ( isPrimitive( value ) || isObject( value ) ); } // EXPORTS // module.exports = isString; },{"./object.js":151,"./primitive.js":152}],151:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var nativeClass = require( '@stdlib/utils/native-class' ); var test = require( './try2valueof.js' ); // VARIABLES // var FLG = hasToStringTag(); // MAIN // /** * Tests if a value is a string object. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a string object * * @example * var bool = isString( new String( 'beep' ) ); * // returns true * * @example * var bool = isString( 'beep' ); * // returns false */ function isString( value ) { if ( typeof value === 'object' ) { if ( value instanceof String ) { return true; } if ( FLG ) { return test( value ); } return ( nativeClass( value ) === '[object String]' ); } return false; } // EXPORTS // module.exports = isString; },{"./try2valueof.js":153,"@stdlib/assert/has-tostringtag-support":50,"@stdlib/utils/native-class":346}],152:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Tests if a value is a string primitive. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a string primitive * * @example * var bool = isString( 'beep' ); * // returns true * * @example * var bool = isString( new String( 'beep' ) ); * // returns false */ function isString( value ) { return ( typeof value === 'string' ); } // EXPORTS // module.exports = isString; },{}],153:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var valueOf = require( './valueof.js' ); // eslint-disable-line stdlib/no-redeclare // MAIN // /** * Attempts to extract a string value. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating if a string can be extracted */ function test( value ) { try { valueOf.call( value ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = test; },{"./valueof.js":154}],154:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // eslint-disable-next-line stdlib/no-redeclare var valueOf = String.prototype.valueOf; // non-generic // EXPORTS // module.exports = valueOf; },{}],155:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a Uint16Array. * * @module @stdlib/assert/is-uint16array * * @example * var isUint16Array = require( '@stdlib/assert/is-uint16array' ); * * var bool = isUint16Array( new Uint16Array( 10 ) ); * // returns true * * bool = isUint16Array( [] ); * // returns false */ // MODULES // var isUint16Array = require( './main.js' ); // EXPORTS // module.exports = isUint16Array; },{"./main.js":156}],156:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint16Array = ( typeof Uint16Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint16Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint16Array * * @example * var bool = isUint16Array( new Uint16Array( 10 ) ); * // returns true * * @example * var bool = isUint16Array( [] ); * // returns false */ function isUint16Array( value ) { return ( ( hasUint16Array && value instanceof Uint16Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint16Array]' ); } // EXPORTS // module.exports = isUint16Array; },{"@stdlib/utils/native-class":346}],157:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a Uint32Array. * * @module @stdlib/assert/is-uint32array * * @example * var isUint32Array = require( '@stdlib/assert/is-uint32array' ); * * var bool = isUint32Array( new Uint32Array( 10 ) ); * // returns true * * bool = isUint32Array( [] ); * // returns false */ // MODULES // var isUint32Array = require( './main.js' ); // EXPORTS // module.exports = isUint32Array; },{"./main.js":158}],158:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint32Array = ( typeof Uint32Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint32Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint32Array * * @example * var bool = isUint32Array( new Uint32Array( 10 ) ); * // returns true * * @example * var bool = isUint32Array( [] ); * // returns false */ function isUint32Array( value ) { return ( ( hasUint32Array && value instanceof Uint32Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint32Array]' ); } // EXPORTS // module.exports = isUint32Array; },{"@stdlib/utils/native-class":346}],159:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a Uint8Array. * * @module @stdlib/assert/is-uint8array * * @example * var isUint8Array = require( '@stdlib/assert/is-uint8array' ); * * var bool = isUint8Array( new Uint8Array( 10 ) ); * // returns true * * bool = isUint8Array( [] ); * // returns false */ // MODULES // var isUint8Array = require( './main.js' ); // EXPORTS // module.exports = isUint8Array; },{"./main.js":160}],160:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint8Array = ( typeof Uint8Array === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint8Array. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint8Array * * @example * var bool = isUint8Array( new Uint8Array( 10 ) ); * // returns true * * @example * var bool = isUint8Array( [] ); * // returns false */ function isUint8Array( value ) { return ( ( hasUint8Array && value instanceof Uint8Array ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint8Array]' ); } // EXPORTS // module.exports = isUint8Array; },{"@stdlib/utils/native-class":346}],161:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a value is a Uint8ClampedArray. * * @module @stdlib/assert/is-uint8clampedarray * * @example * var isUint8ClampedArray = require( '@stdlib/assert/is-uint8clampedarray' ); * * var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) ); * // returns true * * bool = isUint8ClampedArray( [] ); * // returns false */ // MODULES // var isUint8ClampedArray = require( './main.js' ); // EXPORTS // module.exports = isUint8ClampedArray; },{"./main.js":162}],162:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); // VARIABLES // var hasUint8ClampedArray = ( typeof Uint8ClampedArray === 'function' ); // eslint-disable-line stdlib/require-globals // MAIN // /** * Tests if a value is a Uint8ClampedArray. * * @param {*} value - value to test * @returns {boolean} boolean indicating whether value is a Uint8ClampedArray * * @example * var bool = isUint8ClampedArray( new Uint8ClampedArray( 10 ) ); * // returns true * * @example * var bool = isUint8ClampedArray( [] ); * // returns false */ function isUint8ClampedArray( value ) { return ( ( hasUint8ClampedArray && value instanceof Uint8ClampedArray ) || // eslint-disable-line stdlib/require-globals nativeClass( value ) === '[object Uint8ClampedArray]' ); } // EXPORTS // module.exports = isUint8ClampedArray; },{"@stdlib/utils/native-class":346}],163:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); // MAIN // /** * Returns a function which tests if every element in an array passes a test condition. * * @param {Function} predicate - function to apply * @throws {TypeError} must provide a function * @returns {Function} an array function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arrayfcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ function arrayfcn( predicate ) { if ( typeof predicate !== 'function' ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' ); } return every; /** * Tests if every element in an array passes a test condition. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an array for which all elements pass a test condition */ function every( value ) { var len; var i; if ( !isArray( value ) ) { return false; } len = value.length; if ( len === 0 ) { return false; } for ( i = 0; i < len; i++ ) { if ( predicate( value[ i ] ) === false ) { return false; } } return true; } } // EXPORTS // module.exports = arrayfcn; },{"@stdlib/assert/is-array":70}],164:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a function which tests if every element in an array passes a test condition. * * @module @stdlib/assert/tools/array-function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * var arrayfcn = require( '@stdlib/assert/tools/array-function' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arrayfcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ // MODULES // var arrayfcn = require( './arrayfcn.js' ); // EXPORTS // module.exports = arrayfcn; },{"./arrayfcn.js":163}],165:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isArrayLike = require( '@stdlib/assert/is-array-like' ); // MAIN // /** * Returns a function which tests if every element in an array-like object passes a test condition. * * @param {Function} predicate - function to apply * @throws {TypeError} must provide a function * @returns {Function} an array-like object function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arraylikefcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ function arraylikefcn( predicate ) { if ( typeof predicate !== 'function' ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + predicate + '`.' ); } return every; /** * Tests if every element in an array-like object passes a test condition. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value is an array-like object for which all elements pass a test condition */ function every( value ) { var len; var i; if ( !isArrayLike( value ) ) { return false; } len = value.length; if ( len === 0 ) { return false; } for ( i = 0; i < len; i++ ) { if ( predicate( value[ i ] ) === false ) { return false; } } return true; } } // EXPORTS // module.exports = arraylikefcn; },{"@stdlib/assert/is-array-like":68}],166:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a function which tests if every element in an array-like object passes a test condition. * * @module @stdlib/assert/tools/array-like-function * * @example * var isOdd = require( '@stdlib/assert/is-odd' ); * var arraylikefcn = require( '@stdlib/assert/tools/array-like-function' ); * * var arr1 = [ 1, 3, 5, 7 ]; * var arr2 = [ 3, 5, 8 ]; * * var validate = arraylikefcn( isOdd ); * * var bool = validate( arr1 ); * // returns true * * bool = validate( arr2 ); * // returns false */ // MODULES // var arraylikefcn = require( './arraylikefcn.js' ); // EXPORTS // module.exports = arraylikefcn; },{"./arraylikefcn.js":165}],167:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var TransformStream = require( '@stdlib/streams/node/transform' ); var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var isFunction = require( '@stdlib/assert/is-function' ); var createHarness = require( './harness' ); var harness = require( './get_harness.js' ); // VARIABLES // var listeners = []; // FUNCTIONS // /** * Callback invoked when a harness finishes running all benchmarks. * * @private */ function done() { var len; var f; var i; len = listeners.length; // Inform all the listeners that the harness has finished... for ( i = 0; i < len; i++ ) { f = listeners.shift(); f(); } } /** * Creates a results stream. * * @private * @param {Options} [options] - stream options * @throws {Error} must provide valid stream options * @returns {TransformStream} results stream */ function createStream( options ) { var stream; var bench; var opts; if ( arguments.length ) { opts = options; } else { opts = {}; } // If we have already created a harness, calling this function simply creates another results stream... if ( harness.cached ) { bench = harness(); return bench.createStream( opts ); } stream = new TransformStream( opts ); opts.stream = stream; // Create a harness which uses the created output stream: harness( opts, done ); return stream; } /** * Adds a listener for when a harness finishes running all benchmarks. * * @private * @param {Callback} clbk - listener * @throws {TypeError} must provide a function * @throws {Error} must provide a listener only once * @returns {void} */ function onFinish( clbk ) { var i; if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `'+clbk+'`.' ); } // Allow adding a listener only once... for ( i = 0; i < listeners.length; i++ ) { if ( clbk === listeners[ i ] ) { throw new Error( 'invalid argument. Attempted to add duplicate listener.' ); } } listeners.push( clbk ); } // MAIN // /** * Runs a benchmark. * * @param {string} name - benchmark name * @param {Options} [options] - benchmark options * @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations * @param {PositiveInteger} [options.repeats=3] - number of repeats * @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @throws {TypeError} first argument must be a string * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} benchmark argument must a function * @returns {Benchmark} benchmark harness * * @example * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); */ function bench( name, options, benchmark ) { var h = harness( done ); if ( arguments.length < 2 ) { h( name ); } else if ( arguments.length === 2 ) { h( name, options ); } else { h( name, options, benchmark ); } return bench; } /** * Creates a benchmark harness. * * @name createHarness * @memberof bench * @type {Function} * @param {Options} [options] - harness options * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness */ setReadOnly( bench, 'createHarness', createHarness ); /** * Creates a results stream. * * @name createStream * @memberof bench * @type {Function} * @param {Options} [options] - stream options * @throws {Error} must provide valid stream options * @returns {TransformStream} results stream */ setReadOnly( bench, 'createStream', createStream ); /** * Adds a listener for when a harness finishes running all benchmarks. * * @name onFinish * @memberof bench * @type {Function} * @param {Callback} clbk - listener * @throws {TypeError} must provide a function * @throws {Error} must provide a listener only once * @returns {void} */ setReadOnly( bench, 'onFinish', onFinish ); // EXPORTS // module.exports = bench; },{"./get_harness.js":189,"./harness":190,"@stdlib/assert/is-function":93,"@stdlib/streams/node/transform":273,"@stdlib/utils/define-nonenumerable-read-only-property":297}],168:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Generates an assertion. * * @private * @param {boolean} ok - assertion outcome * @param {Options} opts - options */ function assert( ok, opts ) { /* eslint-disable no-invalid-this, no-unused-vars */ // TODO: remove no-unused-vars once `err` is used var result; var err; result = { 'id': this._count, 'ok': ok, 'skip': opts.skip, 'todo': opts.todo, 'name': opts.message || '(unnamed assert)', 'operator': opts.operator }; if ( hasOwnProp( opts, 'actual' ) ) { result.actual = opts.actual; } if ( hasOwnProp( opts, 'expected' ) ) { result.expected = opts.expected; } if ( !ok ) { result.error = opts.error || new Error( this.name ); err = new Error( 'exception' ); // TODO: generate an exception in order to locate the calling function (https://github.com/substack/tape/blob/master/lib/test.js#L215) } this._count += 1; this.emit( 'result', result ); } // EXPORTS // module.exports = assert; },{"@stdlib/assert/has-own-property":46}],169:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // EXPORTS // module.exports = clearTimeout; },{}],170:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var trim = require( '@stdlib/string/trim' ); var replace = require( '@stdlib/string/replace' ); var EOL = require( '@stdlib/regexp/eol' ).REGEXP; // VARIABLES // var RE_COMMENT = /^#\s*/; // MAIN // /** * Writes a comment. * * @private * @param {string} msg - comment message */ function comment( msg ) { /* eslint-disable no-invalid-this */ var lines; var i; msg = trim( msg ); lines = msg.split( EOL ); for ( i = 0; i < lines.length; i++ ) { msg = trim( lines[ i ] ); msg = replace( msg, RE_COMMENT, '' ); this.emit( 'result', msg ); } } // EXPORTS // module.exports = comment; },{"@stdlib/regexp/eol":257,"@stdlib/string/replace":279,"@stdlib/string/trim":281}],171:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Asserts that `actual` is deeply equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ function deepEqual( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' ); // TODO: implement } // EXPORTS // module.exports = deepEqual; },{}],172:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nextTick = require( './../utils/next_tick.js' ); // MAIN // /** * Ends a benchmark. * * @private */ function end() { /* eslint-disable no-invalid-this */ var self = this; if ( this._ended ) { this.fail( '.end() called more than once' ); } else { // Prevents releasing the zalgo when running synchronous benchmarks. nextTick( onTick ); } this._ended = true; this._running = false; /** * Callback invoked upon a subsequent tick of the event loop. * * @private */ function onTick() { self.emit( 'end' ); } } // EXPORTS // module.exports = end; },{"./../utils/next_tick.js":209}],173:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Returns a `boolean` indicating if a benchmark has ended. * * @private * @returns {boolean} boolean indicating if a benchmark has ended */ function ended() { /* eslint-disable no-invalid-this */ return this._ended; } // EXPORTS // module.exports = ended; },{}],174:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Asserts that `actual` is strictly equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ function equal( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this._assert( actual === expected, { 'message': msg || 'should be equal', 'operator': 'equal', 'expected': expected, 'actual': actual }); } // EXPORTS // module.exports = equal; },{}],175:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Forcefully ends a benchmark. * * @private * @returns {void} */ function exit() { /* eslint-disable no-invalid-this */ if ( this._exited ) { // If we have already "exited", do not create more failing assertions when one should suffice... return; } // Only "exit" when a benchmark has either not yet been run or is currently running. If a benchmark has already ended, no need to generate a failing assertion. if ( !this._ended ) { this._exited = true; this.fail( 'benchmark exited without ending' ); // Allow running benchmarks to call `end` on their own... if ( !this._running ) { this.end(); } } } // EXPORTS // module.exports = exit; },{}],176:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Generates a failing assertion. * * @private * @param {string} msg - message */ function fail( msg ) { /* eslint-disable no-invalid-this */ this._assert( false, { 'message': msg, 'operator': 'fail' }); } // EXPORTS // module.exports = fail; },{}],177:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var EventEmitter = require( 'events' ).EventEmitter; var inherit = require( '@stdlib/utils/inherit' ); var defineProperty = require( '@stdlib/utils/define-property' ); var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var tic = require( '@stdlib/time/tic' ); var toc = require( '@stdlib/time/toc' ); var run = require( './run.js' ); var exit = require( './exit.js' ); var ended = require( './ended.js' ); var assert = require( './assert.js' ); var comment = require( './comment.js' ); var skip = require( './skip.js' ); var todo = require( './todo.js' ); var fail = require( './fail.js' ); var pass = require( './pass.js' ); var ok = require( './ok.js' ); var notOk = require( './not_ok.js' ); var equal = require( './equal.js' ); var notEqual = require( './not_equal.js' ); var deepEqual = require( './deep_equal.js' ); var notDeepEqual = require( './not_deep_equal.js' ); var end = require( './end.js' ); // MAIN // /** * Benchmark constructor. * * @constructor * @param {string} name - benchmark name * @param {Options} opts - benchmark options * @param {boolean} opts.skip - boolean indicating whether to skip a benchmark * @param {PositiveInteger} opts.iterations - number of iterations * @param {PositiveInteger} opts.timeout - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @returns {Benchmark} Benchmark instance * * @example * var bench = new Benchmark( 'beep', function benchmark( b ) { * var x; * var i; * b.comment( 'Running benchmarks...' ); * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.comment( 'Finished running benchmarks.' ); * b.end(); * }); */ function Benchmark( name, opts, benchmark ) { var hasTicked; var hasTocked; var self; var time; if ( !( this instanceof Benchmark ) ) { return new Benchmark( name, opts, benchmark ); } self = this; hasTicked = false; hasTocked = false; EventEmitter.call( this ); // Private properties: setReadOnly( this, '_benchmark', benchmark ); setReadOnly( this, '_skip', opts.skip ); defineProperty( this, '_ended', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': false }); defineProperty( this, '_running', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': false }); defineProperty( this, '_exited', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': false }); defineProperty( this, '_count', { 'configurable': false, 'enumerable': false, 'writable': true, 'value': 0 }); // Read-only: setReadOnly( this, 'name', name ); setReadOnly( this, 'tic', start ); setReadOnly( this, 'toc', stop ); setReadOnly( this, 'iterations', opts.iterations ); setReadOnly( this, 'timeout', opts.timeout ); return this; /** * Starts a benchmark timer. * * ## Notes * * - Using a scoped variable prevents nefarious mutation by bad actors hoping to manipulate benchmark results. * - The one attack vector which remains is manipulation of the `require` cache for `tic` and `toc`. * - One way to combat cache manipulation is by comparing the checksum of `Function#toString()` against known values. * * @private */ function start() { if ( hasTicked ) { self.fail( '.tic() called more than once' ); } else { self.emit( 'tic' ); hasTicked = true; time = tic(); } } /** * Stops a benchmark timer. * * @private * @returns {void} */ function stop() { var elapsed; var secs; var rate; var out; if ( hasTicked === false ) { return self.fail( '.toc() called before .tic()' ); } elapsed = toc( time ); if ( hasTocked ) { return self.fail( '.toc() called more than once' ); } hasTocked = true; self.emit( 'toc' ); secs = elapsed[ 0 ] + ( elapsed[ 1 ]/1e9 ); rate = self.iterations / secs; out = { 'ok': true, 'operator': 'result', 'iterations': self.iterations, 'elapsed': secs, 'rate': rate }; self.emit( 'result', out ); } } /* * Inherit from the `EventEmitter` prototype. */ inherit( Benchmark, EventEmitter ); /** * Runs a benchmark. * * @private * @name run * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'run', run ); /** * Forcefully ends a benchmark. * * @private * @name exit * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'exit', exit ); /** * Returns a `boolean` indicating if a benchmark has ended. * * @private * @name ended * @memberof Benchmark.prototype * @type {Function} * @returns {boolean} boolean indicating if a benchmark has ended */ setReadOnly( Benchmark.prototype, 'ended', ended ); /** * Generates an assertion. * * @private * @name _assert * @memberof Benchmark.prototype * @type {Function} * @param {boolean} ok - assertion outcome * @param {Options} opts - options */ setReadOnly( Benchmark.prototype, '_assert', assert ); /** * Writes a comment. * * @name comment * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - comment message */ setReadOnly( Benchmark.prototype, 'comment', comment ); /** * Generates an assertion which will be skipped. * * @name skip * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'skip', skip ); /** * Generates an assertion which should be implemented. * * @name todo * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'todo', todo ); /** * Generates a failing assertion. * * @name fail * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'fail', fail ); /** * Generates a passing assertion. * * @name pass * @memberof Benchmark.prototype * @type {Function} * @param {string} msg - message */ setReadOnly( Benchmark.prototype, 'pass', pass ); /** * Asserts that a `value` is truthy. * * @name ok * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'ok', ok ); /** * Asserts that a `value` is falsy. * * @name notOk * @memberof Benchmark.prototype * @type {Function} * @param {*} value - value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'notOk', notOk ); /** * Asserts that `actual` is strictly equal to `expected`. * * @name equal * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'equal', equal ); /** * Asserts that `actual` is not strictly equal to `expected`. * * @name notEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ setReadOnly( Benchmark.prototype, 'notEqual', notEqual ); /** * Asserts that `actual` is deeply equal to `expected`. * * @name deepEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ setReadOnly( Benchmark.prototype, 'deepEqual', deepEqual ); /** * Asserts that `actual` is not deeply equal to `expected`. * * @name notDeepEqual * @memberof Benchmark.prototype * @type {Function} * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ setReadOnly( Benchmark.prototype, 'notDeepEqual', notDeepEqual ); /** * Ends a benchmark. * * @name end * @memberof Benchmark.prototype * @type {Function} */ setReadOnly( Benchmark.prototype, 'end', end ); // EXPORTS // module.exports = Benchmark; },{"./assert.js":168,"./comment.js":170,"./deep_equal.js":171,"./end.js":172,"./ended.js":173,"./equal.js":174,"./exit.js":175,"./fail.js":176,"./not_deep_equal.js":178,"./not_equal.js":179,"./not_ok.js":180,"./ok.js":181,"./pass.js":182,"./run.js":183,"./skip.js":185,"./todo.js":186,"@stdlib/time/tic":283,"@stdlib/time/toc":287,"@stdlib/utils/define-nonenumerable-read-only-property":297,"@stdlib/utils/define-property":302,"@stdlib/utils/inherit":325,"events":378}],178:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Asserts that `actual` is not deeply equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] message */ function notDeepEqual( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this.comment( 'actual: '+actual+'. expected: '+expected+'. msg: '+msg+'.' ); // TODO: implement } // EXPORTS // module.exports = notDeepEqual; },{}],179:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Asserts that `actual` is not strictly equal to `expected`. * * @private * @param {*} actual - actual value * @param {*} expected - expected value * @param {string} [msg] - message */ function notEqual( actual, expected, msg ) { /* eslint-disable no-invalid-this */ this._assert( actual !== expected, { 'message': msg || 'should not be equal', 'operator': 'notEqual', 'expected': expected, 'actual': actual }); } // EXPORTS // module.exports = notEqual; },{}],180:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Asserts that a `value` is falsy. * * @private * @param {*} value - value * @param {string} [msg] - message */ function notOk( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( !value, { 'message': msg || 'should be falsy', 'operator': 'notOk', 'expected': false, 'actual': value }); } // EXPORTS // module.exports = notOk; },{}],181:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Asserts that a `value` is truthy. * * @private * @param {*} value - value * @param {string} [msg] - message */ function ok( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( !!value, { 'message': msg || 'should be truthy', 'operator': 'ok', 'expected': true, 'actual': value }); } // EXPORTS // module.exports = ok; },{}],182:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Generates a passing assertion. * * @private * @param {string} msg - message */ function pass( msg ) { /* eslint-disable no-invalid-this */ this._assert( true, { 'message': msg, 'operator': 'pass' }); } // EXPORTS // module.exports = pass; },{}],183:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var timeout = require( './set_timeout.js' ); var clear = require( './clear_timeout.js' ); // MAIN // /** * Runs a benchmark. * * @private * @returns {void} */ function run() { /* eslint-disable no-invalid-this */ var self; var id; if ( this._skip ) { this.comment( 'SKIP '+this.name ); return this.end(); } if ( !this._benchmark ) { this.comment( 'TODO '+this.name ); return this.end(); } self = this; this._running = true; id = timeout( onTimeout, this.timeout ); this.once( 'end', endTimeout ); this.emit( 'prerun' ); this._benchmark( this ); this.emit( 'run' ); /** * Callback invoked once a timeout ends. * * @private */ function onTimeout() { self.fail( 'benchmark timed out after '+self.timeout+'ms' ); } /** * Clears a timeout. * * @private */ function endTimeout() { clear( id ); } } // EXPORTS // module.exports = run; },{"./clear_timeout.js":169,"./set_timeout.js":184}],184:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // EXPORTS // module.exports = setTimeout; },{}],185:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Generates an assertion which will be skipped. * * @private * @param {*} value - value * @param {string} msg - message */ function skip( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( true, { 'message': msg, 'operator': 'skip', 'skip': true }); } // EXPORTS // module.exports = skip; },{}],186:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Generates an assertion which should be implemented. * * @private * @param {*} value - value * @param {string} msg - message */ function todo( value, msg ) { /* eslint-disable no-invalid-this */ this._assert( !!value, { 'message': msg, 'operator': 'todo', 'todo': true }); } // EXPORTS // module.exports = todo; },{}],187:[function(require,module,exports){ module.exports={ "skip": false, "iterations": null, "repeats": 3, "timeout": 300000 } },{}],188:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isObject = require( '@stdlib/assert/is-plain-object' ); var isNodeWritableStreamLike = require( '@stdlib/assert/is-node-writable-stream-like' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var pick = require( '@stdlib/utils/pick' ); var omit = require( '@stdlib/utils/omit' ); var noop = require( '@stdlib/utils/noop' ); var createHarness = require( './harness' ); var logStream = require( './log' ); var canEmitExit = require( './utils/can_emit_exit.js' ); var proc = require( './utils/process.js' ); // MAIN // /** * Creates a benchmark harness which supports closing when a process exits. * * @private * @param {Options} [options] - function options * @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks * @param {Stream} [options.stream] - output writable stream * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness * * @example * var proc = require( 'process' ); * var bench = createExitHarness( onFinish ); * * function onFinish() { * bench.close(); * } * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = createExitHarness().createStream(); * stream.pipe( stdout ); */ function createExitHarness() { var exitCode; var pipeline; var harness; var options; var stream; var topts; var opts; var clbk; if ( arguments.length === 0 ) { options = {}; clbk = noop; } else if ( arguments.length === 1 ) { if ( isFunction( arguments[ 0 ] ) ) { options = {}; clbk = arguments[ 0 ]; } else if ( isObject( arguments[ 0 ] ) ) { options = arguments[ 0 ]; clbk = noop; } else { throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+arguments[ 0 ]+'`.' ); } } else { options = arguments[ 0 ]; if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' ); } clbk = arguments[ 1 ]; if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+clbk+'`.' ); } } opts = {}; if ( hasOwnProp( options, 'autoclose' ) ) { opts.autoclose = options.autoclose; if ( !isBoolean( opts.autoclose ) ) { throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' ); } } if ( hasOwnProp( options, 'stream' ) ) { opts.stream = options.stream; if ( !isNodeWritableStreamLike( opts.stream ) ) { throw new TypeError( 'invalid option. `stream` option must be a writable stream. Option: `'+opts.stream+'`.' ); } } exitCode = 0; // Create a new harness: topts = pick( opts, [ 'autoclose' ] ); harness = createHarness( topts, done ); // Create a results stream: topts = omit( options, [ 'autoclose', 'stream' ] ); stream = harness.createStream( topts ); // Pipe results to an output stream: pipeline = stream.pipe( opts.stream || logStream() ); // If a process can emit an 'exit' event, capture errors in order to set the exit code... if ( canEmitExit ) { pipeline.on( 'error', onError ); proc.on( 'exit', onExit ); } return harness; /** * Callback invoked when a harness finishes. * * @private * @returns {void} */ function done() { return clbk(); } /** * Callback invoked upon a stream `error` event. * * @private * @param {Error} error - error object */ function onError() { exitCode = 1; } /** * Callback invoked upon an `exit` event. * * @private * @param {integer} code - exit code */ function onExit( code ) { if ( code !== 0 ) { // Allow the process to exit... return; } harness.close(); proc.exit( exitCode || harness.exitCode ); } } // EXPORTS // module.exports = createExitHarness; },{"./harness":190,"./log":196,"./utils/can_emit_exit.js":207,"./utils/process.js":210,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-function":93,"@stdlib/assert/is-node-writable-stream-like":115,"@stdlib/assert/is-plain-object":138,"@stdlib/utils/noop":353,"@stdlib/utils/omit":355,"@stdlib/utils/pick":357}],189:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var canEmitExit = require( './utils/can_emit_exit.js' ); var createExitHarness = require( './exit_harness.js' ); // VARIABLES // var harness; // MAIN // /** * Returns a benchmark harness. If a harness has already been created, returns the cached harness. * * @private * @param {Options} [options] - harness options * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @returns {Function} benchmark harness */ function getHarness( options, clbk ) { var opts; var cb; if ( harness ) { return harness; } if ( arguments.length > 1 ) { opts = options; cb = clbk; } else { opts = {}; cb = options; } opts.autoclose = !canEmitExit; harness = createExitHarness( opts, cb ); // Update state: getHarness.cached = true; return harness; } // EXPORTS // module.exports = getHarness; },{"./exit_harness.js":188,"./utils/can_emit_exit.js":207}],190:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); var Runner = require( './../runner' ); var nextTick = require( './../utils/next_tick.js' ); var DEFAULTS = require( './../defaults.json' ); var validate = require( './validate.js' ); var init = require( './init.js' ); // MAIN // /** * Creates a benchmark harness. * * @param {Options} [options] - function options * @param {boolean} [options.autoclose] - boolean indicating whether to automatically close a harness after a harness finishes running all benchmarks * @param {Callback} [clbk] - callback to invoke when a harness finishes running all benchmarks * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} callback argument must be a function * @returns {Function} benchmark harness * * @example * var bench = createHarness( onFinish ); * * function onFinish() { * bench.close(); * console.log( 'Exit code: %d', bench.exitCode ); * } * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = createHarness().createStream(); * stream.pipe( stdout ); */ function createHarness( options, clbk ) { var exitCode; var runner; var queue; var opts; var cb; opts = {}; if ( arguments.length === 1 ) { if ( isFunction( options ) ) { cb = options; } else if ( isObject( options ) ) { opts = options; } else { throw new TypeError( 'invalid argument. Must provide either an options object or a callback function. Value: `'+options+'`.' ); } } else if ( arguments.length > 1 ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+options+'`.' ); } if ( hasOwnProp( options, 'autoclose' ) ) { opts.autoclose = options.autoclose; if ( !isBoolean( opts.autoclose ) ) { throw new TypeError( 'invalid option. `autoclose` option must be a boolean primitive. Option: `'+opts.autoclose+'`.' ); } } cb = clbk; if ( !isFunction( cb ) ) { throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+cb+'`.' ); } } runner = new Runner(); if ( opts.autoclose ) { runner.once( 'done', close ); } if ( cb ) { runner.once( 'done', cb ); } exitCode = 0; queue = []; /** * Benchmark harness. * * @private * @param {string} name - benchmark name * @param {Options} [options] - benchmark options * @param {boolean} [options.skip=false] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations=null] - number of iterations * @param {PositiveInteger} [options.repeats=3] - number of repeats * @param {PositiveInteger} [options.timeout=300000] - number of milliseconds before a benchmark automatically fails * @param {Function} [benchmark] - function containing benchmark code * @throws {TypeError} first argument must be a string * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} benchmark argument must a function * @throws {Error} benchmark error * @returns {Function} benchmark harness */ function harness( name, options, benchmark ) { var opts; var err; var b; if ( !isString( name ) ) { throw new TypeError( 'invalid argument. First argument must be a string. Value: `'+name+'`.' ); } opts = copy( DEFAULTS ); if ( arguments.length === 2 ) { if ( isFunction( options ) ) { b = options; } else { err = validate( opts, options ); if ( err ) { throw err; } } } else if ( arguments.length > 2 ) { err = validate( opts, options ); if ( err ) { throw err; } b = benchmark; if ( !isFunction( b ) ) { throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+b+'`.' ); } } // Add the benchmark to the initialization queue: queue.push( [ name, opts, b ] ); // Perform initialization on the next turn of the event loop (note: this allows all benchmarks to be "registered" within the same turn of the loop; otherwise, we run the risk of registration-execution race conditions (i.e., a benchmark registers and executes before other benchmarks can register, depleting the benchmark queue and leading the harness to close)): if ( queue.length === 1 ) { nextTick( initialize ); } return harness; } /** * Initializes each benchmark. * * @private * @returns {void} */ function initialize() { var idx = -1; return next(); /** * Initialize the next benchmark. * * @private * @returns {void} */ function next() { var args; idx += 1; // If all benchmarks have been initialized, begin running the benchmarks: if ( idx === queue.length ) { queue.length = 0; return runner.run(); } // Initialize the next benchmark: args = queue[ idx ]; init( args[ 0 ], args[ 1 ], args[ 2 ], onInit ); } /** * Callback invoked after performing initialization tasks. * * @private * @param {string} name - benchmark name * @param {Options} opts - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @returns {void} */ function onInit( name, opts, benchmark ) { var b; var i; // Create a `Benchmark` instance for each repeat to ensure each benchmark has its own state... for ( i = 0; i < opts.repeats; i++ ) { b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); runner.push( b ); } return next(); } } /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && !result.ok && !result.todo ) { exitCode = 1; } } /** * Returns a results stream. * * @private * @param {Object} [options] - options * @returns {TransformStream} transform stream */ function createStream( options ) { if ( arguments.length ) { return runner.createStream( options ); } return runner.createStream(); } /** * Closes a benchmark harness. * * @private */ function close() { runner.close(); } /** * Forcefully exits a benchmark harness. * * @private */ function exit() { runner.exit(); } /** * Returns the harness exit code. * * @private * @returns {NonNegativeInteger} exit code */ function getExitCode() { return exitCode; } setReadOnly( harness, 'createStream', createStream ); setReadOnly( harness, 'close', close ); setReadOnly( harness, 'exit', exit ); setReadOnlyAccessor( harness, 'exitCode', getExitCode ); return harness; } // EXPORTS // module.exports = createHarness; },{"./../benchmark-class":177,"./../defaults.json":187,"./../runner":204,"./../utils/next_tick.js":209,"./init.js":191,"./validate.js":194,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-function":93,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-string":149,"@stdlib/utils/copy":293,"@stdlib/utils/define-nonenumerable-read-only-accessor":295,"@stdlib/utils/define-nonenumerable-read-only-property":297}],191:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var pretest = require( './pretest.js' ); var iterations = require( './iterations.js' ); // MAIN // /** * Performs benchmark initialization tasks. * * @private * @param {string} name - benchmark name * @param {Options} opts - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @param {Callback} clbk - callback to invoke after completing initialization tasks * @returns {void} */ function init( name, opts, benchmark, clbk ) { // If no benchmark function, then the benchmark is considered a "todo", so no need to repeat multiple times... if ( !benchmark ) { opts.repeats = 1; return clbk( name, opts, benchmark ); } // If the `skip` option to `true`, no need to initialize or repeat multiple times as will not be running the benchmark: if ( opts.skip ) { opts.repeats = 1; return clbk( name, opts, benchmark ); } // Perform pretests: pretest( name, opts, benchmark, onPreTest ); /** * Callback invoked upon completing pretests. * * @private * @param {Error} [error] - error object * @returns {void} */ function onPreTest( error ) { // If the pretests failed, don't run the benchmark multiple times... if ( error ) { opts.repeats = 1; opts.iterations = 1; return clbk( name, opts, benchmark ); } // If a user specified an iteration number, we can begin running benchmarks... if ( opts.iterations ) { return clbk( name, opts, benchmark ); } // Determine iteration number: iterations( name, opts, benchmark, onIterations ); } /** * Callback invoked upon determining an iteration number. * * @private * @param {(Error|null)} error - error object * @param {PositiveInteger} iter - number of iterations * @returns {void} */ function onIterations( error, iter ) { // If provided an error, then a benchmark failed, and, similar to pretests, don't run the benchmark multiple times... if ( error ) { opts.repeats = 1; opts.iterations = 1; return clbk( name, opts, benchmark ); } opts.iterations = iter; return clbk( name, opts, benchmark ); } } // EXPORTS // module.exports = init; },{"./iterations.js":192,"./pretest.js":193}],192:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); // VARIABLES // var MIN_TIME = 0.1; // seconds var ITERATIONS = 10; // 10^1 var MAX_ITERATIONS = 10000000000; // 10^10 // MAIN // /** * Determines the number of iterations. * * @private * @param {string} name - benchmark name * @param {Options} options - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @param {Callback} clbk - callback to invoke after determining number of iterations * @returns {void} */ function iterations( name, options, benchmark, clbk ) { var opts; var time; // Elapsed time (in seconds): time = 0; // Create a local copy: opts = copy( options ); opts.iterations = ITERATIONS; // Begin running benchmarks: return next(); /** * Run a new benchmark. * * @private */ function next() { var b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); b.once( 'end', onEnd ); b.run(); } /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && result.operator === 'result' ) { time = result.elapsed; } } /** * Callback invoked upon an `end` event. * * @private * @returns {void} */ function onEnd() { if ( time < MIN_TIME && opts.iterations < MAX_ITERATIONS ) { opts.iterations *= 10; return next(); } clbk( null, opts.iterations ); } } // EXPORTS // module.exports = iterations; },{"./../benchmark-class":177,"@stdlib/assert/is-string":149,"@stdlib/utils/copy":293}],193:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var copy = require( '@stdlib/utils/copy' ); var Benchmark = require( './../benchmark-class' ); // MAIN // /** * Runs pretests to sanity check and/or catch failures. * * @private * @param {string} name - benchmark name * @param {Options} options - benchmark options * @param {(Function|undefined)} benchmark - function containing benchmark code * @param {Callback} clbk - callback to invoke after completing pretests */ function pretest( name, options, benchmark, clbk ) { var fail; var opts; var tic; var toc; var b; // Counters to determine the number of `tic` and `toc` events: tic = 0; toc = 0; // Local copy: opts = copy( options ); opts.iterations = 1; // Pretest to check for minimum requirements and/or errors... b = new Benchmark( name, opts, benchmark ); b.on( 'result', onResult ); b.on( 'tic', onTic ); b.on( 'toc', onToc ); b.once( 'end', onEnd ); b.run(); /** * Callback invoked upon a `result` event. * * @private * @param {(string|Object)} result - result */ function onResult( result ) { if ( !isString( result ) && !result.ok && !result.todo ) { fail = true; } } /** * Callback invoked upon a `tic` event. * * @private */ function onTic() { tic += 1; } /** * Callback invoked upon a `toc` event. * * @private */ function onToc() { toc += 1; } /** * Callback invoked upon an `end` event. * * @private * @returns {void} */ function onEnd() { var err; if ( fail ) { // Possibility that failure is intermittent, but we will assume that the usual case is that the failure would persist across all repeats and no sense failing multiple times when once suffices. err = new Error( 'benchmark failed' ); } else if ( tic !== 1 || toc !== 1 ) { // Unable to do anything definitive with timing information (e.g., a tic with no toc or vice versa, or benchmark function calls neither tic nor toc). err = new Error( 'invalid benchmark' ); } if ( err ) { return clbk( err ); } return clbk(); } } // EXPORTS // module.exports = pretest; },{"./../benchmark-class":177,"@stdlib/assert/is-string":149,"@stdlib/utils/copy":293}],194:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isNull = require( '@stdlib/assert/is-null' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {boolean} [options.skip] - boolean indicating whether to skip a benchmark * @param {(PositiveInteger|null)} [options.iterations] - number of iterations * @param {PositiveInteger} [options.repeats] - number of repeats * @param {PositiveInteger} [options.timeout] - number of milliseconds before a benchmark automatically fails * @returns {(Error|null)} error object or null * * @example * var opts = {}; * var options = { * 'skip': false, * 'iterations': 1e6, * 'repeats': 3, * 'timeout': 10000 * }; * * var err = validate( opts, options ); * if ( err ) { * throw err; * } */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'skip' ) ) { opts.skip = options.skip; if ( !isBoolean( opts.skip ) ) { return new TypeError( 'invalid option. `skip` option must be a boolean primitive. Option: `' + opts.skip + '`.' ); } } if ( hasOwnProp( options, 'iterations' ) ) { opts.iterations = options.iterations; if ( !isPositiveInteger( opts.iterations ) && !isNull( opts.iterations ) ) { return new TypeError( 'invalid option. `iterations` option must be either a positive integer or `null`. Option: `' + opts.iterations + '`.' ); } } if ( hasOwnProp( options, 'repeats' ) ) { opts.repeats = options.repeats; if ( !isPositiveInteger( opts.repeats ) ) { return new TypeError( 'invalid option. `repeats` option must be a positive integer. Option: `' + opts.repeats + '`.' ); } } if ( hasOwnProp( options, 'timeout' ) ) { opts.timeout = options.timeout; if ( !isPositiveInteger( opts.timeout ) ) { return new TypeError( 'invalid option. `timeout` option must be a positive integer. Option: `' + opts.timeout + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-null":126,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-positive-integer":140}],195:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Benchmark harness. * * @module @stdlib/bench/harness * * @example * var bench = require( '@stdlib/bench/harness' ); * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); */ // MODULES // var bench = require( './bench.js' ); // EXPORTS // module.exports = bench; },{"./bench.js":167}],196:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var TransformStream = require( '@stdlib/streams/node/transform' ); var fromCodePoint = require( '@stdlib/string/from-code-point' ); var log = require( './log.js' ); // MAIN // /** * Returns a Transform stream for logging to the console. * * @private * @returns {TransformStream} transform stream */ function createStream() { var stream; var line; stream = new TransformStream({ 'transform': transform, 'flush': flush }); line = ''; return stream; /** * Callback invoked upon receiving a new chunk. * * @private * @param {(Buffer|string)} chunk - chunk * @param {string} enc - Buffer encoding * @param {Callback} clbk - callback to invoke after transforming the streamed chunk */ function transform( chunk, enc, clbk ) { var c; var i; for ( i = 0; i < chunk.length; i++ ) { c = fromCodePoint( chunk[ i ] ); if ( c === '\n' ) { flush(); } else { line += c; } } clbk(); } /** * Callback to flush data to `stdout`. * * @private * @param {Callback} [clbk] - callback to invoke after processing data * @returns {void} */ function flush( clbk ) { try { log( line ); } catch ( err ) { stream.emit( 'error', err ); } line = ''; if ( clbk ) { return clbk(); } } } // EXPORTS // module.exports = createStream; },{"./log.js":197,"@stdlib/streams/node/transform":273,"@stdlib/string/from-code-point":277}],197:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Writes a string to the console. * * @private * @param {string} str - string to write */ function log( str ) { console.log( str ); // eslint-disable-line no-console } // EXPORTS // module.exports = log; },{}],198:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Removes any pending benchmarks. * * @private */ function clear() { /* eslint-disable no-invalid-this */ this._benchmarks.length = 0; } // EXPORTS // module.exports = clear; },{}],199:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Closes a benchmark runner. * * @private * @returns {void} */ function closeRunner() { /* eslint-disable no-invalid-this */ var self = this; if ( this._closed ) { return; } this._closed = true; if ( this._benchmarks.length ) { this.clear(); this._stream.write( '# WARNING: harness closed before completion.\n' ); } else { this._stream.write( '#\n' ); this._stream.write( '1..'+this.total+'\n' ); this._stream.write( '# total '+this.total+'\n' ); this._stream.write( '# pass '+this.pass+'\n' ); if ( this.fail ) { this._stream.write( '# fail '+this.fail+'\n' ); } if ( this.skip ) { this._stream.write( '# skip '+this.skip+'\n' ); } if ( this.todo ) { this._stream.write( '# todo '+this.todo+'\n' ); } if ( !this.fail ) { this._stream.write( '#\n# ok\n' ); } } this._stream.once( 'close', onClose ); this._stream.destroy(); /** * Callback invoked upon a `close` event. * * @private */ function onClose() { self.emit( 'close' ); } } // EXPORTS // module.exports = closeRunner; },{}],200:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 no-underscore-dangle */ 'use strict'; // MODULES // var TransformStream = require( '@stdlib/streams/node/transform' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var nextTick = require( './../utils/next_tick.js' ); // VARIABLES // var TAP_HEADER = 'TAP version 13'; // MAIN // /** * Creates a results stream. * * @private * @param {Options} [options] - stream options * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream */ function createStream( options ) { /* eslint-disable no-invalid-this */ var stream; var opts; var self; var id; self = this; if ( arguments.length ) { opts = options; } else { opts = {}; } stream = new TransformStream( opts ); if ( opts.objectMode ) { id = 0; this.on( '_push', onPush ); this.on( 'done', onDone ); } else { stream.write( TAP_HEADER+'\n' ); this._stream.pipe( stream ); } this.on( '_run', onRun ); return stream; /** * Runs the next benchmark. * * @private */ function next() { nextTick( onTick ); } /** * Callback invoked upon the next tick. * * @private * @returns {void} */ function onTick() { var b = self._benchmarks.shift(); if ( b ) { b.run(); if ( !b.ended() ) { return b.once( 'end', next ); } return next(); } self._running = false; self.emit( 'done' ); } /** * Callback invoked upon a run event. * * @private * @returns {void} */ function onRun() { if ( !self._running ) { self._running = true; return next(); } } /** * Callback invoked upon a push event. * * @private * @param {Benchmark} b - benchmark */ function onPush( b ) { var bid = id; id += 1; b.once( 'prerun', onPreRun ); b.on( 'result', onResult ); b.on( 'end', onEnd ); /** * Callback invoked upon a `prerun` event. * * @private */ function onPreRun() { var row = { 'type': 'benchmark', 'name': b.name, 'id': bid }; stream.write( row ); } /** * Callback invoked upon a `result` event. * * @private * @param {(Object|string)} res - result */ function onResult( res ) { if ( isString( res ) ) { res = { 'benchmark': bid, 'type': 'comment', 'name': res }; } else if ( res.operator === 'result' ) { res.benchmark = bid; res.type = 'result'; } else { res.benchmark = bid; res.type = 'assert'; } stream.write( res ); } /** * Callback invoked upon an `end` event. * * @private */ function onEnd() { stream.write({ 'benchmark': bid, 'type': 'end' }); } } /** * Callback invoked upon a `done` event. * * @private */ function onDone() { stream.destroy(); } } // EXPORTS // module.exports = createStream; },{"./../utils/next_tick.js":209,"@stdlib/assert/is-string":149,"@stdlib/streams/node/transform":273}],201:[function(require,module,exports){ /* eslint-disable stdlib/jsdoc-require-throws-tags */ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var replace = require( '@stdlib/string/replace' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var reEOL = require( '@stdlib/regexp/eol' ); // VARIABLES // var RE_WHITESPACE = /\s+/g; // MAIN // /** * Encodes an assertion. * * @private * @param {Object} result - result * @param {PositiveInteger} count - result count * @returns {string} encoded assertion */ function encodeAssertion( result, count ) { var actualStack; var errorStack; var expected; var actual; var indent; var stack; var lines; var out; var i; out = ''; if ( !result.ok ) { out += 'not '; } // Add result count: out += 'ok ' + count; // Add description: if ( result.name ) { out += ' ' + replace( result.name.toString(), RE_WHITESPACE, ' ' ); } // Append directives: if ( result.skip ) { out += ' # SKIP'; } else if ( result.todo ) { out += ' # TODO'; } out += '\n'; if ( result.ok ) { return out; } // Format diagnostics as YAML... indent = ' '; out += indent + '---\n'; out += indent + 'operator: ' + result.operator + '\n'; if ( hasOwnProp( result, 'actual' ) || hasOwnProp( result, 'expected' ) ) { // TODO: inspect object logic (https://github.com/substack/tape/blob/master/lib/results.js#L145) expected = result.expected; actual = result.actual; if ( actual !== actual && expected !== expected ) { throw new Error( 'TODO: remove me' ); } } if ( result.at ) { out += indent + 'at: ' + result.at + '\n'; } if ( result.actual ) { actualStack = result.actual.stack; } if ( result.error ) { errorStack = result.error.stack; } if ( actualStack ) { stack = actualStack; } else { stack = errorStack; } if ( stack ) { lines = stack.toString().split( reEOL.REGEXP ); out += indent + 'stack: |-\n'; for ( i = 0; i < lines.length; i++ ) { out += indent + ' ' + lines[ i ] + '\n'; } } out += indent + '...\n'; return out; } // EXPORTS // module.exports = encodeAssertion; },{"@stdlib/assert/has-own-property":46,"@stdlib/regexp/eol":257,"@stdlib/string/replace":279}],202:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // VARIABLES // var YAML_INDENT = ' '; var YAML_BEGIN = YAML_INDENT + '---\n'; var YAML_END = YAML_INDENT + '...\n'; // MAIN // /** * Encodes a result as a YAML block. * * @private * @param {Object} result - result * @returns {string} encoded result */ function encodeResult( result ) { var out = YAML_BEGIN; out += YAML_INDENT + 'iterations: '+result.iterations+'\n'; out += YAML_INDENT + 'elapsed: '+result.elapsed+'\n'; out += YAML_INDENT + 'rate: '+result.rate+'\n'; out += YAML_END; return out; } // EXPORTS // module.exports = encodeResult; },{}],203:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Forcefully exits a benchmark runner. * * @private */ function exit() { /* eslint-disable no-invalid-this */ var self; var i; for ( i = 0; i < this._benchmarks.length; i++ ) { this._benchmarks[ i ].exit(); } self = this; this.clear(); this._stream.once( 'close', onClose ); this._stream.destroy(); /** * Callback invoked upon a `close` event. * * @private */ function onClose() { self.emit( 'close' ); } } // EXPORTS // module.exports = exit; },{}],204:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var EventEmitter = require( 'events' ).EventEmitter; var inherit = require( '@stdlib/utils/inherit' ); var defineProperty = require( '@stdlib/utils/define-property' ); var TransformStream = require( '@stdlib/streams/node/transform' ); var push = require( './push.js' ); var createStream = require( './create_stream.js' ); var run = require( './run.js' ); var clear = require( './clear.js' ); var close = require( './close.js' ); // eslint-disable-line stdlib/no-redeclare var exit = require( './exit.js' ); // MAIN // /** * Benchmark runner. * * @private * @constructor * @returns {Runner} Runner instance * * @example * var runner = new Runner(); */ function Runner() { if ( !( this instanceof Runner ) ) { return new Runner(); } EventEmitter.call( this ); // Private properties: defineProperty( this, '_benchmarks', { 'value': [], 'configurable': false, 'writable': false, 'enumerable': false }); defineProperty( this, '_stream', { 'value': new TransformStream(), 'configurable': false, 'writable': false, 'enumerable': false }); defineProperty( this, '_closed', { 'value': false, 'configurable': false, 'writable': true, 'enumerable': false }); defineProperty( this, '_running', { 'value': false, 'configurable': false, 'writable': true, 'enumerable': false }); // Public properties: defineProperty( this, 'total', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'fail', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'pass', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'skip', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); defineProperty( this, 'todo', { 'value': 0, 'configurable': false, 'writable': true, 'enumerable': true }); return this; } /* * Inherit from the `EventEmitter` prototype. */ inherit( Runner, EventEmitter ); /** * Adds a new benchmark. * * @private * @memberof Runner.prototype * @function push * @param {Benchmark} b - benchmark */ defineProperty( Runner.prototype, 'push', { 'value': push, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Creates a results stream. * * @private * @memberof Runner.prototype * @function createStream * @param {Options} [options] - stream options * @returns {TransformStream} transform stream */ defineProperty( Runner.prototype, 'createStream', { 'value': createStream, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Runs pending benchmarks. * * @private * @memberof Runner.prototype * @function run */ defineProperty( Runner.prototype, 'run', { 'value': run, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Removes any pending benchmarks. * * @private * @memberof Runner.prototype * @function clear */ defineProperty( Runner.prototype, 'clear', { 'value': clear, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Closes a benchmark runner. * * @private * @memberof Runner.prototype * @function close */ defineProperty( Runner.prototype, 'close', { 'value': close, 'configurable': false, 'writable': false, 'enumerable': false }); /** * Forcefully exits a benchmark runner. * * @private * @memberof Runner.prototype * @function exit */ defineProperty( Runner.prototype, 'exit', { 'value': exit, 'configurable': false, 'writable': false, 'enumerable': false }); // EXPORTS // module.exports = Runner; },{"./clear.js":198,"./close.js":199,"./create_stream.js":200,"./exit.js":203,"./push.js":205,"./run.js":206,"@stdlib/streams/node/transform":273,"@stdlib/utils/define-property":302,"@stdlib/utils/inherit":325,"events":378}],205:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 no-underscore-dangle */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var encodeAssertion = require( './encode_assertion.js' ); var encodeResult = require( './encode_result.js' ); // MAIN // /** * Adds a new benchmark. * * @private * @param {Benchmark} b - benchmark */ function push( b ) { /* eslint-disable no-invalid-this */ var self = this; this._benchmarks.push( b ); b.once( 'prerun', onPreRun ); b.on( 'result', onResult ); this.emit( '_push', b ); /** * Callback invoked upon a `prerun` event. * * @private */ function onPreRun() { self._stream.write( '# '+b.name+'\n' ); } /** * Callback invoked upon a `result` event. * * @private * @param {(Object|string)} res - result * @returns {void} */ function onResult( res ) { // Check for a comment... if ( isString( res ) ) { return self._stream.write( '# '+res+'\n' ); } if ( res.operator === 'result' ) { res = encodeResult( res ); return self._stream.write( res ); } self.total += 1; if ( res.ok ) { if ( res.skip ) { self.skip += 1; } else if ( res.todo ) { self.todo += 1; } self.pass += 1; } // According to the TAP spec, todos pass even if not "ok"... else if ( res.todo ) { self.pass += 1; self.todo += 1; } // Everything else is a failure... else { self.fail += 1; } res = encodeAssertion( res, self.total ); self._stream.write( res ); } } // EXPORTS // module.exports = push; },{"./encode_assertion.js":201,"./encode_result.js":202,"@stdlib/assert/is-string":149}],206:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Runs pending benchmarks. * * @private */ function run() { /* eslint-disable no-invalid-this */ this.emit( '_run' ); } // EXPORTS // module.exports = run; },{}],207:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var IS_BROWSER = require( '@stdlib/assert/is-browser' ); var canExit = require( './can_exit.js' ); // MAIN // var bool = ( !IS_BROWSER && canExit ); // EXPORTS // module.exports = bool; },{"./can_exit.js":208,"@stdlib/assert/is-browser":78}],208:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var proc = require( './process.js' ); // MAIN // var bool = ( proc && typeof proc.exit === 'function' ); // EXPORTS // module.exports = bool; },{"./process.js":210}],209:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Runs a function on a subsequent turn of the event loop. * * ## Notes * * - `process.nextTick` is only Node.js. * - `setImmediate` is non-standard. * - Everything else is browser based (e.g., mutation observer, requestAnimationFrame, etc). * - Only API which is universal is `setTimeout`. * - Note that `0` is not actually `0ms`. Browser environments commonly have a minimum delay of `4ms`. This is acceptable. Here, the main intent of this function is to give the runtime a chance to run garbage collection, clear state, and tend to any other pending tasks before returning control to benchmark tasks. The larger aim (attainable or not) is to provide each benchmark run with as much of a fresh state as possible. * * * @private * @param {Function} fcn - function to run upon a subsequent turn of the event loop */ function nextTick( fcn ) { setTimeout( fcn, 0 ); } // EXPORTS // module.exports = nextTick; },{}],210:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var proc = require( 'process' ); // EXPORTS // module.exports = proc; },{"process":389}],211:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Benchmark harness. * * @module @stdlib/bench * * @example * var bench = require( '@stdlib/bench' ); * * bench( 'beep', function benchmark( b ) { * var x; * var i; * b.tic(); * for ( i = 0; i < b.iterations; i++ ) { * x = Math.sin( Math.random() ); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * } * b.toc(); * if ( x !== x ) { * b.ok( false, 'should not return NaN' ); * } * b.end(); * }); */ // MODULES // var bench = require( '@stdlib/bench/harness' ); // EXPORTS // module.exports = bench; },{"@stdlib/bench/harness":195}],212:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{"buffer":379}],213:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Buffer constructor. * * @module @stdlib/buffer/ctor * * @example * var ctor = require( '@stdlib/buffer/ctor' ); * * var b = new ctor( [ 1, 2, 3, 4 ] ); * // returns <Buffer> */ // MODULES // var hasNodeBufferSupport = require( '@stdlib/assert/has-node-buffer-support' ); var main = require( './buffer.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var ctor; if ( hasNodeBufferSupport() ) { ctor = main; } else { ctor = polyfill; } // EXPORTS // module.exports = ctor; },{"./buffer.js":212,"./polyfill.js":214,"@stdlib/assert/has-node-buffer-support":44}],214:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: write (browser) polyfill // MAIN // /** * Buffer constructor. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],215:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // var bool = isFunction( Buffer.from ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-function":93,"@stdlib/buffer/ctor":213}],216:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Copy buffer data to a new `Buffer` instance. * * @module @stdlib/buffer/from-buffer * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * var copyBuffer = require( '@stdlib/buffer/from-buffer' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = copyBuffer( b1 ); * // returns <Buffer> */ // MODULES // var hasFrom = require( './has_from.js' ); var main = require( './main.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var copyBuffer; if ( hasFrom ) { copyBuffer = main; } else { copyBuffer = polyfill; } // EXPORTS // module.exports = copyBuffer; },{"./has_from.js":215,"./main.js":217,"./polyfill.js":218}],217:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // /** * Copies buffer data to a new `Buffer` instance. * * @param {Buffer} buffer - buffer from which to copy * @throws {TypeError} must provide a `Buffer` instance * @returns {Buffer} new `Buffer` instance * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = fromBuffer( b1 ); * // returns <Buffer> */ function fromBuffer( buffer ) { if ( !isBuffer( buffer ) ) { throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' ); } return Buffer.from( buffer ); } // EXPORTS // module.exports = fromBuffer; },{"@stdlib/assert/is-buffer":79,"@stdlib/buffer/ctor":213}],218:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isBuffer = require( '@stdlib/assert/is-buffer' ); var Buffer = require( '@stdlib/buffer/ctor' ); // MAIN // /** * Copies buffer data to a new `Buffer` instance. * * @param {Buffer} buffer - buffer from which to copy * @throws {TypeError} must provide a `Buffer` instance * @returns {Buffer} new `Buffer` instance * * @example * var fromArray = require( '@stdlib/buffer/from-array' ); * * var b1 = fromArray( [ 1, 2, 3, 4 ] ); * // returns <Buffer> * * var b2 = fromBuffer( b1 ); * // returns <Buffer> */ function fromBuffer( buffer ) { if ( !isBuffer( buffer ) ) { throw new TypeError( 'invalid argument. Must provide a Buffer. Value: `' + buffer + '`' ); } return new Buffer( buffer ); // eslint-disable-line no-buffer-constructor } // EXPORTS // module.exports = fromBuffer; },{"@stdlib/assert/is-buffer":79,"@stdlib/buffer/ctor":213}],219:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum length of a generic array. * * @module @stdlib/constants/array/max-array-length * * @example * var MAX_ARRAY_LENGTH = require( '@stdlib/constants/array/max-array-length' ); * // returns 4294967295 */ // MAIN // /** * Maximum length of a generic array. * * ```tex * 2^{32} - 1 * ``` * * @constant * @type {uinteger32} * @default 4294967295 */ var MAX_ARRAY_LENGTH = 4294967295>>>0; // asm type annotation // EXPORTS // module.exports = MAX_ARRAY_LENGTH; },{}],220:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum length of a typed array. * * @module @stdlib/constants/array/max-typed-array-length * * @example * var MAX_TYPED_ARRAY_LENGTH = require( '@stdlib/constants/array/max-typed-array-length' ); * // returns 9007199254740991 */ // MAIN // /** * Maximum length of a typed array. * * ```tex * 2^{53} - 1 * ``` * * @constant * @type {number} * @default 9007199254740991 */ var MAX_TYPED_ARRAY_LENGTH = 9007199254740991; // EXPORTS // module.exports = MAX_TYPED_ARRAY_LENGTH; },{}],221:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * The bias of a double-precision floating-point number's exponent. * * @module @stdlib/constants/float64/exponent-bias * @type {integer32} * * @example * var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' ); * // returns 1023 */ // MAIN // /** * Bias of a double-precision floating-point number's exponent. * * ## Notes * * The bias can be computed via * * ```tex * \mathrm{bias} = 2^{k-1} - 1 * ``` * * where \\(k\\) is the number of bits in the exponent; here, \\(k = 11\\). * * @constant * @type {integer32} * @default 1023 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_EXPONENT_BIAS = 1023|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_EXPONENT_BIAS; },{}],222:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * High word mask for the exponent of a double-precision floating-point number. * * @module @stdlib/constants/float64/high-word-exponent-mask * @type {uinteger32} * * @example * var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); * // returns 2146435072 */ // MAIN // /** * High word mask for the exponent of a double-precision floating-point number. * * ## Notes * * The high word mask for the exponent of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 2146435072 \\), which corresponds to the bit sequence * * ```binarystring * 0 11111111111 00000000000000000000 * ``` * * @constant * @type {uinteger32} * @default 0x7ff00000 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_HIGH_WORD_EXPONENT_MASK = 0x7ff00000; // EXPORTS // module.exports = FLOAT64_HIGH_WORD_EXPONENT_MASK; },{}],223:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * High word mask for the significand of a double-precision floating-point number. * * @module @stdlib/constants/float64/high-word-significand-mask * @type {uinteger32} * * @example * var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); * // returns 1048575 */ // MAIN // /** * High word mask for the significand of a double-precision floating-point number. * * ## Notes * * The high word mask for the significand of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 1048575 \\), which corresponds to the bit sequence * * ```binarystring * 0 00000000000 11111111111111111111 * ``` * * @constant * @type {uinteger32} * @default 0x000fffff * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = 0x000fffff; // EXPORTS // module.exports = FLOAT64_HIGH_WORD_SIGNIFICAND_MASK; },{}],224:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Double-precision floating-point negative infinity. * * @module @stdlib/constants/float64/ninf * @type {number} * * @example * var FLOAT64_NINF = require( '@stdlib/constants/float64/ninf' ); * // returns -Infinity */ // MODULES // var Number = require( '@stdlib/number/ctor' ); // MAIN // /** * Double-precision floating-point negative infinity. * * ## Notes * * Double-precision floating-point negative infinity has the bit sequence * * ```binarystring * 1 11111111111 00000000000000000000 00000000000000000000000000000000 * ``` * * @constant * @type {number} * @default Number.NEGATIVE_INFINITY * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_NINF = Number.NEGATIVE_INFINITY; // EXPORTS // module.exports = FLOAT64_NINF; },{"@stdlib/number/ctor":248}],225:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Double-precision floating-point positive infinity. * * @module @stdlib/constants/float64/pinf * @type {number} * * @example * var FLOAT64_PINF = require( '@stdlib/constants/float64/pinf' ); * // returns Infinity */ // MAIN // /** * Double-precision floating-point positive infinity. * * ## Notes * * Double-precision floating-point positive infinity has the bit sequence * * ```binarystring * 0 11111111111 00000000000000000000 00000000000000000000000000000000 * ``` * * @constant * @type {number} * @default Number.POSITIVE_INFINITY * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_PINF = Number.POSITIVE_INFINITY; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = FLOAT64_PINF; },{}],226:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum signed 16-bit integer. * * @module @stdlib/constants/int16/max * @type {integer32} * * @example * var INT16_MAX = require( '@stdlib/constants/int16/max' ); * // returns 32767 */ // MAIN // /** * Maximum signed 16-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{15} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 0111111111111111 * ``` * * @constant * @type {integer32} * @default 32767 */ var INT16_MAX = 32767|0; // asm type annotation // EXPORTS // module.exports = INT16_MAX; },{}],227:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Minimum signed 16-bit integer. * * @module @stdlib/constants/int16/min * @type {integer32} * * @example * var INT16_MIN = require( '@stdlib/constants/int16/min' ); * // returns -32768 */ // MAIN // /** * Minimum signed 16-bit integer. * * ## Notes * * The number has the value * * ```tex * -(2^{15}) * ``` * * which corresponds to the two's complement bit sequence * * ```binarystring * 1000000000000000 * ``` * * @constant * @type {integer32} * @default -32768 */ var INT16_MIN = -32768|0; // asm type annotation // EXPORTS // module.exports = INT16_MIN; },{}],228:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum signed 32-bit integer. * * @module @stdlib/constants/int32/max * @type {integer32} * * @example * var INT32_MAX = require( '@stdlib/constants/int32/max' ); * // returns 2147483647 */ // MAIN // /** * Maximum signed 32-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{31} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 01111111111111111111111111111111 * ``` * * @constant * @type {integer32} * @default 2147483647 */ var INT32_MAX = 2147483647|0; // asm type annotation // EXPORTS // module.exports = INT32_MAX; },{}],229:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Minimum signed 32-bit integer. * * @module @stdlib/constants/int32/min * @type {integer32} * * @example * var INT32_MIN = require( '@stdlib/constants/int32/min' ); * // returns -2147483648 */ // MAIN // /** * Minimum signed 32-bit integer. * * ## Notes * * The number has the value * * ```tex * -(2^{31}) * ``` * * which corresponds to the two's complement bit sequence * * ```binarystring * 10000000000000000000000000000000 * ``` * * @constant * @type {integer32} * @default -2147483648 */ var INT32_MIN = -2147483648|0; // asm type annotation // EXPORTS // module.exports = INT32_MIN; },{}],230:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum signed 8-bit integer. * * @module @stdlib/constants/int8/max * @type {integer32} * * @example * var INT8_MAX = require( '@stdlib/constants/int8/max' ); * // returns 127 */ // MAIN // /** * Maximum signed 8-bit integer. * * ## Notes * * The number is given by * * ```tex * 2^{7} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 01111111 * ``` * * @constant * @type {integer32} * @default 127 */ var INT8_MAX = 127|0; // asm type annotation // EXPORTS // module.exports = INT8_MAX; },{}],231:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Minimum signed 8-bit integer. * * @module @stdlib/constants/int8/min * @type {integer32} * * @example * var INT8_MIN = require( '@stdlib/constants/int8/min' ); * // returns -128 */ // MAIN // /** * Minimum signed 8-bit integer. * * ## Notes * * The number is given by * * ```tex * -(2^{7}) * ``` * * which corresponds to the two's complement bit sequence * * ```binarystring * 10000000 * ``` * * @constant * @type {integer32} * @default -128 */ var INT8_MIN = -128|0; // asm type annotation // EXPORTS // module.exports = INT8_MIN; },{}],232:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum unsigned 16-bit integer. * * @module @stdlib/constants/uint16/max * @type {integer32} * * @example * var UINT16_MAX = require( '@stdlib/constants/uint16/max' ); * // returns 65535 */ // MAIN // /** * Maximum unsigned 16-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{16} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 1111111111111111 * ``` * * @constant * @type {integer32} * @default 65535 */ var UINT16_MAX = 65535|0; // asm type annotation // EXPORTS // module.exports = UINT16_MAX; },{}],233:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum unsigned 32-bit integer. * * @module @stdlib/constants/uint32/max * @type {uinteger32} * * @example * var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); * // returns 4294967295 */ // MAIN // /** * Maximum unsigned 32-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{32} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 11111111111111111111111111111111 * ``` * * @constant * @type {uinteger32} * @default 4294967295 */ var UINT32_MAX = 4294967295; // EXPORTS // module.exports = UINT32_MAX; },{}],234:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum unsigned 8-bit integer. * * @module @stdlib/constants/uint8/max * @type {integer32} * * @example * var UINT8_MAX = require( '@stdlib/constants/uint8/max' ); * // returns 255 */ // MAIN // /** * Maximum unsigned 8-bit integer. * * ## Notes * * The number has the value * * ```tex * 2^{8} - 1 * ``` * * which corresponds to the bit sequence * * ```binarystring * 11111111 * ``` * * @constant * @type {integer32} * @default 255 */ var UINT8_MAX = 255|0; // asm type annotation // EXPORTS // module.exports = UINT8_MAX; },{}],235:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum Unicode code point in the Basic Multilingual Plane (BMP). * * @module @stdlib/constants/unicode/max-bmp * @type {integer32} * * @example * var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' ); * // returns 65535 */ // MAIN // /** * Maximum Unicode code point in the Basic Multilingual Plane (BMP). * * @constant * @type {integer32} * @default 65535 * @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode} */ var UNICODE_MAX_BMP = 0xFFFF|0; // asm type annotation // EXPORTS // module.exports = UNICODE_MAX_BMP; },{}],236:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Maximum Unicode code point. * * @module @stdlib/constants/unicode/max * @type {integer32} * * @example * var UNICODE_MAX = require( '@stdlib/constants/unicode/max' ); * // returns 1114111 */ // MAIN // /** * Maximum Unicode code point. * * @constant * @type {integer32} * @default 1114111 * @see [Unicode]{@link https://en.wikipedia.org/wiki/Unicode} */ var UNICODE_MAX = 0x10FFFF|0; // asm type annotation // EXPORTS // module.exports = UNICODE_MAX; },{}],237:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a finite double-precision floating-point number is an integer. * * @module @stdlib/math/base/assert/is-integer * * @example * var isInteger = require( '@stdlib/math/base/assert/is-integer' ); * * var bool = isInteger( 1.0 ); * // returns true * * bool = isInteger( 3.14 ); * // returns false */ // MODULES // var isInteger = require( './is_integer.js' ); // EXPORTS // module.exports = isInteger; },{"./is_integer.js":238}],238:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var floor = require( '@stdlib/math/base/special/floor' ); // MAIN // /** * Tests if a finite double-precision floating-point number is an integer. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is an integer * * @example * var bool = isInteger( 1.0 ); * // returns true * * @example * var bool = isInteger( 3.14 ); * // returns false */ function isInteger( x ) { return (floor(x) === x); } // EXPORTS // module.exports = isInteger; },{"@stdlib/math/base/special/floor":241}],239:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test if a double-precision floating-point numeric value is `NaN`. * * @module @stdlib/math/base/assert/is-nan * * @example * var isnan = require( '@stdlib/math/base/assert/is-nan' ); * * var bool = isnan( NaN ); * // returns true * * bool = isnan( 7.0 ); * // returns false */ // MODULES // var isnan = require( './main.js' ); // EXPORTS // module.exports = isnan; },{"./main.js":240}],240:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Tests if a double-precision floating-point numeric value is `NaN`. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is `NaN` * * @example * var bool = isnan( NaN ); * // returns true * * @example * var bool = isnan( 7.0 ); * // returns false */ function isnan( x ) { return ( x !== x ); } // EXPORTS // module.exports = isnan; },{}],241:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Round a double-precision floating-point number toward negative infinity. * * @module @stdlib/math/base/special/floor * * @example * var floor = require( '@stdlib/math/base/special/floor' ); * * var v = floor( -4.2 ); * // returns -5.0 * * v = floor( 9.99999 ); * // returns 9.0 * * v = floor( 0.0 ); * // returns 0.0 * * v = floor( NaN ); * // returns NaN */ // MODULES // var floor = require( './main.js' ); // EXPORTS // module.exports = floor; },{"./main.js":242}],242:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: implementation (?) /** * Rounds a double-precision floating-point number toward negative infinity. * * @param {number} x - input value * @returns {number} rounded value * * @example * var v = floor( -4.2 ); * // returns -5.0 * * @example * var v = floor( 9.99999 ); * // returns 9.0 * * @example * var v = floor( 0.0 ); * // returns 0.0 * * @example * var v = floor( NaN ); * // returns NaN */ var floor = Math.floor; // eslint-disable-line stdlib/no-builtin-math // EXPORTS // module.exports = floor; },{}],243:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Decompose a double-precision floating-point number into integral and fractional parts. * * @module @stdlib/math/base/special/modf * * @example * var modf = require( '@stdlib/math/base/special/modf' ); * * var parts = modf( 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var modf = require( '@stdlib/math/base/special/modf' ); * * var out = new Float64Array( 2 ); * * var parts = modf( out, 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] * * var bool = ( parts === out ); * // returns true */ // MODULES // var modf = require( './main.js' ); // EXPORTS // module.exports = modf; },{"./main.js":244}],244:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var fcn = require( './modf.js' ); // MAIN // /** * Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value. * * @param {(Array|TypedArray|Object)} [out] - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var parts = modf( 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var out = new Float64Array( 2 ); * * var parts = modf( out, 3.14 ); * // returns <Float64Array>[ 3.0, 0.14000000000000012 ] * * var bool = ( parts === out ); * // returns true */ function modf( out, x ) { if ( arguments.length === 1 ) { return fcn( [ 0.0, 0.0 ], out ); } return fcn( out, x ); } // EXPORTS // module.exports = modf; },{"./modf.js":245}],245:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isnan = require( '@stdlib/math/base/assert/is-nan' ); var toWords = require( '@stdlib/number/float64/base/to-words' ); var fromWords = require( '@stdlib/number/float64/base/from-words' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var FLOAT64_EXPONENT_BIAS = require( '@stdlib/constants/float64/exponent-bias' ); var FLOAT64_HIGH_WORD_EXPONENT_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); // eslint-disable-line id-length var FLOAT64_HIGH_WORD_SIGNIFICAND_MASK = require( '@stdlib/constants/float64/high-word-significand-mask' ); // eslint-disable-line id-length // VARIABLES // // 4294967295 => 0xffffffff => 11111111111111111111111111111111 var ALL_ONES = 4294967295>>>0; // asm type annotation // High/low words workspace: var WORDS = [ 0|0, 0|0 ]; // WARNING: not thread safe // MAIN // /** * Decomposes a double-precision floating-point number into integral and fractional parts, each having the same type and sign as the input value. * * @private * @param {(Array|TypedArray|Object)} out - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var parts = modf( [ 0.0, 0.0 ], 3.14 ); * // returns [ 3.0, 0.14000000000000012 ] */ function modf( out, x ) { var high; var low; var exp; var i; // Special cases... if ( x < 1.0 ) { if ( x < 0.0 ) { modf( out, -x ); out[ 0 ] *= -1.0; out[ 1 ] *= -1.0; return out; } if ( x === 0.0 ) { // [ +-0, +-0 ] out[ 0 ] = x; out[ 1 ] = x; return out; } out[ 0 ] = 0.0; out[ 1 ] = x; return out; } if ( isnan( x ) ) { out[ 0 ] = NaN; out[ 1 ] = NaN; return out; } if ( x === PINF ) { out[ 0 ] = PINF; out[ 1 ] = 0.0; return out; } // Decompose |x|... // Extract the high and low words: toWords( WORDS, x ); high = WORDS[ 0 ]; low = WORDS[ 1 ]; // Extract the unbiased exponent from the high word: exp = ((high & FLOAT64_HIGH_WORD_EXPONENT_MASK) >> 20)|0; // asm type annotation exp -= FLOAT64_EXPONENT_BIAS|0; // asm type annotation // Handle smaller values (x < 2**20 = 1048576)... if ( exp < 20 ) { i = (FLOAT64_HIGH_WORD_SIGNIFICAND_MASK >> exp)|0; // asm type annotation // Determine if `x` is integral by checking for significand bits which cannot be exponentiated away... if ( ((high&i)|low) === 0 ) { out[ 0 ] = x; out[ 1 ] = 0.0; return out; } // Turn off all the bits which cannot be exponentiated away: high &= (~i); // Generate the integral part: i = fromWords( high, 0 ); // The fractional part is whatever is leftover: out[ 0 ] = i; out[ 1 ] = x - i; return out; } // Check if `x` can even have a fractional part... if ( exp > 51 ) { // `x` is integral: out[ 0 ] = x; out[ 1 ] = 0.0; return out; } i = ALL_ONES >>> (exp-20); // Determine if `x` is integral by checking for less significant significand bits which cannot be exponentiated away... if ( (low&i) === 0 ) { out[ 0 ] = x; out[ 1 ] = 0.0; return out; } // Turn off all the bits which cannot be exponentiated away: low &= (~i); // Generate the integral part: i = fromWords( high, low ); // The fractional part is whatever is leftover: out[ 0 ] = i; out[ 1 ] = x - i; return out; } // EXPORTS // module.exports = modf; },{"@stdlib/constants/float64/exponent-bias":221,"@stdlib/constants/float64/high-word-exponent-mask":222,"@stdlib/constants/float64/high-word-significand-mask":223,"@stdlib/constants/float64/pinf":225,"@stdlib/math/base/assert/is-nan":239,"@stdlib/number/float64/base/from-words":250,"@stdlib/number/float64/base/to-words":253}],246:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: implementation /** * Round a numeric value to the nearest integer. * * @module @stdlib/math/base/special/round * * @example * var round = require( '@stdlib/math/base/special/round' ); * * var v = round( -4.2 ); * // returns -4.0 * * v = round( -4.5 ); * // returns -4.0 * * v = round( -4.6 ); * // returns -5.0 * * v = round( 9.99999 ); * // returns 10.0 * * v = round( 9.5 ); * // returns 10.0 * * v = round( 9.2 ); * // returns 9.0 * * v = round( 0.0 ); * // returns 0.0 * * v = round( -0.0 ); * // returns -0.0 * * v = round( Infinity ); * // returns Infinity * * v = round( -Infinity ); * // returns -Infinity * * v = round( NaN ); * // returns NaN */ // MODULES // var round = require( './round.js' ); // EXPORTS // module.exports = round; },{"./round.js":247}],247:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // TODO: implementation /** * Rounds a numeric value to the nearest integer. * * @param {number} x - input value * @returns {number} function value * * @example * var v = round( -4.2 ); * // returns -4.0 * * @example * var v = round( -4.5 ); * // returns -4.0 * * @example * var v = round( -4.6 ); * // returns -5.0 * * @example * var v = round( 9.99999 ); * // returns 10.0 * * @example * var v = round( 9.5 ); * // returns 10.0 * * @example * var v = round( 9.2 ); * // returns 9.0 * * @example * var v = round( 0.0 ); * // returns 0.0 * * @example * var v = round( -0.0 ); * // returns -0.0 * * @example * var v = round( Infinity ); * // returns Infinity * * @example * var v = round( -Infinity ); * // returns -Infinity * * @example * var v = round( NaN ); * // returns NaN */ var round = Math.round; // eslint-disable-line stdlib/no-builtin-math // EXPORTS // module.exports = round; },{}],248:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Constructor which returns a `Number` object. * * @module @stdlib/number/ctor * * @example * var Number = require( '@stdlib/number/ctor' ); * * var v = new Number( 10.0 ); * // returns <Number> */ // MODULES // var Number = require( './number.js' ); // EXPORTS // module.exports = Number; },{"./number.js":249}],249:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // EXPORTS // module.exports = Number; // eslint-disable-line stdlib/require-globals },{}],250:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Create a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * @module @stdlib/number/float64/base/from-words * * @example * var fromWords = require( '@stdlib/number/float64/base/from-words' ); * * var v = fromWords( 1774486211, 2479577218 ); * // returns 3.14e201 * * v = fromWords( 3221823995, 1413754136 ); * // returns -3.141592653589793 * * v = fromWords( 0, 0 ); * // returns 0.0 * * v = fromWords( 2147483648, 0 ); * // returns -0.0 * * v = fromWords( 2146959360, 0 ); * // returns NaN * * v = fromWords( 2146435072, 0 ); * // returns Infinity * * v = fromWords( 4293918720, 0 ); * // returns -Infinity */ // MODULES // var fromWords = require( './main.js' ); // EXPORTS // module.exports = fromWords; },{"./main.js":252}],251:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isLittleEndian = require( '@stdlib/assert/is-little-endian' ); // MAIN // var indices; var HIGH; var LOW; if ( isLittleEndian === true ) { HIGH = 1; // second index LOW = 0; // first index } else { HIGH = 0; // first index LOW = 1; // second index } indices = { 'HIGH': HIGH, 'LOW': LOW }; // EXPORTS // module.exports = indices; },{"@stdlib/assert/is-little-endian":107}],252:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var Uint32Array = require( '@stdlib/array/uint32' ); var Float64Array = require( '@stdlib/array/float64' ); var indices = require( './indices.js' ); // VARIABLES // var FLOAT64_VIEW = new Float64Array( 1 ); var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer ); var HIGH = indices.HIGH; var LOW = indices.LOW; // MAIN // /** * Creates a double-precision floating-point number from a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * ## Notes * * ```text * float64 (64 bits) * f := fraction (significand/mantissa) (52 bits) * e := exponent (11 bits) * s := sign bit (1 bit) * * |-------- -------- -------- -------- -------- -------- -------- --------| * | Float64 | * |-------- -------- -------- -------- -------- -------- -------- --------| * | Uint32 | Uint32 | * |-------- -------- -------- -------- -------- -------- -------- --------| * ``` * * If little endian (more significant bits last): * * ```text * <-- lower higher --> * | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 | * ``` * * If big endian (more significant bits first): * * ```text * <-- higher lower --> * |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 | * ``` * * * In which Uint32 should we place the higher order bits? If little endian, the second; if big endian, the first. * * * ## References * * - [Open Group][1] * * [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm * * @param {uinteger32} high - higher order word (unsigned 32-bit integer) * @param {uinteger32} low - lower order word (unsigned 32-bit integer) * @returns {number} floating-point number * * @example * var v = fromWords( 1774486211, 2479577218 ); * // returns 3.14e201 * * @example * var v = fromWords( 3221823995, 1413754136 ); * // returns -3.141592653589793 * * @example * var v = fromWords( 0, 0 ); * // returns 0.0 * * @example * var v = fromWords( 2147483648, 0 ); * // returns -0.0 * * @example * var v = fromWords( 2146959360, 0 ); * // returns NaN * * @example * var v = fromWords( 2146435072, 0 ); * // returns Infinity * * @example * var v = fromWords( 4293918720, 0 ); * // returns -Infinity */ function fromWords( high, low ) { UINT32_VIEW[ HIGH ] = high; UINT32_VIEW[ LOW ] = low; return FLOAT64_VIEW[ 0 ]; } // EXPORTS // module.exports = fromWords; },{"./indices.js":251,"@stdlib/array/float64":5,"@stdlib/array/uint32":19}],253:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Split a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * @module @stdlib/number/float64/base/to-words * * @example * var toWords = require( '@stdlib/number/float64/base/to-words' ); * * var w = toWords( 3.14e201 ); * // returns [ 1774486211, 2479577218 ] * * @example * var Uint32Array = require( '@stdlib/array/uint32' ); * var toWords = require( '@stdlib/number/float64/base/to-words' ); * * var out = new Uint32Array( 2 ); * * var w = toWords( out, 3.14e201 ); * // returns <Uint32Array>[ 1774486211, 2479577218 ] * * var bool = ( w === out ); * // returns true */ // MODULES // var toWords = require( './main.js' ); // EXPORTS // module.exports = toWords; },{"./main.js":255}],254:[function(require,module,exports){ arguments[4][251][0].apply(exports,arguments) },{"@stdlib/assert/is-little-endian":107,"dup":251}],255:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var fcn = require( './to_words.js' ); // MAIN // /** * Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * @param {(Array|TypedArray|Object)} [out] - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var w = toWords( 3.14e201 ); * // returns [ 1774486211, 2479577218 ] * * @example * var Uint32Array = require( '@stdlib/array/uint32' ); * * var out = new Uint32Array( 2 ); * * var w = toWords( out, 3.14e201 ); * // returns <Uint32Array>[ 1774486211, 2479577218 ] * * var bool = ( w === out ); * // returns true */ function toWords( out, x ) { if ( arguments.length === 1 ) { return fcn( [ 0, 0 ], out ); } return fcn( out, x ); } // EXPORTS // module.exports = toWords; },{"./to_words.js":256}],256:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var Uint32Array = require( '@stdlib/array/uint32' ); var Float64Array = require( '@stdlib/array/float64' ); var indices = require( './indices.js' ); // VARIABLES // var FLOAT64_VIEW = new Float64Array( 1 ); var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer ); var HIGH = indices.HIGH; var LOW = indices.LOW; // MAIN // /** * Splits a double-precision floating-point number into a higher order word (unsigned 32-bit integer) and a lower order word (unsigned 32-bit integer). * * ## Notes * * ```text * float64 (64 bits) * f := fraction (significand/mantissa) (52 bits) * e := exponent (11 bits) * s := sign bit (1 bit) * * |-------- -------- -------- -------- -------- -------- -------- --------| * | Float64 | * |-------- -------- -------- -------- -------- -------- -------- --------| * | Uint32 | Uint32 | * |-------- -------- -------- -------- -------- -------- -------- --------| * ``` * * If little endian (more significant bits last): * * ```text * <-- lower higher --> * | f7 f6 f5 f4 f3 f2 e2 | f1 |s| e1 | * ``` * * If big endian (more significant bits first): * * ```text * <-- higher lower --> * |s| e1 e2 | f1 f2 f3 f4 f5 f6 f7 | * ``` * * In which Uint32 can we find the higher order bits? If little endian, the second; if big endian, the first. * * * ## References * * - [Open Group][1] * * [1]: http://pubs.opengroup.org/onlinepubs/9629399/chap14.htm * * * @private * @param {(Array|TypedArray|Object)} out - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var Uint32Array = require( '@stdlib/array/uint32' ); * * var out = new Uint32Array( 2 ); * * var w = toWords( out, 3.14e201 ); * // returns <Uint32Array>[ 1774486211, 2479577218 ] * * var bool = ( w === out ); * // returns true */ function toWords( out, x ) { FLOAT64_VIEW[ 0 ] = x; out[ 0 ] = UINT32_VIEW[ HIGH ]; out[ 1 ] = UINT32_VIEW[ LOW ]; return out; } // EXPORTS // module.exports = toWords; },{"./indices.js":254,"@stdlib/array/float64":5,"@stdlib/array/uint32":19}],257:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Regular expression to match a newline character sequence. * * @module @stdlib/regexp/eol * * @example * var reEOL = require( '@stdlib/regexp/eol' ); * var RE_EOL = reEOL(); * * var bool = RE_EOL.test( '\n' ); * // returns true * * bool = RE_EOL.test( '\\r\\n' ); * // returns false * * @example * var reEOL = require( '@stdlib/regexp/eol' ); * var replace = require( '@stdlib/string/replace' ); * * var RE_EOL = reEOL({ * 'flags': 'g' * }); * var str = '1\n2\n3'; * var out = replace( str, RE_EOL, '' ); * * @example * var reEOL = require( '@stdlib/regexp/eol' ); * var bool = reEOL.REGEXP.test( '\r\n' ); * // returns true */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var reEOL = require( './main.js' ); var REGEXP_CAPTURE = require( './regexp_capture.js' ); var REGEXP = require( './regexp.js' ); // MAIN // setReadOnly( reEOL, 'REGEXP', REGEXP ); setReadOnly( reEOL, 'REGEXP_CAPTURE', REGEXP_CAPTURE ); // EXPORTS // module.exports = reEOL; },{"./main.js":258,"./regexp.js":259,"./regexp_capture.js":260,"@stdlib/utils/define-nonenumerable-read-only-property":297}],258:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MODULES // var validate = require( './validate.js' ); // VARIABLES // var REGEXP_STRING = '\\r?\\n'; // MAIN // /** * Returns a regular expression to match a newline character sequence. * * @param {Options} [options] - function options * @param {string} [options.flags=''] - regular expression flags * @param {boolean} [options.capture=false] - boolean indicating whether to create a capture group for the match * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {RegExp} regular expression * * @example * var RE_EOL = reEOL(); * var bool = RE_EOL.test( '\r\n' ); * // returns true * * @example * var replace = require( '@stdlib/string/replace' ); * * var RE_EOL = reEOL({ * 'flags': 'g' * }); * var str = '1\n2\n3'; * var out = replace( str, RE_EOL, '' ); */ function reEOL( options ) { var opts; var err; if ( arguments.length > 0 ) { opts = {}; err = validate( opts, options ); if ( err ) { throw err; } if ( opts.capture ) { return new RegExp( '('+REGEXP_STRING+')', opts.flags ); } return new RegExp( REGEXP_STRING, opts.flags ); } return /\r?\n/; } // EXPORTS // module.exports = reEOL; },{"./validate.js":261}],259:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MODULES // var reEOL = require( './main.js' ); // MAIN // /** * Matches a newline character sequence. * * Regular expression: `/\r?\n/` * * - `\r?` * - match a carriage return character (optional) * * - `\n` * - match a line feed character * * @constant * @type {RegExp} * @default /\r?\n/ */ var REGEXP = reEOL(); // EXPORTS // module.exports = REGEXP; },{"./main.js":258}],260:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MODULES // var reEOL = require( './main.js' ); // MAIN // /** * Captures a newline character sequence. * * Regular expression: `/\r?\n/` * * - `()` * - capture * * - `\r?` * - match a carriage return character (optional) * * - `\n` * - match a line feed character * * @constant * @type {RegExp} * @default /(\r?\n)/ */ var REGEXP_CAPTURE = reEOL({ 'capture': true }); // EXPORTS // module.exports = REGEXP_CAPTURE; },{"./main.js":258}],261:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {string} [options.flags] - regular expression flags * @param {boolean} [options.capture] - boolean indicating whether to wrap a regular expression matching a decimal number with a capture group * @returns {(Error|null)} null or an error object * * @example * var opts = {}; * var options = { * 'flags': 'gm' * }; * var err = validate( opts, options ); * if ( err ) { * throw err; * } */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'flags' ) ) { opts.flags = options.flags; if ( !isString( opts.flags ) ) { return new TypeError( 'invalid option. `flags` option must be a string primitive. Option: `' + opts.flags + '`.' ); } } if ( hasOwnProp( options, 'capture' ) ) { opts.capture = options.capture; if ( !isBoolean( opts.capture ) ) { return new TypeError( 'invalid option. `capture` option must be a boolean primitive. Option: `' + opts.capture + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-string":149}],262:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; /** * Regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis. * * @module @stdlib/regexp/function-name * * @example * var reFunctionName = require( '@stdlib/regexp/function-name' ); * var RE_FUNCTION_NAME = reFunctionName(); * * function fname( fcn ) { * return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ]; * } * * var fn = fname( Math.sqrt ); * // returns 'sqrt' * * fn = fname( Int8Array ); * // returns 'Int8Array' * * fn = fname( Object.prototype.toString ); * // returns 'toString' * * fn = fname( function(){} ); * // returns '' */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var reFunctionName = require( './main.js' ); var REGEXP = require( './regexp.js' ); // MAIN // setReadOnly( reFunctionName, 'REGEXP', REGEXP ); // EXPORTS // module.exports = reFunctionName; },{"./main.js":263,"./regexp.js":264,"@stdlib/utils/define-nonenumerable-read-only-property":297}],263:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MAIN // /** * Returns a regular expression to capture everything that is not a space immediately after the `function` keyword and before the first left parenthesis. * * @returns {RegExp} regular expression * * @example * var RE_FUNCTION_NAME = reFunctionName(); * * function fname( fcn ) { * return RE_FUNCTION_NAME.exec( fcn.toString() )[ 1 ]; * } * * var fn = fname( Math.sqrt ); * // returns 'sqrt' * * fn = fname( Int8Array ); * // returns 'Int8Array' * * fn = fname( Object.prototype.toString ); * // returns 'toString' * * fn = fname( function(){} ); * // returns '' */ function reFunctionName() { return /^\s*function\s*([^(]*)/i; } // EXPORTS // module.exports = reFunctionName; },{}],264:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var reFunctionName = require( './main.js' ); // MAIN // /** * Captures everything that is not a space immediately after the `function` keyword and before the first left parenthesis. * * Regular expression: `/^\s*function\s*([^(]*)/i` * * - `/^\s*` * - Match zero or more spaces at beginning * * - `function` * - Match the word `function` * * - `\s*` * - Match zero or more spaces after the word `function` * * - `()` * - Capture * * - `[^(]*` * - Match anything except a left parenthesis `(` zero or more times * * - `/i` * - ignore case * * @constant * @type {RegExp} * @default /^\s*function\s*([^(]*)/i */ var RE_FUNCTION_NAME = reFunctionName(); // EXPORTS // module.exports = RE_FUNCTION_NAME; },{"./main.js":263}],265:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a regular expression to parse a regular expression string. * * @module @stdlib/regexp/regexp * * @example * var reRegExp = require( '@stdlib/regexp/regexp' ); * * var RE_REGEXP = reRegExp(); * * var bool = RE_REGEXP.test( '/^beep$/' ); * // returns true * * bool = RE_REGEXP.test( '' ); * // returns false * * @example * var reRegExp = require( '@stdlib/regexp/regexp' ); * * var RE_REGEXP = reRegExp(); * * var parts = RE_REGEXP.exec( '/^.*$/ig' ); * // returns [ '/^.*$/ig', '^.*$', 'ig', 'index': 0, 'input': '/^.*$/ig' ] */ // MAIN // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var reRegExp = require( './main.js' ); var REGEXP = require( './regexp.js' ); // MAIN // setReadOnly( reRegExp, 'REGEXP', REGEXP ); // EXPORTS // module.exports = reRegExp; // EXPORTS // module.exports = reRegExp; },{"./main.js":266,"./regexp.js":267,"@stdlib/utils/define-nonenumerable-read-only-property":297}],266:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MAIN // /** * Returns a regular expression to parse a regular expression string. * * @returns {RegExp} regular expression * * @example * var RE_REGEXP = reRegExp(); * * var bool = RE_REGEXP.test( '/^beep$/' ); * // returns true * * bool = RE_REGEXP.test( '' ); * // returns false */ function reRegExp() { return /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/; // eslint-disable-line no-useless-escape } // EXPORTS // module.exports = reRegExp; },{}],267:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var reRegExp = require( './main.js' ); // MAIN // /** * Matches parts of a regular expression string. * * Regular expression: `/^\/((?:\\\/|[^\/])+)\/([imgy]*)$/` * * - `/^\/` * - match a string that begins with a `/` * * - `()` * - capture * * - `(?:)+` * - capture, but do not remember, a group of characters which occur one or more times * * - `\\\/` * - match the literal `\/` * * - `|` * - OR * * - `[^\/]` * - anything which is not the literal `\/` * * - `\/` * - match the literal `/` * * - `([imgy]*)` * - capture any characters matching `imgy` occurring zero or more times * * - `$/` * - string end * * * @constant * @type {RegExp} * @default /^\/((?:\\\/|[^\/])+)\/([imgy]*)$/ */ var RE_REGEXP = reRegExp(); // EXPORTS // module.exports = RE_REGEXP; },{"./main.js":266}],268:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var logger = require( 'debug' ); // VARIABLES // var debug = logger( 'transform-stream:transform' ); // MAIN // /** * Implements the `_transform` method as a pass through. * * @private * @param {(Uint8Array|Buffer|string)} chunk - streamed chunk * @param {string} encoding - Buffer encoding * @param {Callback} clbk - callback to invoke after transforming the streamed chunk */ function transform( chunk, encoding, clbk ) { debug( 'Received a new chunk. Chunk: %s. Encoding: %s.', chunk.toString(), encoding ); clbk( null, chunk ); } // EXPORTS // module.exports = transform; },{"debug":381}],269:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var logger = require( 'debug' ); var Transform = require( 'readable-stream' ).Transform; var inherit = require( '@stdlib/utils/inherit' ); var copy = require( '@stdlib/utils/copy' ); var DEFAULTS = require( './defaults.json' ); var validate = require( './validate.js' ); var destroy = require( './destroy.js' ); var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle // VARIABLES // var debug = logger( 'transform-stream:ctor' ); // MAIN // /** * Transform stream constructor factory. * * @param {Options} [options] - stream options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {Function} Transform stream constructor * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * * var TransformStream = ctor( opts ); * * var stream = new TransformStream(); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * * // prints: '1\n2\n3\n' */ function ctor( options ) { var transform; var copts; var err; copts = copy( DEFAULTS ); if ( arguments.length ) { err = validate( copts, options ); if ( err ) { throw err; } } if ( copts.transform ) { transform = copts.transform; } else { transform = _transform; } /** * Transform stream constructor. * * @private * @constructor * @param {Options} [options] - stream options * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * var stream = new TransformStream(); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * * // prints: '1\n2\n3\n' */ function TransformStream( options ) { var opts; var err; if ( !( this instanceof TransformStream ) ) { if ( arguments.length ) { return new TransformStream( options ); } return new TransformStream(); } opts = copy( copts ); if ( arguments.length ) { err = validate( opts, options ); if ( err ) { throw err; } } debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) ); Transform.call( this, opts ); this._destroyed = false; return this; } /** * Inherit from the `Transform` prototype. */ inherit( TransformStream, Transform ); /** * Implements the `_transform` method. * * @private * @name _transform * @memberof TransformStream.prototype * @type {Function} * @param {(Buffer|string)} chunk - streamed chunk * @param {string} encoding - Buffer encoding * @param {Callback} clbk - callback to invoke after transforming the streamed chunk */ TransformStream.prototype._transform = transform; // eslint-disable-line no-underscore-dangle if ( copts.flush ) { /** * Implements the `_flush` method. * * @private * @name _flush * @memberof TransformStream.prototype * @type {Function} * @param {Callback} callback to invoke after performing flush tasks */ TransformStream.prototype._flush = copts.flush; // eslint-disable-line no-underscore-dangle } /** * Gracefully destroys a stream, providing backward compatibility. * * @private * @name destroy * @memberof TransformStream.prototype * @type {Function} * @param {Object} [error] - optional error message * @returns {TransformStream} stream instance */ TransformStream.prototype.destroy = destroy; return TransformStream; } // EXPORTS // module.exports = ctor; },{"./_transform.js":268,"./defaults.json":270,"./destroy.js":271,"./validate.js":276,"@stdlib/utils/copy":293,"@stdlib/utils/inherit":325,"debug":381,"readable-stream":398}],270:[function(require,module,exports){ module.exports={ "objectMode": false, "encoding": null, "allowHalfOpen": false, "decodeStrings": true } },{}],271:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var logger = require( 'debug' ); var nextTick = require( '@stdlib/utils/next-tick' ); // VARIABLES // var debug = logger( 'transform-stream:destroy' ); // MAIN // /** * Gracefully destroys a stream, providing backward compatibility. * * @private * @param {Object} [error] - optional error message * @returns {Stream} stream instance */ function destroy( error ) { /* eslint-disable no-invalid-this */ var self; if ( this._destroyed ) { debug( 'Attempted to destroy an already destroyed stream.' ); return this; } self = this; this._destroyed = true; nextTick( close ); return this; /** * Closes a stream. * * @private */ function close() { if ( error ) { debug( 'Stream was destroyed due to an error. Error: %s.', JSON.stringify( error ) ); self.emit( 'error', error ); } debug( 'Closing the stream...' ); self.emit( 'close' ); } } // EXPORTS // module.exports = destroy; },{"@stdlib/utils/next-tick":351,"debug":381}],272:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var copy = require( '@stdlib/utils/copy' ); var Stream = require( './main.js' ); // MAIN // /** * Creates a reusable transform stream factory. * * @param {Options} [options] - stream options * @param {boolean} [options.objectMode=false] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @returns {Function} transform stream factory * * @example * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'objectMode': true, * 'encoding': 'utf8', * 'highWaterMark': 64, * 'decodeStrings': false * }; * * var factory = streamFactory( opts ); * * // Create 10 identically configured streams... * var streams = []; * var i; * for ( i = 0; i < 10; i++ ) { * streams.push( factory( transform ) ); * } */ function streamFactory( options ) { var opts; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } opts = copy( options ); } else { opts = {}; } return createStream; /** * Creates a transform stream. * * @private * @param {Function} transform - callback to invoke upon receiving a new chunk * @param {Function} [flush] - callback to invoke after receiving all chunks and prior to the stream closing * @throws {TypeError} must provide valid options * @throws {TypeError} transform callback must be a function * @throws {TypeError} flush callback must be a function * @returns {TransformStream} transform stream */ function createStream( transform, flush ) { opts.transform = transform; if ( arguments.length > 1 ) { opts.flush = flush; } else { delete opts.flush; // clear any previous `flush` } return new Stream( opts ); } } // EXPORTS // module.exports = streamFactory; },{"./main.js":274,"@stdlib/assert/is-plain-object":138,"@stdlib/utils/copy":293}],273:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Transform stream. * * @module @stdlib/streams/node/transform * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * var transformStream = require( '@stdlib/streams/node/transform' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * var stream = transformStream( opts ); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * // => '1\n2\n3\n' * * * @example * var transformStream = require( '@stdlib/streams/node/transform' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'objectMode': true, * 'encoding': 'utf8', * 'highWaterMark': 64, * 'decodeStrings': false * }; * * var factory = transformStream.factory( opts ); * * // Create 10 identically configured streams... * var streams = []; * var i; * for ( i = 0; i < 10; i++ ) { * streams.push( factory( transform ) ); * } * * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * var transformStream = require( '@stdlib/streams/node/transform' ); * * function stringify( chunk, enc, clbk ) { * clbk( null, JSON.stringify( chunk ) ); * } * * function newline( chunk, enc, clbk ) { * clbk( null, chunk+'\n' ); * } * * var s1 = transformStream.objectMode({ * 'transform': stringify * }); * * var s2 = transformStream.objectMode({ * 'transform': newline * }); * * s1.pipe( s2 ).pipe( stdout ); * * s1.write( {'value': 'a'} ); * s1.write( {'value': 'b'} ); * s1.write( {'value': 'c'} ); * * s1.end(); * // => '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n' * * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * var transformStream = require( '@stdlib/streams/node/transform' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * * var Stream = transformStream.ctor( opts ); * * var stream = new Stream(); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * // => '1\n2\n3\n' */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var transform = require( './main.js' ); var objectMode = require( './object_mode.js' ); var factory = require( './factory.js' ); var ctor = require( './ctor.js' ); // MAIN // setReadOnly( transform, 'objectMode', objectMode ); setReadOnly( transform, 'factory', factory ); setReadOnly( transform, 'ctor', ctor ); // EXPORTS // module.exports = transform; },{"./ctor.js":269,"./factory.js":272,"./main.js":274,"./object_mode.js":275,"@stdlib/utils/define-nonenumerable-read-only-property":297}],274:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var logger = require( 'debug' ); var Transform = require( 'readable-stream' ).Transform; var inherit = require( '@stdlib/utils/inherit' ); var copy = require( '@stdlib/utils/copy' ); var DEFAULTS = require( './defaults.json' ); var validate = require( './validate.js' ); var destroy = require( './destroy.js' ); var _transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle // VARIABLES // var debug = logger( 'transform-stream:main' ); // MAIN // /** * Transform stream constructor. * * @constructor * @param {Options} [options] - stream options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {boolean} [options.objectMode=false] - specifies whether stream should operate in object mode * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * function transform( chunk, enc, clbk ) { * clbk( null, chunk.toString()+'\n' ); * } * * var opts = { * 'transform': transform * }; * var stream = new TransformStream( opts ); * * stream.pipe( stdout ); * * stream.write( '1' ); * stream.write( '2' ); * stream.write( '3' ); * * stream.end(); * * // prints: '1\n2\n3\n' */ function TransformStream( options ) { var opts; var err; if ( !( this instanceof TransformStream ) ) { if ( arguments.length ) { return new TransformStream( options ); } return new TransformStream(); } opts = copy( DEFAULTS ); if ( arguments.length ) { err = validate( opts, options ); if ( err ) { throw err; } } debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) ); Transform.call( this, opts ); this._destroyed = false; if ( opts.transform ) { this._transform = opts.transform; } else { this._transform = _transform; } if ( opts.flush ) { this._flush = opts.flush; } return this; } /* * Inherit from the `Transform` prototype. */ inherit( TransformStream, Transform ); /** * Gracefully destroys a stream, providing backward compatibility. * * @name destroy * @memberof TransformStream.prototype * @type {Function} * @param {Object} [error] - optional error message * @returns {TransformStream} stream instance */ TransformStream.prototype.destroy = destroy; // EXPORTS // module.exports = TransformStream; },{"./_transform.js":268,"./defaults.json":270,"./destroy.js":271,"./validate.js":276,"@stdlib/utils/copy":293,"@stdlib/utils/inherit":325,"debug":381,"readable-stream":398}],275:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var copy = require( '@stdlib/utils/copy' ); var Stream = require( './main.js' ); // MAIN // /** * Returns a transform stream with `objectMode` set to `true`. * * @param {Options} [options] - stream options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings=true] - specifies whether to decode `strings` into `Buffer` objects when writing * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {TransformStream} transform stream * * @example * var stdout = require( '@stdlib/streams/node/stdout' ); * * function stringify( chunk, enc, clbk ) { * clbk( null, JSON.stringify( chunk ) ); * } * * function newline( chunk, enc, clbk ) { * clbk( null, chunk+'\n' ); * } * * var s1 = objectMode({ * 'transform': stringify * }); * * var s2 = objectMode({ * 'transform': newline * }); * * s1.pipe( s2 ).pipe( stdout ); * * s1.write( {'value': 'a'} ); * s1.write( {'value': 'b'} ); * s1.write( {'value': 'c'} ); * * s1.end(); * * // prints: '{"value":"a"}\n{"value":"b"}\n{"value":"c"}\n' */ function objectMode( options ) { var opts; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } opts = copy( options ); } else { opts = {}; } opts.objectMode = true; return new Stream( opts ); } // EXPORTS // module.exports = objectMode; },{"./main.js":274,"@stdlib/assert/is-plain-object":138,"@stdlib/utils/copy":293}],276:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isFunction = require( '@stdlib/assert/is-function' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isNonNegative = require( '@stdlib/assert/is-nonnegative-number' ).isPrimitive; var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // MAIN // /** * Validates function options. * * @private * @param {Object} opts - destination object * @param {Options} options - function options * @param {Function} [options.transform] - callback to invoke upon receiving a new chunk * @param {Function} [options.flush] - callback to invoke after receiving all chunks and prior to the stream closing * @param {boolean} [options.objectMode] - specifies whether a stream should operate in object mode * @param {(string|null)} [options.encoding] - specifies how `Buffer` objects should be decoded to `strings` * @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false` * @param {boolean} [options.allowHalfOpen] - specifies whether the stream should remain open even if one side ends * @param {boolean} [options.decodeStrings] - specifies whether to decode `strings` into `Buffer` objects when writing * @returns {(Error|null)} null or an error object */ function validate( opts, options ) { if ( !isObject( options ) ) { return new TypeError( 'invalid argument. Options must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'transform' ) ) { opts.transform = options.transform; if ( !isFunction( opts.transform ) ) { return new TypeError( 'invalid option. `transform` option must be a function. Option: `' + opts.transform + '`.' ); } } if ( hasOwnProp( options, 'flush' ) ) { opts.flush = options.flush; if ( !isFunction( opts.flush ) ) { return new TypeError( 'invalid option. `flush` option must be a function. Option: `' + opts.flush + '`.' ); } } if ( hasOwnProp( options, 'objectMode' ) ) { opts.objectMode = options.objectMode; if ( !isBoolean( opts.objectMode ) ) { return new TypeError( 'invalid option. `objectMode` option must be a primitive boolean. Option: `' + opts.objectMode + '`.' ); } } if ( hasOwnProp( options, 'encoding' ) ) { opts.encoding = options.encoding; if ( !isString( opts.encoding ) ) { return new TypeError( 'invalid option. `encoding` option must be a primitive string. Option: `' + opts.encoding + '`.' ); } } if ( hasOwnProp( options, 'allowHalfOpen' ) ) { opts.allowHalfOpen = options.allowHalfOpen; if ( !isBoolean( opts.allowHalfOpen ) ) { return new TypeError( 'invalid option. `allowHalfOpen` option must be a primitive boolean. Option: `' + opts.allowHalfOpen + '`.' ); } } if ( hasOwnProp( options, 'highWaterMark' ) ) { opts.highWaterMark = options.highWaterMark; if ( !isNonNegative( opts.highWaterMark ) ) { return new TypeError( 'invalid option. `highWaterMark` option must be a nonnegative number. Option: `' + opts.highWaterMark + '`.' ); } } if ( hasOwnProp( options, 'decodeStrings' ) ) { opts.decodeStrings = options.decodeStrings; if ( !isBoolean( opts.decodeStrings ) ) { return new TypeError( 'invalid option. `decodeStrings` option must be a primitive boolean. Option: `' + opts.decodeStrings + '`.' ); } } return null; } // EXPORTS // module.exports = validate; },{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-boolean":72,"@stdlib/assert/is-function":93,"@stdlib/assert/is-nonnegative-number":122,"@stdlib/assert/is-plain-object":138,"@stdlib/assert/is-string":149}],277:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Create a string from a sequence of Unicode code points. * * @module @stdlib/string/from-code-point * * @example * var fromCodePoint = require( '@stdlib/string/from-code-point' ); * * var str = fromCodePoint( 9731 ); * // returns '☃' */ // MODULES // var fromCodePoint = require( './main.js' ); // EXPORTS // module.exports = fromCodePoint; },{"./main.js":278}],278:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var UNICODE_MAX = require( '@stdlib/constants/unicode/max' ); var UNICODE_MAX_BMP = require( '@stdlib/constants/unicode/max-bmp' ); // VARIABLES // var fromCharCode = String.fromCharCode; // Factor to rescale a code point from a supplementary plane: var Ox10000 = 0x10000|0; // 65536 // Factor added to obtain a high surrogate: var OxD800 = 0xD800|0; // 55296 // Factor added to obtain a low surrogate: var OxDC00 = 0xDC00|0; // 56320 // 10-bit mask: 2^10-1 = 1023 => 0x3ff => 00000000 00000000 00000011 11111111 var Ox3FF = 1023|0; // MAIN // /** * Creates a string from a sequence of Unicode code points. * * ## Notes * * - UTF-16 encoding uses one 16-bit unit for non-surrogates (U+0000 to U+D7FF and U+E000 to U+FFFF). * - UTF-16 encoding uses two 16-bit units (surrogate pairs) for U+10000 to U+10FFFF and encodes U+10000-U+10FFFF by subtracting 0x10000 from the code point, expressing the result as a 20-bit binary, and splitting the 20 bits of 0x0-0xFFFFF as upper and lower 10-bits. The respective 10-bits are stored in two 16-bit words: a high and a low surrogate. * * * @param {...NonNegativeInteger} args - sequence of code points * @throws {Error} must provide either an array-like object of code points or one or more code points as separate arguments * @throws {TypeError} a code point must be a nonnegative integer * @throws {RangeError} must provide a valid Unicode code point * @returns {string} created string * * @example * var str = fromCodePoint( 9731 ); * // returns '☃' */ function fromCodePoint( args ) { var len; var str; var arr; var low; var hi; var pt; var i; len = arguments.length; if ( len === 1 && isCollection( args ) ) { arr = arguments[ 0 ]; len = arr.length; } else { arr = []; for ( i = 0; i < len; i++ ) { arr.push( arguments[ i ] ); } } if ( len === 0 ) { throw new Error( 'insufficient input arguments. Must provide either an array of code points or one or more code points as separate arguments.' ); } str = ''; for ( i = 0; i < len; i++ ) { pt = arr[ i ]; if ( !isNonNegativeInteger( pt ) ) { throw new TypeError( 'invalid argument. Must provide valid code points (nonnegative integers). Value: `'+pt+'`.' ); } if ( pt > UNICODE_MAX ) { throw new RangeError( 'invalid argument. Must provide a valid code point (cannot exceed max). Value: `'+pt+'`.' ); } if ( pt <= UNICODE_MAX_BMP ) { str += fromCharCode( pt ); } else { // Code point from a supplementary plane. Split into two 16-bit code units (surrogate pair). pt -= Ox10000; hi = (pt >> 10) + OxD800; low = (pt & Ox3FF) + OxDC00; str += fromCharCode( hi, low ); } } return str; } // EXPORTS // module.exports = fromCodePoint; },{"@stdlib/assert/is-collection":81,"@stdlib/assert/is-nonnegative-integer":118,"@stdlib/constants/unicode/max":236,"@stdlib/constants/unicode/max-bmp":235}],279:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Replace search occurrences with a replacement string. * * @module @stdlib/string/replace * * @example * var replace = require( '@stdlib/string/replace' ); * * var str = 'beep'; * var out = replace( str, 'e', 'o' ); * // returns 'boop' * * str = 'Hello World'; * out = replace( str, /world/i, 'Mr. President' ); * // returns 'Hello Mr. President' */ // MODULES // var replace = require( './replace.js' ); // EXPORTS // module.exports = replace; },{"./replace.js":280}],280:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var rescape = require( '@stdlib/utils/escape-regexp-string' ); var isFunction = require( '@stdlib/assert/is-function' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isRegExp = require( '@stdlib/assert/is-regexp' ); // MAIN // /** * Replace search occurrences with a replacement string. * * @param {string} str - input string * @param {(string|RegExp)} search - search expression * @param {(string|Function)} newval - replacement value or function * @throws {TypeError} first argument must be a string primitive * @throws {TypeError} second argument argument must be a string primitive or regular expression * @throws {TypeError} third argument must be a string primitive or function * @returns {string} new string containing replacement(s) * * @example * var str = 'beep'; * var out = replace( str, 'e', 'o' ); * // returns 'boop' * * @example * var str = 'Hello World'; * var out = replace( str, /world/i, 'Mr. President' ); * // returns 'Hello Mr. President' * * @example * var capitalize = require( '@stdlib/string/capitalize' ); * * var str = 'Oranges and lemons say the bells of St. Clement\'s'; * * function replacer( match, p1 ) { * return capitalize( p1 ); * } * * var out = replace( str, /([^\s]*)/gi, replacer); * // returns 'Oranges And Lemons Say The Bells Of St. Clement\'s' */ function replace( str, search, newval ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + str + '`.' ); } if ( isString( search ) ) { search = rescape( search ); search = new RegExp( search, 'g' ); } else if ( !isRegExp( search ) ) { throw new TypeError( 'invalid argument. Second argument must be a string primitive or regular expression. Value: `' + search + '`.' ); } if ( !isString( newval ) && !isFunction( newval ) ) { throw new TypeError( 'invalid argument. Third argument must be a string primitive or replacement function. Value: `' + newval + '`.' ); } return str.replace( search, newval ); } // EXPORTS // module.exports = replace; },{"@stdlib/assert/is-function":93,"@stdlib/assert/is-regexp":145,"@stdlib/assert/is-string":149,"@stdlib/utils/escape-regexp-string":304}],281:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Trim whitespace characters from the beginning and end of a string. * * @module @stdlib/string/trim * * @example * var trim = require( '@stdlib/string/trim' ); * * var out = trim( ' Whitespace ' ); * // returns 'Whitespace' * * out = trim( '\t\t\tTabs\t\t\t' ); * // returns 'Tabs' * * out = trim( '\n\n\nNew Lines\n\n\n' ); * // returns 'New Lines' */ // MODULES // var trim = require( './trim.js' ); // EXPORTS // module.exports = trim; },{"./trim.js":282}],282:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var replace = require( '@stdlib/string/replace' ); // VARIABLES // // The following regular expression should suffice to polyfill (most?) all environments. var RE = /^[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*([\S\s]*?)[\u0020\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$/; // MAIN // /** * Trim whitespace characters from beginning and end of a string. * * @param {string} str - input string * @throws {TypeError} must provide a string primitive * @returns {string} trimmed string * * @example * var out = trim( ' Whitespace ' ); * // returns 'Whitespace' * * @example * var out = trim( '\t\t\tTabs\t\t\t' ); * // returns 'Tabs' * * @example * var out = trim( '\n\n\nNew Lines\n\n\n' ); * // returns 'New Lines' */ function trim( str ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a string primitive. Value: `' + str + '`.' ); } return replace( str, RE, '$1' ); } // EXPORTS // module.exports = trim; },{"@stdlib/assert/is-string":149,"@stdlib/string/replace":279}],283:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var getGlobal = require( '@stdlib/utils/global' ); var isObject = require( '@stdlib/assert/is-object' ); var modf = require( '@stdlib/math/base/special/modf' ); var round = require( '@stdlib/math/base/special/round' ); var now = require( './now.js' ); // VARIABLES // var Global = getGlobal(); var ts; var ns; if ( isObject( Global.performance ) ) { ns = Global.performance; } else { ns = {}; } if ( ns.now ) { ts = ns.now.bind( ns ); } else if ( ns.mozNow ) { ts = ns.mozNow.bind( ns ); } else if ( ns.msNow ) { ts = ns.msNow.bind( ns ); } else if ( ns.oNow ) { ts = ns.oNow.bind( ns ); } else if ( ns.webkitNow ) { ts = ns.webkitNow.bind( ns ); } else { ts = now; } // MAIN // /** * Returns a high-resolution time. * * ## Notes * * - Output format: `[seconds, nanoseconds]`. * * * @private * @returns {NumberArray} high-resolution time * * @example * var t = tic(); * // returns [<number>,<number>] */ function tic() { var parts; var t; // Get a millisecond timestamp and convert to seconds: t = ts() / 1000; // Decompose the timestamp into integer (seconds) and fractional parts: parts = modf( t ); // Convert the fractional part to nanoseconds: parts[ 1 ] = round( parts[1] * 1.0e9 ); // Return the high-resolution time: return parts; } // EXPORTS // module.exports = tic; },{"./now.js":285,"@stdlib/assert/is-object":136,"@stdlib/math/base/special/modf":243,"@stdlib/math/base/special/round":246,"@stdlib/utils/global":318}],284:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); // MAIN // var bool = isFunction( Date.now ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-function":93}],285:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var bool = require( './detect.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var now; if ( bool ) { now = Date.now; } else { now = polyfill; } // EXPORTS // module.exports = now; },{"./detect.js":284,"./polyfill.js":286}],286:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Returns the time in milliseconds since the epoch. * * @private * @returns {number} time * * @example * var ts = now(); * // returns <number> */ function now() { var d = new Date(); return d.getTime(); } // EXPORTS // module.exports = now; },{}],287:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a high-resolution time difference. * * @module @stdlib/time/toc * * @example * var tic = require( '@stdlib/time/tic' ); * var toc = require( '@stdlib/time/toc' ); * * var start = tic(); * var delta = toc( start ); * // returns [<number>,<number>] */ // MODULES // var toc = require( './toc.js' ); // EXPORTS // module.exports = toc; },{"./toc.js":288}],288:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives; var tic = require( '@stdlib/time/tic' ); // MAIN // /** * Returns a high-resolution time difference. * * ## Notes * * - Output format: `[seconds, nanoseconds]`. * * * @param {NonNegativeIntegerArray} time - high-resolution time * @throws {TypeError} must provide a nonnegative integer array * @throws {RangeError} input array must have length `2` * @returns {NumberArray} high resolution time difference * * @example * var tic = require( '@stdlib/time/tic' ); * * var start = tic(); * var delta = toc( start ); * // returns [<number>,<number>] */ function toc( time ) { var now = tic(); var sec; var ns; if ( !isNonNegativeIntegerArray( time ) ) { throw new TypeError( 'invalid argument. Must provide an array of nonnegative integers. Value: `' + time + '`.' ); } if ( time.length !== 2 ) { throw new RangeError( 'invalid argument. Input array must have length `2`.' ); } sec = now[ 0 ] - time[ 0 ]; ns = now[ 1 ] - time[ 1 ]; if ( sec > 0 && ns < 0 ) { sec -= 1; ns += 1e9; } else if ( sec < 0 && ns > 0 ) { sec += 1; ns -= 1e9; } return [ sec, ns ]; } // EXPORTS // module.exports = toc; },{"@stdlib/assert/is-nonnegative-integer-array":117,"@stdlib/time/tic":283}],289:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Determine the name of a value's constructor. * * @module @stdlib/utils/constructor-name * * @example * var constructorName = require( '@stdlib/utils/constructor-name' ); * * var v = constructorName( 'a' ); * // returns 'String' * * v = constructorName( {} ); * // returns 'Object' * * v = constructorName( true ); * // returns 'Boolean' */ // MODULES // var constructorName = require( './main.js' ); // EXPORTS // module.exports = constructorName; },{"./main.js":290}],290:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); var RE = require( '@stdlib/regexp/function-name' ).REGEXP; var isBuffer = require( '@stdlib/assert/is-buffer' ); // MAIN // /** * Determines the name of a value's constructor. * * @param {*} v - input value * @returns {string} name of a value's constructor * * @example * var v = constructorName( 'a' ); * // returns 'String' * * @example * var v = constructorName( 5 ); * // returns 'Number' * * @example * var v = constructorName( null ); * // returns 'Null' * * @example * var v = constructorName( undefined ); * // returns 'Undefined' * * @example * var v = constructorName( function noop() {} ); * // returns 'Function' */ function constructorName( v ) { var match; var name; var ctor; name = nativeClass( v ).slice( 8, -1 ); if ( (name === 'Object' || name === 'Error') && v.constructor ) { ctor = v.constructor; if ( typeof ctor.name === 'string' ) { return ctor.name; } match = RE.exec( ctor.toString() ); if ( match ) { return match[ 1 ]; } } if ( isBuffer( v ) ) { return 'Buffer'; } return name; } // EXPORTS // module.exports = constructorName; },{"@stdlib/assert/is-buffer":79,"@stdlib/regexp/function-name":262,"@stdlib/utils/native-class":346}],291:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isArray = require( '@stdlib/assert/is-array' ); var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive; var PINF = require( '@stdlib/constants/float64/pinf' ); var deepCopy = require( './deep_copy.js' ); // MAIN // /** * Copies or deep clones a value to an arbitrary depth. * * @param {*} value - value to copy * @param {NonNegativeInteger} [level=+infinity] - copy depth * @throws {TypeError} `level` must be a nonnegative integer * @returns {*} value copy * * @example * var out = copy( 'beep' ); * // returns 'beep' * * @example * var value = [ * { * 'a': 1, * 'b': true, * 'c': [ 1, 2, 3 ] * } * ]; * var out = copy( value ); * // returns [ { 'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ] * * var bool = ( value[0].c === out[0].c ); * // returns false */ function copy( value, level ) { var out; if ( arguments.length > 1 ) { if ( !isNonNegativeInteger( level ) ) { throw new TypeError( 'invalid argument. `level` must be a nonnegative integer. Value: `' + level + '`.' ); } if ( level === 0 ) { return value; } } else { level = PINF; } out = ( isArray( value ) ) ? new Array( value.length ) : {}; return deepCopy( value, out, [value], [out], level ); } // EXPORTS // module.exports = copy; },{"./deep_copy.js":292,"@stdlib/assert/is-array":70,"@stdlib/assert/is-nonnegative-integer":118,"@stdlib/constants/float64/pinf":225}],292:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isArray = require( '@stdlib/assert/is-array' ); var isBuffer = require( '@stdlib/assert/is-buffer' ); var isError = require( '@stdlib/assert/is-error' ); var typeOf = require( '@stdlib/utils/type-of' ); var regexp = require( '@stdlib/utils/regexp-from-string' ); var indexOf = require( '@stdlib/utils/index-of' ); var objectKeys = require( '@stdlib/utils/keys' ); var propertyNames = require( '@stdlib/utils/property-names' ); var propertyDescriptor = require( '@stdlib/utils/property-descriptor' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var defineProperty = require( '@stdlib/utils/define-property' ); var copyBuffer = require( '@stdlib/buffer/from-buffer' ); var typedArrays = require( './typed_arrays.js' ); // FUNCTIONS // /** * Clones a class instance. * * ## Notes * * - This should **only** be used for simple cases. Any instances with privileged access to variables (e.g., within closures) cannot be cloned. This approach should be considered **fragile**. * - The function is greedy, disregarding the notion of a `level`. Instead, the function deep copies all properties, as we assume the concept of `level` applies only to the class instance reference but not to its internal state. This prevents, in theory, two instances from sharing state. * * * @private * @param {Object} val - class instance * @returns {Object} new instance */ function cloneInstance( val ) { var cache; var names; var name; var refs; var desc; var tmp; var ref; var i; cache = []; refs = []; ref = Object.create( getPrototypeOf( val ) ); cache.push( val ); refs.push( ref ); names = propertyNames( val ); for ( i = 0; i < names.length; i++ ) { name = names[ i ]; desc = propertyDescriptor( val, name ); if ( hasOwnProp( desc, 'value' ) ) { tmp = ( isArray( val[name] ) ) ? [] : {}; desc.value = deepCopy( val[name], tmp, cache, refs, -1 ); } defineProperty( ref, name, desc ); } if ( !Object.isExtensible( val ) ) { Object.preventExtensions( ref ); } if ( Object.isSealed( val ) ) { Object.seal( ref ); } if ( Object.isFrozen( val ) ) { Object.freeze( ref ); } return ref; } /** * Copies an error object. * * @private * @param {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error - error to copy * @returns {(Error|TypeError|SyntaxError|URIError|ReferenceError|RangeError|EvalError)} error copy * * @example * var err1 = new TypeError( 'beep' ); * * var err2 = copyError( err1 ); * // returns <TypeError> */ function copyError( error ) { var cache = []; var refs = []; var keys; var desc; var tmp; var key; var err; var i; // Create a new error... err = new error.constructor( error.message ); cache.push( error ); refs.push( err ); // If a `stack` property is present, copy it over... if ( error.stack ) { err.stack = error.stack; } // Node.js specific (system errors)... if ( error.code ) { err.code = error.code; } if ( error.errno ) { err.errno = error.errno; } if ( error.syscall ) { err.syscall = error.syscall; } // Any enumerable properties... keys = objectKeys( error ); for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; desc = propertyDescriptor( error, key ); if ( hasOwnProp( desc, 'value' ) ) { tmp = ( isArray( error[ key ] ) ) ? [] : {}; desc.value = deepCopy( error[ key ], tmp, cache, refs, -1 ); } defineProperty( err, key, desc ); } return err; } // MAIN // /** * Recursively performs a deep copy of an input object. * * @private * @param {*} val - value to copy * @param {(Array|Object)} copy - copy * @param {Array} cache - an array of visited objects * @param {Array} refs - an array of object references * @param {NonNegativeInteger} level - copy depth * @returns {*} deep copy */ function deepCopy( val, copy, cache, refs, level ) { var parent; var keys; var name; var desc; var ctor; var key; var ref; var x; var i; var j; level -= 1; // Primitives and functions... if ( typeof val !== 'object' || val === null ) { return val; } if ( isBuffer( val ) ) { return copyBuffer( val ); } if ( isError( val ) ) { return copyError( val ); } // Objects... name = typeOf( val ); if ( name === 'date' ) { return new Date( +val ); } if ( name === 'regexp' ) { return regexp( val.toString() ); } if ( name === 'set' ) { return new Set( val ); } if ( name === 'map' ) { return new Map( val ); } if ( name === 'string' || name === 'boolean' || name === 'number' ) { // If provided an `Object`, return an equivalent primitive! return val.valueOf(); } ctor = typedArrays[ name ]; if ( ctor ) { return ctor( val ); } // Class instances... if ( name !== 'array' && name !== 'object' ) { // Cloning requires ES5 or higher... if ( typeof Object.freeze === 'function' ) { return cloneInstance( val ); } return {}; } // Arrays and plain objects... keys = objectKeys( val ); if ( level > 0 ) { parent = name; for ( j = 0; j < keys.length; j++ ) { key = keys[ j ]; x = val[ key ]; // Primitive, Buffer, special class instance... name = typeOf( x ); if ( typeof x !== 'object' || x === null || ( name !== 'array' && name !== 'object' ) || isBuffer( x ) ) { if ( parent === 'object' ) { desc = propertyDescriptor( val, key ); if ( hasOwnProp( desc, 'value' ) ) { desc.value = deepCopy( x ); } defineProperty( copy, key, desc ); } else { copy[ key ] = deepCopy( x ); } continue; } // Circular reference... i = indexOf( cache, x ); if ( i !== -1 ) { copy[ key ] = refs[ i ]; continue; } // Plain array or object... ref = ( isArray( x ) ) ? new Array( x.length ) : {}; cache.push( x ); refs.push( ref ); if ( parent === 'array' ) { copy[ key ] = deepCopy( x, ref, cache, refs, level ); } else { desc = propertyDescriptor( val, key ); if ( hasOwnProp( desc, 'value' ) ) { desc.value = deepCopy( x, ref, cache, refs, level ); } defineProperty( copy, key, desc ); } } } else if ( name === 'array' ) { for ( j = 0; j < keys.length; j++ ) { key = keys[ j ]; copy[ key ] = val[ key ]; } } else { for ( j = 0; j < keys.length; j++ ) { key = keys[ j ]; desc = propertyDescriptor( val, key ); defineProperty( copy, key, desc ); } } if ( !Object.isExtensible( val ) ) { Object.preventExtensions( copy ); } if ( Object.isSealed( val ) ) { Object.seal( copy ); } if ( Object.isFrozen( val ) ) { Object.freeze( copy ); } return copy; } // EXPORTS // module.exports = deepCopy; },{"./typed_arrays.js":294,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-array":70,"@stdlib/assert/is-buffer":79,"@stdlib/assert/is-error":87,"@stdlib/buffer/from-buffer":216,"@stdlib/utils/define-property":302,"@stdlib/utils/get-prototype-of":312,"@stdlib/utils/index-of":322,"@stdlib/utils/keys":339,"@stdlib/utils/property-descriptor":361,"@stdlib/utils/property-names":365,"@stdlib/utils/regexp-from-string":368,"@stdlib/utils/type-of":373}],293:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Copy or deep clone a value to an arbitrary depth. * * @module @stdlib/utils/copy * * @example * var copy = require( '@stdlib/utils/copy' ); * * var out = copy( 'beep' ); * // returns 'beep' * * @example * var copy = require( '@stdlib/utils/copy' ); * * var value = [ * { * 'a': 1, * 'b': true, * 'c': [ 1, 2, 3 ] * } * ]; * var out = copy( value ); * // returns [ {'a': 1, 'b': true, 'c': [ 1, 2, 3 ] } ] * * var bool = ( value[0].c === out[0].c ); * // returns false */ // MODULES // var copy = require( './copy.js' ); // EXPORTS // module.exports = copy; },{"./copy.js":291}],294:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var Int8Array = require( '@stdlib/array/int8' ); var Uint8Array = require( '@stdlib/array/uint8' ); var Uint8ClampedArray = require( '@stdlib/array/uint8c' ); var Int16Array = require( '@stdlib/array/int16' ); var Uint16Array = require( '@stdlib/array/uint16' ); var Int32Array = require( '@stdlib/array/int32' ); var Uint32Array = require( '@stdlib/array/uint32' ); var Float32Array = require( '@stdlib/array/float32' ); var Float64Array = require( '@stdlib/array/float64' ); // VARIABLES // var hash; // FUNCTIONS // /** * Copies an `Int8Array`. * * @private * @param {Int8Array} arr - array to copy * @returns {Int8Array} new array */ function int8array( arr ) { return new Int8Array( arr ); } /** * Copies a `Uint8Array`. * * @private * @param {Uint8Array} arr - array to copy * @returns {Uint8Array} new array */ function uint8array( arr ) { return new Uint8Array( arr ); } /** * Copies a `Uint8ClampedArray`. * * @private * @param {Uint8ClampedArray} arr - array to copy * @returns {Uint8ClampedArray} new array */ function uint8clampedarray( arr ) { return new Uint8ClampedArray( arr ); } /** * Copies an `Int16Array`. * * @private * @param {Int16Array} arr - array to copy * @returns {Int16Array} new array */ function int16array( arr ) { return new Int16Array( arr ); } /** * Copies a `Uint16Array`. * * @private * @param {Uint16Array} arr - array to copy * @returns {Uint16Array} new array */ function uint16array( arr ) { return new Uint16Array( arr ); } /** * Copies an `Int32Array`. * * @private * @param {Int32Array} arr - array to copy * @returns {Int32Array} new array */ function int32array( arr ) { return new Int32Array( arr ); } /** * Copies a `Uint32Array`. * * @private * @param {Uint32Array} arr - array to copy * @returns {Uint32Array} new array */ function uint32array( arr ) { return new Uint32Array( arr ); } /** * Copies a `Float32Array`. * * @private * @param {Float32Array} arr - array to copy * @returns {Float32Array} new array */ function float32array( arr ) { return new Float32Array( arr ); } /** * Copies a `Float64Array`. * * @private * @param {Float64Array} arr - array to copy * @returns {Float64Array} new array */ function float64array( arr ) { return new Float64Array( arr ); } /** * Returns a hash of functions for copying typed arrays. * * @private * @returns {Object} function hash */ function typedarrays() { var out = { 'int8array': int8array, 'uint8array': uint8array, 'uint8clampedarray': uint8clampedarray, 'int16array': int16array, 'uint16array': uint16array, 'int32array': int32array, 'uint32array': uint32array, 'float32array': float32array, 'float64array': float64array }; return out; } // MAIN // hash = typedarrays(); // EXPORTS // module.exports = hash; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":16,"@stdlib/array/uint32":19,"@stdlib/array/uint8":22,"@stdlib/array/uint8c":25}],295:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Define a non-enumerable read-only accessor. * * @module @stdlib/utils/define-nonenumerable-read-only-accessor * * @example * var setNonEnumerableReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); * * function getter() { * return 'bar'; * } * * var obj = {}; * * setNonEnumerableReadOnlyAccessor( obj, 'foo', getter ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ // MODULES // var setNonEnumerableReadOnlyAccessor = require( './main.js' ); // eslint-disable-line id-length // EXPORTS // module.exports = setNonEnumerableReadOnlyAccessor; },{"./main.js":296}],296:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); // MAIN // /** * Defines a non-enumerable read-only accessor. * * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {Function} getter - accessor * * @example * function getter() { * return 'bar'; * } * * var obj = {}; * * setNonEnumerableReadOnlyAccessor( obj, 'foo', getter ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ function setNonEnumerableReadOnlyAccessor( obj, prop, getter ) { // eslint-disable-line id-length defineProperty( obj, prop, { 'configurable': false, 'enumerable': false, 'get': getter }); } // EXPORTS // module.exports = setNonEnumerableReadOnlyAccessor; },{"@stdlib/utils/define-property":302}],297:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Define a non-enumerable read-only property. * * @module @stdlib/utils/define-nonenumerable-read-only-property * * @example * var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); * * var obj = {}; * * setNonEnumerableReadOnly( obj, 'foo', 'bar' ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ // MODULES // var setNonEnumerableReadOnly = require( './main.js' ); // EXPORTS // module.exports = setNonEnumerableReadOnly; },{"./main.js":298}],298:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); // MAIN // /** * Defines a non-enumerable read-only property. * * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {*} value - value to set * * @example * var obj = {}; * * setNonEnumerableReadOnly( obj, 'foo', 'bar' ); * * try { * obj.foo = 'boop'; * } catch ( err ) { * console.error( err.message ); * } */ function setNonEnumerableReadOnly( obj, prop, value ) { defineProperty( obj, prop, { 'configurable': false, 'enumerable': false, 'writable': false, 'value': value }); } // EXPORTS // module.exports = setNonEnumerableReadOnly; },{"@stdlib/utils/define-property":302}],299:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Defines (or modifies) an object property. * * ## Notes * * - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both. * * @name defineProperty * @type {Function} * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {Object} descriptor - property descriptor * @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object * @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties * @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator * @param {*} [descriptor.value] - property value * @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value. * @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned. * @throws {TypeError} first argument must be an object * @throws {TypeError} third argument must be an object * @throws {Error} property descriptor cannot have both a value and a setter and/or getter * @returns {Object} object with added property * * @example * var obj = {}; * * defineProperty( obj, 'foo', { * 'value': 'bar' * }); * * var str = obj.foo; * // returns 'bar' */ var defineProperty = Object.defineProperty; // EXPORTS // module.exports = defineProperty; },{}],300:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MAIN // var main = ( typeof Object.defineProperty === 'function' ) ? Object.defineProperty : null; // EXPORTS // module.exports = main; },{}],301:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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'; // MODULES // var defineProperty = require( './define_property.js' ); // MAIN // /** * Tests for `Object.defineProperty` support. * * @private * @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support * * @example * var bool = hasDefinePropertySupport(); * // returns <boolean> */ function hasDefinePropertySupport() { // Test basic support... try { defineProperty( {}, 'x', {} ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = hasDefinePropertySupport; },{"./define_property.js":300}],302:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Define (or modify) an object property. * * @module @stdlib/utils/define-property * * @example * var defineProperty = require( '@stdlib/utils/define-property' ); * * var obj = {}; * defineProperty( obj, 'foo', { * 'value': 'bar', * 'writable': false, * 'configurable': false, * 'enumerable': false * }); * obj.foo = 'boop'; // => throws */ // MODULES // var hasDefinePropertySupport = require( './has_define_property_support.js' ); var builtin = require( './builtin.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var defineProperty; if ( hasDefinePropertySupport() ) { defineProperty = builtin; } else { defineProperty = polyfill; } // EXPORTS // module.exports = defineProperty; },{"./builtin.js":299,"./has_define_property_support.js":301,"./polyfill.js":303}],303:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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 no-underscore-dangle, no-proto */ 'use strict'; // VARIABLES // var objectProtoype = Object.prototype; var toStr = objectProtoype.toString; var defineGetter = objectProtoype.__defineGetter__; var defineSetter = objectProtoype.__defineSetter__; var lookupGetter = objectProtoype.__lookupGetter__; var lookupSetter = objectProtoype.__lookupSetter__; // MAIN // /** * Defines (or modifies) an object property. * * ## Notes * * - Property descriptors come in two flavors: **data descriptors** and **accessor descriptors**. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter function pair. A descriptor must be one of these two flavors and cannot be both. * * @param {Object} obj - object on which to define the property * @param {string} prop - property name * @param {Object} descriptor - property descriptor * @param {boolean} [descriptor.configurable=false] - boolean indicating if property descriptor can be changed and if the property can be deleted from the provided object * @param {boolean} [descriptor.enumerable=false] - boolean indicating if the property shows up when enumerating object properties * @param {boolean} [descriptor.writable=false] - boolean indicating if the value associated with the property can be changed with an assignment operator * @param {*} [descriptor.value] - property value * @param {(Function|void)} [descriptor.get=undefined] - function which serves as a getter for the property, or, if no getter, undefined. When the property is accessed, a getter function is called without arguments and with the `this` context set to the object through which the property is accessed (which may not be the object on which the property is defined due to inheritance). The return value will be used as the property value. * @param {(Function|void)} [descriptor.set=undefined] - function which serves as a setter for the property, or, if no setter, undefined. When assigning a property value, a setter function is called with one argument (the value being assigned to the property) and with the `this` context set to the object through which the property is assigned. * @throws {TypeError} first argument must be an object * @throws {TypeError} third argument must be an object * @throws {Error} property descriptor cannot have both a value and a setter and/or getter * @returns {Object} object with added property * * @example * var obj = {}; * * defineProperty( obj, 'foo', { * 'value': 'bar' * }); * * var str = obj.foo; * // returns 'bar' */ function defineProperty( obj, prop, descriptor ) { var prototype; var hasValue; var hasGet; var hasSet; if ( typeof obj !== 'object' || obj === null || toStr.call( obj ) === '[object Array]' ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `' + obj + '`.' ); } if ( typeof descriptor !== 'object' || descriptor === null || toStr.call( descriptor ) === '[object Array]' ) { throw new TypeError( 'invalid argument. Property descriptor must be an object. Value: `' + descriptor + '`.' ); } hasValue = ( 'value' in descriptor ); if ( hasValue ) { if ( lookupGetter.call( obj, prop ) || lookupSetter.call( obj, prop ) ) { // Override `__proto__` to avoid touching inherited accessors: prototype = obj.__proto__; obj.__proto__ = objectProtoype; // Delete property as existing getters/setters prevent assigning value to specified property: delete obj[ prop ]; obj[ prop ] = descriptor.value; // Restore original prototype: obj.__proto__ = prototype; } else { obj[ prop ] = descriptor.value; } } hasGet = ( 'get' in descriptor ); hasSet = ( 'set' in descriptor ); if ( hasValue && ( hasGet || hasSet ) ) { throw new Error( 'invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.' ); } if ( hasGet && defineGetter ) { defineGetter.call( obj, prop, descriptor.get ); } if ( hasSet && defineSetter ) { defineSetter.call( obj, prop, descriptor.set ); } return obj; } // EXPORTS // module.exports = defineProperty; },{}],304:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Escape a regular expression string or pattern. * * @module @stdlib/utils/escape-regexp-string * * @example * var rescape = require( '@stdlib/utils/escape-regexp-string' ); * * var str = rescape( '[A-Z]*' ); * // returns '\\[A\\-Z\\]\\*' */ // MODULES // var rescape = require( './main.js' ); // EXPORTS // module.exports = rescape; },{"./main.js":305}],305:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; // VARIABLES // var RE_CHARS = /[-\/\\^$*+?.()|[\]{}]/g; // eslint-disable-line no-useless-escape // MAIN // /** * Escapes a regular expression string. * * @param {string} str - regular expression string * @throws {TypeError} first argument must be a string primitive * @returns {string} escaped string * * @example * var str = rescape( '[A-Z]*' ); * // returns '\\[A\\-Z\\]\\*' */ function rescape( str ) { var len; var s; var i; if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' ); } // Check if the string starts with a forward slash... if ( str[ 0 ] === '/' ) { // Find the last forward slash... len = str.length; for ( i = len-1; i >= 0; i-- ) { if ( str[ i ] === '/' ) { break; } } } // If we searched the string to no avail or if the first letter is not `/`, assume that the string is not of the form `/[...]/[guimy]`: if ( i === void 0 || i <= 0 ) { return str.replace( RE_CHARS, '\\$&' ); } // We need to de-construct the string... s = str.substring( 1, i ); // Only escape the characters between the `/`: s = s.replace( RE_CHARS, '\\$&' ); // Reassemble: str = str[ 0 ] + s + str.substring( i ); return str; } // EXPORTS // module.exports = rescape; },{"@stdlib/assert/is-string":149}],306:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var bench = require( '@stdlib/bench' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pkg = require( './../package.json' ).name; var everyBy = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var bool; var arr; var i; function predicate( v ) { return !isnan( v ); } b.tic(); for ( i = 0; i < b.iterations; i++ ) { arr = [ i, i+1, i+2, i+3, i+4 ]; bool = everyBy( arr, predicate ); if ( !isBoolean( bool ) ) { b.fail( 'should return a boolean' ); } } b.toc(); if ( !isBoolean( bool ) ) { b.fail( 'should return a boolean' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::built-in', function benchmark( b ) { var bool; var arr; var i; function predicate( v ) { return !isnan( v ); } b.tic(); for ( i = 0; i < b.iterations; i++ ) { arr = [ i, i+1, i+2, i+3, i+4 ]; bool = arr.every( predicate ); if ( !isBoolean( bool ) ) { b.fail( 'should return a boolean' ); } } b.toc(); if ( !isBoolean( bool ) ) { b.fail( 'should return a boolean' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::loop', function benchmark( b ) { var bool; var arr; var i; var j; b.tic(); for ( i = 0; i < b.iterations; i++ ) { arr = [ i, i+1, i+2, i+3, i+4 ]; bool = true; for ( j = 0; j < arr.length; j++ ) { if ( isnan( arr[ j ] ) ) { bool = false; break; } } if ( !isBoolean( bool ) ) { b.fail( 'should be a boolean' ); } } b.toc(); if ( !isBoolean( bool ) ) { b.fail( 'should be a boolean' ); } b.pass( 'benchmark finished' ); b.end(); }); },{"./../lib":308,"./../package.json":309,"@stdlib/assert/is-boolean":72,"@stdlib/bench":211,"@stdlib/math/base/assert/is-nan":239}],307:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isCollection = require( '@stdlib/assert/is-collection' ); var isFunction = require( '@stdlib/assert/is-function' ); // MAIN // /** * Tests whether all elements in a collection pass a test implemented by a predicate function. * * @param {Collection} collection - input collection * @param {Function} predicate - test function * @param {*} [thisArg] - execution context * @throws {TypeError} first argument must be a collection * @throws {TypeError} second argument must be a function * @returns {boolean} boolean indicating whether all elements pass a test * * @example * function isPositive( v ) { * return ( v > 0 ); * } * * var arr = [ 1, 2, 3, 4 ]; * * var bool = everyBy( arr, isPositive ); * // returns true */ function everyBy( collection, predicate, thisArg ) { var out; var len; var i; if ( !isCollection( collection ) ) { throw new TypeError( 'invalid argument. First argument must be a collection. Value: `'+collection+'`.' ); } if ( !isFunction( predicate ) ) { throw new TypeError( 'invalid argument. Second argument must be a function. Value: `'+predicate+'`.' ); } len = collection.length; for ( i = 0; i < len; i++ ) { out = predicate.call( thisArg, collection[ i ], i, collection ); if ( !out ) { return false; } // Account for dynamically resizing a collection: len = collection.length; } return true; } // EXPORTS // module.exports = everyBy; },{"@stdlib/assert/is-collection":81,"@stdlib/assert/is-function":93}],308:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Test whether all elements in a collection pass a test implemented by a predicate function. * * @module @stdlib/utils/every-by * * @example * var every = require( '@stdlib/utils/every-by' ); * * function isPositive( v ) { * return ( v > 0 ); * } * * var arr = [ 1, 2, 3, 4 ]; * * var bool = everyBy( arr, isPositive ); * // returns true */ // MODULES // var everyBy = require( './every_by.js' ); // EXPORTS // module.exports = everyBy; },{"./every_by.js":307}],309:[function(require,module,exports){ module.exports={ "name": "@stdlib/utils/every-by", "version": "0.0.0", "description": "Test whether all elements in a collection pass a test implemented by a predicate function.", "license": "Apache-2.0", "author": { "name": "The Stdlib Authors", "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" }, "contributors": [ { "name": "The Stdlib Authors", "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" } ], "main": "./lib", "directories": { "benchmark": "./benchmark", "doc": "./docs", "example": "./examples", "lib": "./lib", "test": "./test" }, "types": "./docs/types", "scripts": {}, "homepage": "https://github.com/stdlib-js/stdlib", "repository": { "type": "git", "url": "git://github.com/stdlib-js/stdlib.git" }, "bugs": { "url": "https://github.com/stdlib-js/stdlib/issues" }, "dependencies": {}, "devDependencies": {}, "engines": { "node": ">=0.10.0", "npm": ">2.7.0" }, "os": [ "aix", "darwin", "freebsd", "linux", "macos", "openbsd", "sunos", "win32", "windows" ], "keywords": [ "stdlib", "stdutils", "stdutil", "utilities", "utility", "utils", "util", "test", "predicate", "every", "all", "array.every", "iterate", "collection", "array-like", "validate" ] } },{}],310:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); var builtin = require( './native.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var getProto; if ( isFunction( Object.getPrototypeOf ) ) { getProto = builtin; } else { getProto = polyfill; } // EXPORTS // module.exports = getProto; },{"./native.js":313,"./polyfill.js":314,"@stdlib/assert/is-function":93}],311:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var getProto = require( './detect.js' ); // MAIN // /** * Returns the prototype of a provided object. * * @param {*} value - input value * @returns {(Object|null)} prototype * * @example * var proto = getPrototypeOf( {} ); * // returns {} */ function getPrototypeOf( value ) { if ( value === null || value === void 0 ) { return null; } // In order to ensure consistent ES5/ES6 behavior, cast input value to an object (strings, numbers, booleans); ES5 `Object.getPrototypeOf` throws when provided primitives and ES6 `Object.getPrototypeOf` casts: value = Object( value ); return getProto( value ); } // EXPORTS // module.exports = getPrototypeOf; },{"./detect.js":310}],312:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return the prototype of a provided object. * * @module @stdlib/utils/get-prototype-of * * @example * var getPrototype = require( '@stdlib/utils/get-prototype-of' ); * * var proto = getPrototype( {} ); * // returns {} */ // MODULES // var getPrototype = require( './get_prototype_of.js' ); // EXPORTS // module.exports = getPrototype; },{"./get_prototype_of.js":311}],313:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var getProto = Object.getPrototypeOf; // EXPORTS // module.exports = getProto; },{}],314:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var nativeClass = require( '@stdlib/utils/native-class' ); var getProto = require( './proto.js' ); // MAIN // /** * Returns the prototype of a provided object. * * @private * @param {Object} obj - input object * @returns {(Object|null)} prototype */ function getPrototypeOf( obj ) { var proto = getProto( obj ); if ( proto || proto === null ) { return proto; } if ( nativeClass( obj.constructor ) === '[object Function]' ) { // May break if the constructor has been tampered with... return obj.constructor.prototype; } if ( obj instanceof Object ) { return Object.prototype; } // Return `null` for objects created via `Object.create( null )`. Also return `null` for cross-realm objects on browsers that lack `__proto__` support, such as IE < 11. return null; } // EXPORTS // module.exports = getPrototypeOf; },{"./proto.js":315,"@stdlib/utils/native-class":346}],315:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Returns the value of the `__proto__` property. * * @private * @param {Object} obj - input object * @returns {*} value of `__proto__` property */ function getProto( obj ) { // eslint-disable-next-line no-proto return obj.__proto__; } // EXPORTS // module.exports = getProto; },{}],316:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Returns the global object using code generation. * * @private * @returns {Object} global object */ function getGlobal() { return new Function( 'return this;' )(); // eslint-disable-line no-new-func } // EXPORTS // module.exports = getGlobal; },{}],317:[function(require,module,exports){ (function (global){(function (){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var obj = ( typeof global === 'object' ) ? global : null; // EXPORTS // module.exports = obj; }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],318:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return the global object. * * @module @stdlib/utils/global * * @example * var getGlobal = require( '@stdlib/utils/global' ); * * var g = getGlobal(); * // returns {...} */ // MODULES // var getGlobal = require( './main.js' ); // EXPORTS // module.exports = getGlobal; },{"./main.js":319}],319:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var getThis = require( './codegen.js' ); var Self = require( './self.js' ); var Win = require( './window.js' ); var Global = require( './global.js' ); // MAIN // /** * Returns the global object. * * ## Notes * * - Using code generation is the **most** reliable way to resolve the global object; however, doing so is likely to violate content security policies (CSPs) in, e.g., Chrome Apps and elsewhere. * * @param {boolean} [codegen=false] - boolean indicating whether to use code generation to resolve the global object * @throws {TypeError} must provide a boolean * @throws {Error} unable to resolve global object * @returns {Object} global object * * @example * var g = getGlobal(); * // returns {...} */ function getGlobal( codegen ) { if ( arguments.length ) { if ( !isBoolean( codegen ) ) { throw new TypeError( 'invalid argument. Must provide a boolean primitive. Value: `'+codegen+'`.' ); } if ( codegen ) { return getThis(); } // Fall through... } // Case: browsers and web workers if ( Self ) { return Self; } // Case: browsers if ( Win ) { return Win; } // Case: Node.js if ( Global ) { return Global; } // Case: unknown throw new Error( 'unexpected error. Unable to resolve global object.' ); } // EXPORTS // module.exports = getGlobal; },{"./codegen.js":316,"./global.js":317,"./self.js":320,"./window.js":321,"@stdlib/assert/is-boolean":72}],320:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var obj = ( typeof self === 'object' ) ? self : null; // EXPORTS // module.exports = obj; },{}],321:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var obj = ( typeof window === 'object' ) ? window : null; // EXPORTS // module.exports = obj; },{}],322:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return the first index at which a given element can be found. * * @module @stdlib/utils/index-of * * @example * var indexOf = require( '@stdlib/utils/index-of' ); * * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 3 ); * // returns 1 * * arr = [ 4, 3, 2, 1 ]; * idx = indexOf( arr, 5 ); * // returns -1 * * // Using a `fromIndex`: * arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * idx = indexOf( arr, 2, 3 ); * // returns 5 * * // `fromIndex` which exceeds `array` length: * arr = [ 1, 2, 3, 4, 2, 5 ]; * idx = indexOf( arr, 2, 10 ); * // returns -1 * * // Negative `fromIndex`: * arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ]; * idx = indexOf( arr, 2, -4 ); * // returns 5 * * idx = indexOf( arr, 2, -1 ); * // returns 7 * * // Negative `fromIndex` exceeding input `array` length: * arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * idx = indexOf( arr, 2, -10 ); * // returns 1 * * // Array-like objects: * var str = 'bebop'; * idx = indexOf( str, 'o' ); * // returns 3 */ // MODULES // var indexOf = require( './index_of.js' ); // EXPORTS // module.exports = indexOf; },{"./index_of.js":323}],323:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isnan = require( '@stdlib/assert/is-nan' ); var isCollection = require( '@stdlib/assert/is-collection' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // MAIN // /** * Returns the first index at which a given element can be found. * * @param {ArrayLike} arr - array-like object * @param {*} searchElement - element to find * @param {integer} [fromIndex] - starting index (if negative, the start index is determined relative to last element) * @throws {TypeError} must provide an array-like object * @throws {TypeError} `fromIndex` must be an integer * @returns {integer} index or -1 * * @example * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 3 ); * // returns 1 * * @example * var arr = [ 4, 3, 2, 1 ]; * var idx = indexOf( arr, 5 ); * // returns -1 * * @example * // Using a `fromIndex`: * var arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * var idx = indexOf( arr, 2, 3 ); * // returns 5 * * @example * // `fromIndex` which exceeds `array` length: * var arr = [ 1, 2, 3, 4, 2, 5 ]; * var idx = indexOf( arr, 2, 10 ); * // returns -1 * * @example * // Negative `fromIndex`: * var arr = [ 1, 2, 3, 4, 5, 2, 6, 2 ]; * var idx = indexOf( arr, 2, -4 ); * // returns 5 * * idx = indexOf( arr, 2, -1 ); * // returns 7 * * @example * // Negative `fromIndex` exceeding input `array` length: * var arr = [ 1, 2, 3, 4, 5, 2, 6 ]; * var idx = indexOf( arr, 2, -10 ); * // returns 1 * * @example * // Array-like objects: * var str = 'bebop'; * var idx = indexOf( str, 'o' ); * // returns 3 */ function indexOf( arr, searchElement, fromIndex ) { var len; var i; if ( !isCollection( arr ) && !isString( arr ) ) { throw new TypeError( 'invalid argument. First argument must be an array-like object. Value: `' + arr + '`.' ); } len = arr.length; if ( len === 0 ) { return -1; } if ( arguments.length === 3 ) { if ( !isInteger( fromIndex ) ) { throw new TypeError( 'invalid argument. `fromIndex` must be an integer. Value: `' + fromIndex + '`.' ); } if ( fromIndex >= 0 ) { if ( fromIndex >= len ) { return -1; } i = fromIndex; } else { i = len + fromIndex; if ( i < 0 ) { i = 0; } } } else { i = 0; } // Check for `NaN`... if ( isnan( searchElement ) ) { for ( ; i < len; i++ ) { if ( isnan( arr[i] ) ) { return i; } } } else { for ( ; i < len; i++ ) { if ( arr[ i ] === searchElement ) { return i; } } } return -1; } // EXPORTS // module.exports = indexOf; },{"@stdlib/assert/is-collection":81,"@stdlib/assert/is-integer":101,"@stdlib/assert/is-nan":109,"@stdlib/assert/is-string":149}],324:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var builtin = require( './native.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var createObject; if ( typeof builtin === 'function' ) { createObject = builtin; } else { createObject = polyfill; } // EXPORTS // module.exports = createObject; },{"./native.js":327,"./polyfill.js":328}],325:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Implement prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor. * * @module @stdlib/utils/inherit * * @example * var inherit = require( '@stdlib/utils/inherit' ); * * function Foo() { * return this; * } * Foo.prototype.beep = function beep() { * return 'boop'; * }; * * function Bar() { * Foo.call( this ); * return this; * } * inherit( Bar, Foo ); * * var bar = new Bar(); * var v = bar.beep(); * // returns 'boop' */ // MODULES // var inherit = require( './inherit.js' ); // EXPORTS // module.exports = inherit; },{"./inherit.js":326}],326:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var defineProperty = require( '@stdlib/utils/define-property' ); var validate = require( './validate.js' ); var createObject = require( './detect.js' ); // MAIN // /** * Implements prototypical inheritance by replacing the prototype of one constructor with the prototype of another constructor. * * ## Notes * * - This implementation is not designed to work with ES2015/ES6 classes. For ES2015/ES6 classes, use `class` with `extends`. * - For reference, see [node#3455](https://github.com/nodejs/node/pull/3455), [node#4179](https://github.com/nodejs/node/issues/4179), [node#3452](https://github.com/nodejs/node/issues/3452), and [node commit](https://github.com/nodejs/node/commit/29da8cf8d7ab8f66b9091ab22664067d4468461e#diff-3deb3f32958bb937ae05c6f3e4abbdf5). * * * @param {(Object|Function)} ctor - constructor which will inherit * @param {(Object|Function)} superCtor - super (parent) constructor * @throws {TypeError} first argument must be either an object or a function which can inherit * @throws {TypeError} second argument must be either an object or a function from which a constructor can inherit * @throws {TypeError} second argument must have an inheritable prototype * @returns {(Object|Function)} child constructor * * @example * function Foo() { * return this; * } * Foo.prototype.beep = function beep() { * return 'boop'; * }; * * function Bar() { * Foo.call( this ); * return this; * } * inherit( Bar, Foo ); * * var bar = new Bar(); * var v = bar.beep(); * // returns 'boop' */ function inherit( ctor, superCtor ) { var err = validate( ctor ); if ( err ) { throw err; } err = validate( superCtor ); if ( err ) { throw err; } if ( typeof superCtor.prototype === 'undefined' ) { throw new TypeError( 'invalid argument. Second argument must have a prototype from which another object can inherit. Value: `'+superCtor.prototype+'`.' ); } // Create a prototype which inherits from the parent prototype: ctor.prototype = createObject( superCtor.prototype ); // Set the constructor to refer to the child constructor: defineProperty( ctor.prototype, 'constructor', { 'configurable': true, 'enumerable': false, 'writable': true, 'value': ctor }); return ctor; } // EXPORTS // module.exports = inherit; },{"./detect.js":324,"./validate.js":329,"@stdlib/utils/define-property":302}],327:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // EXPORTS // module.exports = Object.create; },{}],328:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // FUNCTIONS // /** * Dummy constructor. * * @private */ function Ctor() { // Empty... } // MAIN // /** * An `Object.create` shim for older JavaScript engines. * * @private * @param {Object} proto - prototype * @returns {Object} created object * * @example * var obj = createObject( Object.prototype ); * // returns {} */ function createObject( proto ) { Ctor.prototype = proto; return new Ctor(); } // EXPORTS // module.exports = createObject; },{}],329:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Tests that a value is a valid constructor. * * @private * @param {*} value - value to test * @returns {(Error|null)} error object or null * * @example * var ctor = function ctor() {}; * * var err = validate( ctor ); * // returns null * * err = validate( null ); * // returns <TypeError> */ function validate( value ) { var type = typeof value; if ( value === null || (type !== 'object' && type !== 'function') ) { return new TypeError( 'invalid argument. A provided constructor must be either an object (except null) or a function. Value: `'+value+'`.' ); } return null; } // EXPORTS // module.exports = validate; },{}],330:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Returns an array of an object's own enumerable property names. * * ## Notes * * - In contrast to the built-in `Object.keys()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error. * * @private * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function keys( value ) { return Object.keys( Object( value ) ); } // EXPORTS // module.exports = keys; },{}],331:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isArguments = require( '@stdlib/assert/is-arguments' ); var builtin = require( './builtin.js' ); // VARIABLES // var slice = Array.prototype.slice; // MAIN // /** * Returns an array of an object's own enumerable property names. * * @private * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function keys( value ) { if ( isArguments( value ) ) { return builtin( slice.call( value ) ); } return builtin( value ); } // EXPORTS // module.exports = keys; },{"./builtin.js":330,"@stdlib/assert/is-arguments":65}],332:[function(require,module,exports){ module.exports=[ "console", "external", "frame", "frameElement", "frames", "innerHeight", "innerWidth", "outerHeight", "outerWidth", "pageXOffset", "pageYOffset", "parent", "scrollLeft", "scrollTop", "scrollX", "scrollY", "self", "webkitIndexedDB", "webkitStorageInfo", "window" ] },{}],333:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var keys = require( './builtin.js' ); // FUNCTIONS // /** * Tests the built-in `Object.keys()` implementation when provided `arguments`. * * @private * @returns {boolean} boolean indicating whether the built-in implementation returns the expected number of keys */ function test() { return ( keys( arguments ) || '' ).length !== 2; } // MAIN // /** * Tests whether the built-in `Object.keys()` implementation supports providing `arguments` as an input value. * * ## Notes * * - Safari 5.0 does **not** support `arguments` as an input value. * * @private * @returns {boolean} boolean indicating whether a built-in implementation supports `arguments` */ function check() { return test( 1, 2 ); } // EXPORTS // module.exports = check; },{"./builtin.js":330}],334:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var indexOf = require( '@stdlib/utils/index-of' ); var typeOf = require( '@stdlib/utils/type-of' ); var isConstructorPrototype = require( './is_constructor_prototype.js' ); var EXCLUDED_KEYS = require( './excluded_keys.json' ); var win = require( './window.js' ); // VARIABLES // var bool; // FUNCTIONS // /** * Determines whether an environment throws when comparing to the prototype of a value's constructor (e.g., [IE9][1]). * * [1]: https://stackoverflow.com/questions/7688070/why-is-comparing-the-constructor-property-of-two-windows-unreliable * * @private * @returns {boolean} boolean indicating whether an environment is buggy */ function check() { var k; if ( typeOf( win ) === 'undefined' ) { return false; } for ( k in win ) { // eslint-disable-line guard-for-in try { if ( indexOf( EXCLUDED_KEYS, k ) === -1 && hasOwnProp( win, k ) && win[ k ] !== null && typeOf( win[ k ] ) === 'object' ) { isConstructorPrototype( win[ k ] ); } } catch ( err ) { // eslint-disable-line no-unused-vars return true; } } return false; } // MAIN // bool = check(); // EXPORTS // module.exports = bool; },{"./excluded_keys.json":332,"./is_constructor_prototype.js":340,"./window.js":345,"@stdlib/assert/has-own-property":46,"@stdlib/utils/index-of":322,"@stdlib/utils/type-of":373}],335:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var bool = ( typeof Object.keys !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],336:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); var noop = require( '@stdlib/utils/noop' ); // MAIN // // Note: certain environments treat an object's prototype as enumerable, which, as a matter of convention, it shouldn't be... var bool = isEnumerableProperty( noop, 'prototype' ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-enumerable-property":84,"@stdlib/utils/noop":353}],337:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isEnumerableProperty = require( '@stdlib/assert/is-enumerable-property' ); // VARIABLES // var obj = { 'toString': null }; // MAIN // // Note: certain environments don't allow enumeration of overwritten properties which are considered non-enumerable... var bool = !isEnumerableProperty( obj, 'toString' ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-enumerable-property":84}],338:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var bool = ( typeof window !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],339:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return an array of an object's own enumerable property names. * * @module @stdlib/utils/keys * * @example * var keys = require( '@stdlib/utils/keys' ); * * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ // MODULES // var keys = require( './main.js' ); // EXPORTS // module.exports = keys; },{"./main.js":342}],340:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // /** * Tests whether a value equals the prototype of its constructor. * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value equals the prototype of its constructor */ function isConstructorPrototype( value ) { return ( value.constructor && value.constructor.prototype === value ); } // EXPORTS // module.exports = isConstructorPrototype; },{}],341:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasAutomationEqualityBug = require( './has_automation_equality_bug.js' ); var isConstructorPrototype = require( './is_constructor_prototype.js' ); var HAS_WINDOW = require( './has_window.js' ); // MAIN // /** * Wraps the test for constructor prototype equality to accommodate buggy environments (e.g., environments which throw when testing equality). * * @private * @param {*} value - value to test * @returns {boolean} boolean indicating whether a value equals the prototype of its constructor */ function wrapper( value ) { if ( HAS_WINDOW === false && !hasAutomationEqualityBug ) { return isConstructorPrototype( value ); } try { return isConstructorPrototype( value ); } catch ( error ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = wrapper; },{"./has_automation_equality_bug.js":334,"./has_window.js":338,"./is_constructor_prototype.js":340}],342:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasArgumentsBug = require( './has_arguments_bug.js' ); var HAS_BUILTIN = require( './has_builtin.js' ); var builtin = require( './builtin.js' ); var wrapper = require( './builtin_wrapper.js' ); var polyfill = require( './polyfill.js' ); // MAIN // /** * Returns an array of an object's own enumerable property names. * * @name keys * @type {Function} * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ var keys; if ( HAS_BUILTIN ) { if ( hasArgumentsBug() ) { keys = wrapper; } else { keys = builtin; } } else { keys = polyfill; } // EXPORTS // module.exports = keys; },{"./builtin.js":330,"./builtin_wrapper.js":331,"./has_arguments_bug.js":333,"./has_builtin.js":335,"./polyfill.js":344}],343:[function(require,module,exports){ module.exports=[ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ] },{}],344:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isObjectLike = require( '@stdlib/assert/is-object-like' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isArguments = require( '@stdlib/assert/is-arguments' ); var HAS_ENUM_PROTO_BUG = require( './has_enumerable_prototype_bug.js' ); var HAS_NON_ENUM_PROPS_BUG = require( './has_non_enumerable_properties_bug.js' ); var isConstructorPrototype = require( './is_constructor_prototype_wrapper.js' ); var NON_ENUMERABLE = require( './non_enumerable.json' ); // MAIN // /** * Returns an array of an object's own enumerable property names. * * @private * @param {*} value - input object * @returns {Array} a list of own enumerable property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var k = keys( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function keys( value ) { var skipConstructor; var skipPrototype; var isFcn; var out; var k; var p; var i; out = []; if ( isArguments( value ) ) { // Account for environments which treat `arguments` differently... for ( i = 0; i < value.length; i++ ) { out.push( i.toString() ); } // Note: yes, we are precluding the `arguments` array-like object from having other enumerable properties; however, this should (1) be very rare and (2) not be encouraged (e.g., doing something like `arguments.a = 'b'`; in certain engines directly manipulating the `arguments` value results in automatic de-optimization). return out; } if ( typeof value === 'string' ) { // Account for environments which do not treat string character indices as "own" properties... if ( value.length > 0 && !hasOwnProp( value, '0' ) ) { for ( i = 0; i < value.length; i++ ) { out.push( i.toString() ); } } } else { isFcn = ( typeof value === 'function' ); if ( isFcn === false && !isObjectLike( value ) ) { return out; } skipPrototype = ( HAS_ENUM_PROTO_BUG && isFcn ); } for ( k in value ) { if ( !( skipPrototype && k === 'prototype' ) && hasOwnProp( value, k ) ) { out.push( String( k ) ); } } if ( HAS_NON_ENUM_PROPS_BUG ) { skipConstructor = isConstructorPrototype( value ); for ( i = 0; i < NON_ENUMERABLE.length; i++ ) { p = NON_ENUMERABLE[ i ]; if ( !( skipConstructor && p === 'constructor' ) && hasOwnProp( value, p ) ) { out.push( String( p ) ); } } } return out; } // EXPORTS // module.exports = keys; },{"./has_enumerable_prototype_bug.js":336,"./has_non_enumerable_properties_bug.js":337,"./is_constructor_prototype_wrapper.js":341,"./non_enumerable.json":343,"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-arguments":65,"@stdlib/assert/is-object-like":134}],345:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var w = ( typeof window === 'undefined' ) ? void 0 : window; // EXPORTS // module.exports = w; },{}],346:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a string value indicating a specification defined classification of an object. * * @module @stdlib/utils/native-class * * @example * var nativeClass = require( '@stdlib/utils/native-class' ); * * var str = nativeClass( 'a' ); * // returns '[object String]' * * str = nativeClass( 5 ); * // returns '[object Number]' * * function Beep() { * return this; * } * str = nativeClass( new Beep() ); * // returns '[object Object]' */ // MODULES // var hasToStringTag = require( '@stdlib/assert/has-tostringtag-support' ); var builtin = require( './native_class.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var nativeClass; if ( hasToStringTag() ) { nativeClass = polyfill; } else { nativeClass = builtin; } // EXPORTS // module.exports = nativeClass; },{"./native_class.js":347,"./polyfill.js":348,"@stdlib/assert/has-tostringtag-support":50}],347:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var toStr = require( './tostring.js' ); // MAIN // /** * Returns a string value indicating a specification defined classification (via the internal property `[[Class]]`) of an object. * * @param {*} v - input value * @returns {string} string value indicating a specification defined classification of the input value * * @example * var str = nativeClass( 'a' ); * // returns '[object String]' * * @example * var str = nativeClass( 5 ); * // returns '[object Number]' * * @example * function Beep() { * return this; * } * var str = nativeClass( new Beep() ); * // returns '[object Object]' */ function nativeClass( v ) { return toStr.call( v ); } // EXPORTS // module.exports = nativeClass; },{"./tostring.js":349}],348:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var toStringTag = require( './tostringtag.js' ); var toStr = require( './tostring.js' ); // MAIN // /** * Returns a string value indicating a specification defined classification of an object in environments supporting `Symbol.toStringTag`. * * @param {*} v - input value * @returns {string} string value indicating a specification defined classification of the input value * * @example * var str = nativeClass( 'a' ); * // returns '[object String]' * * @example * var str = nativeClass( 5 ); * // returns '[object Number]' * * @example * function Beep() { * return this; * } * var str = nativeClass( new Beep() ); * // returns '[object Object]' */ function nativeClass( v ) { var isOwn; var tag; var out; if ( v === null || v === void 0 ) { return toStr.call( v ); } tag = v[ toStringTag ]; isOwn = hasOwnProp( v, toStringTag ); // Attempt to override the `toStringTag` property. For built-ins having a `Symbol.toStringTag` property (e.g., `JSON`, `Math`, etc), the `Symbol.toStringTag` property is read-only (e.g., , so we need to wrap in a `try/catch`. try { v[ toStringTag ] = void 0; } catch ( err ) { // eslint-disable-line no-unused-vars return toStr.call( v ); } out = toStr.call( v ); if ( isOwn ) { v[ toStringTag ] = tag; } else { delete v[ toStringTag ]; } return out; } // EXPORTS // module.exports = nativeClass; },{"./tostring.js":349,"./tostringtag.js":350,"@stdlib/assert/has-own-property":46}],349:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var toStr = Object.prototype.toString; // EXPORTS // module.exports = toStr; },{}],350:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var toStrTag = ( typeof Symbol === 'function' ) ? Symbol.toStringTag : ''; // EXPORTS // module.exports = toStrTag; },{}],351:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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'; /** * Add a callback to the "next tick queue". * * @module @stdlib/utils/next-tick * * @example * var nextTick = require( '@stdlib/utils/next-tick' ); * * function beep() { * console.log( 'boop' ); * } * * nextTick( beep ); */ // MODULES // var nextTick = require( './main.js' ); // EXPORTS // module.exports = nextTick; },{"./main.js":352}],352:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * 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'; // MODULES // var proc = require( 'process' ); // MAIN // /** * Adds a callback to the "next tick queue". * * ## Notes * * - The queue is fully drained after the current operation on the JavaScript stack runs to completion and before the event loop is allowed to continue. * * @param {Callback} clbk - callback * @param {...*} [args] - arguments to provide to the callback upon invocation * * @example * function beep() { * console.log( 'boop' ); * } * * nextTick( beep ); */ function nextTick( clbk ) { var args; var i; args = []; for ( i = 1; i < arguments.length; i++ ) { args.push( arguments[ i ] ); } proc.nextTick( wrapper ); /** * Callback wrapper. * * ## Notes * * - The ability to provide additional arguments was added in Node.js v1.8.1. The wrapper provides support for earlier Node.js versions. * * @private */ function wrapper() { clbk.apply( null, args ); } } // EXPORTS // module.exports = nextTick; },{"process":389}],353:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * No operation. * * @module @stdlib/utils/noop * * @example * var noop = require( '@stdlib/utils/noop' ); * * noop(); * // ...does nothing. */ // MODULES // var noop = require( './noop.js' ); // EXPORTS // module.exports = noop; },{"./noop.js":354}],354:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * No operation. * * @example * noop(); * // ...does nothing. */ function noop() { // Empty function... } // EXPORTS // module.exports = noop; },{}],355:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a partial object copy excluding specified keys. * * @module @stdlib/utils/omit * * @example * var omit = require( '@stdlib/utils/omit' ); * * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = omit( obj1, 'b' ); * // returns { 'a': 1 } */ // MODULES // var omit = require( './omit.js' ); // EXPORTS // module.exports = omit; },{"./omit.js":356}],356:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var objectKeys = require( '@stdlib/utils/keys' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; var indexOf = require( '@stdlib/utils/index-of' ); // MAIN // /** * Returns a partial object copy excluding specified keys. * * @param {Object} obj - source object * @param {(string|StringArray)} keys - keys to exclude * @throws {TypeError} first argument must be an object * @throws {TypeError} second argument must be either a string or an array of strings * @returns {Object} new object * * @example * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = omit( obj1, 'b' ); * // returns { 'a': 1 } */ function omit( obj, keys ) { var ownKeys; var out; var key; var i; if ( typeof obj !== 'object' || obj === null ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); } ownKeys = objectKeys( obj ); out = {}; if ( isString( keys ) ) { for ( i = 0; i < ownKeys.length; i++ ) { key = ownKeys[ i ]; if ( key !== keys ) { out[ key ] = obj[ key ]; } } return out; } if ( isStringArray( keys ) ) { for ( i = 0; i < ownKeys.length; i++ ) { key = ownKeys[ i ]; if ( indexOf( keys, key ) === -1 ) { out[ key ] = obj[ key ]; } } return out; } throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); } // EXPORTS // module.exports = omit; },{"@stdlib/assert/is-string":149,"@stdlib/assert/is-string-array":148,"@stdlib/utils/index-of":322,"@stdlib/utils/keys":339}],357:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a partial object copy containing only specified keys. * * @module @stdlib/utils/pick * * @example * var pick = require( '@stdlib/utils/pick' ); * * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = pick( obj1, 'b' ); * // returns { 'b': 2 } */ // MODULES // var pick = require( './pick.js' ); // EXPORTS // module.exports = pick; },{"./pick.js":358}],358:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored. * * @param {Object} obj - source object * @param {(string|StringArray)} keys - keys to copy * @throws {TypeError} first argument must be an object * @throws {TypeError} second argument must be either a string or an array of strings * @returns {Object} new object * * @example * var obj1 = { * 'a': 1, * 'b': 2 * }; * * var obj2 = pick( obj1, 'b' ); * // returns { 'b': 2 } */ function pick( obj, keys ) { var out; var key; var i; if ( typeof obj !== 'object' || obj === null ) { throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); } out = {}; if ( isString( keys ) ) { if ( hasOwnProp( obj, keys ) ) { out[ keys ] = obj[ keys ]; } return out; } if ( isStringArray( keys ) ) { for ( i = 0; i < keys.length; i++ ) { key = keys[ i ]; if ( hasOwnProp( obj, key ) ) { out[ key ] = obj[ key ]; } } return out; } throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); } // EXPORTS // module.exports = pick; },{"@stdlib/assert/has-own-property":46,"@stdlib/assert/is-string":149,"@stdlib/assert/is-string-array":148}],359:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // VARIABLES // var propertyDescriptor = Object.getOwnPropertyDescriptor; // MAIN // /** * Returns a property descriptor for an object's own property. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error. * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`. * * @private * @param {*} value - input object * @param {(string|symbol)} property - property * @returns {(Object|null)} property descriptor or null * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var desc = getOwnPropertyDescriptor( obj, 'foo' ); * // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14} */ function getOwnPropertyDescriptor( value, property ) { var desc; if ( value === null || value === void 0 ) { return null; } desc = propertyDescriptor( value, property ); return ( desc === void 0 ) ? null : desc; } // EXPORTS // module.exports = getOwnPropertyDescriptor; },{}],360:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var bool = ( typeof Object.getOwnPropertyDescriptor !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],361:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return a property descriptor for an object's own property. * * @module @stdlib/utils/property-descriptor * * @example * var getOwnPropertyDescriptor = require( '@stdlib/utils/property-descriptor' ); * * var obj = { * 'foo': 'bar', * 'beep': 'boop' * }; * * var keys = getOwnPropertyDescriptor( obj, 'foo' ); * // returns {'configurable':true,'enumerable':true,'writable':true,'value':'bar'} */ // MODULES // var HAS_BUILTIN = require( './has_builtin.js' ); var builtin = require( './builtin.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var main; if ( HAS_BUILTIN ) { main = builtin; } else { main = polyfill; } // EXPORTS // module.exports = main; },{"./builtin.js":359,"./has_builtin.js":360,"./polyfill.js":362}],362:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var hasOwnProp = require( '@stdlib/assert/has-own-property' ); // MAIN // /** * Returns a property descriptor for an object's own property. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if provided `undefined` or `null`, rather than throwing an error. * - In contrast to the built-in `Object.getOwnPropertyDescriptor()`, this function returns `null` if an object does not have a provided property, rather than `undefined`. * - In environments lacking `Object.getOwnPropertyDescriptor()` support, property descriptors do not exist. In non-supporting environment, if an object has a provided property, this function returns a descriptor object equivalent to that returned in a supporting environment; otherwise, the function returns `null`. * * @private * @param {*} value - input object * @param {(string|symbol)} property - property * @returns {(Object|null)} property descriptor or null * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var desc = getOwnPropertyDescriptor( obj, 'foo' ); * // returns {'configurable':true,'enumerable':true,'writable':true,'value':3.14} */ function getOwnPropertyDescriptor( value, property ) { if ( hasOwnProp( value, property ) ) { return { 'configurable': true, 'enumerable': true, 'writable': true, 'value': value[ property ] }; } return null; } // EXPORTS // module.exports = getOwnPropertyDescriptor; },{"@stdlib/assert/has-own-property":46}],363:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // VARIABLES // var propertyNames = Object.getOwnPropertyNames; // MAIN // /** * Returns an array of an object's own enumerable and non-enumerable property names. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error. * * @private * @param {*} value - input object * @returns {Array} a list of own property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var keys = getOwnPropertyNames( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function getOwnPropertyNames( value ) { return propertyNames( Object( value ) ); } // EXPORTS // module.exports = getOwnPropertyNames; },{}],364:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MAIN // var bool = ( typeof Object.getOwnPropertyNames !== 'undefined' ); // EXPORTS // module.exports = bool; },{}],365:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Return an array of an object's own enumerable and non-enumerable property names. * * @module @stdlib/utils/property-names * * @example * var getOwnPropertyNames = require( '@stdlib/utils/property-names' ); * * var keys = getOwnPropertyNames({ * 'foo': 'bar', * 'beep': 'boop' * }); * // e.g., returns [ 'foo', 'beep' ] */ // MODULES // var HAS_BUILTIN = require( './has_builtin.js' ); var builtin = require( './builtin.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var main; if ( HAS_BUILTIN ) { main = builtin; } else { main = polyfill; } // EXPORTS // module.exports = main; },{"./builtin.js":363,"./has_builtin.js":364,"./polyfill.js":366}],366:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var keys = require( '@stdlib/utils/keys' ); // MAIN // /** * Returns an array of an object's own enumerable and non-enumerable property names. * * ## Notes * * - In contrast to the built-in `Object.getOwnPropertyNames()`, this function returns an empty array if provided `undefined` or `null`, rather than throwing an error. * - In environments lacking support for `Object.getOwnPropertyNames()`, property descriptors are unavailable, and thus all properties can be safely assumed to be enumerable. Hence, we can defer to calling `Object.keys`, which retrieves all own enumerable property names. * * @private * @param {*} value - input object * @returns {Array} a list of own property names * * @example * var obj = { * 'beep': 'boop', * 'foo': 3.14 * }; * * var keys = getOwnPropertyNames( obj ); * // e.g., returns [ 'beep', 'foo' ] */ function getOwnPropertyNames( value ) { return keys( Object( value ) ); } // EXPORTS // module.exports = getOwnPropertyNames; },{"@stdlib/utils/keys":339}],367:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var reRegExp = require( '@stdlib/regexp/regexp' ); // MAIN // /** * Parses a regular expression string and returns a new regular expression. * * @param {string} str - regular expression string * @throws {TypeError} must provide a regular expression string * @returns {(RegExp|null)} regular expression or null * * @example * var re = reFromString( '/beep/' ); * // returns /beep/ */ function reFromString( str ) { if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a regular expression string. Value: `' + str + '`.' ); } // Capture the regular expression pattern and any flags: str = reRegExp().exec( str ); // Create a new regular expression: return ( str ) ? new RegExp( str[1], str[2] ) : null; } // EXPORTS // module.exports = reFromString; },{"@stdlib/assert/is-string":149,"@stdlib/regexp/regexp":265}],368:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Create a regular expression from a regular expression string. * * @module @stdlib/utils/regexp-from-string * * @example * var reFromString = require( '@stdlib/utils/regexp-from-string' ); * * var re = reFromString( '/beep/' ); * // returns /beep/ */ // MODULES // var reFromString = require( './from_string.js' ); // EXPORTS // module.exports = reFromString; },{"./from_string.js":367}],369:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var RE = require( './fixtures/re.js' ); var nodeList = require( './fixtures/nodelist.js' ); var typedarray = require( './fixtures/typedarray.js' ); // MAIN // /** * Checks whether a polyfill is needed when using the `typeof` operator. * * @private * @returns {boolean} boolean indicating whether a polyfill is needed */ function check() { if ( // Chrome 1-12 returns 'function' for regular expression instances (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof): typeof RE === 'function' || // Safari 8 returns 'object' for typed array and weak map constructors (underscore #1929): typeof typedarray === 'object' || // PhantomJS 1.9 returns 'function' for `NodeList` instances (underscore #2236): typeof nodeList === 'function' ) { return true; } return false; } // EXPORTS // module.exports = check; },{"./fixtures/nodelist.js":370,"./fixtures/re.js":371,"./fixtures/typedarray.js":372}],370:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var getGlobal = require( '@stdlib/utils/global' ); // MAIN // var root = getGlobal(); var nodeList = root.document && root.document.childNodes; // EXPORTS // module.exports = nodeList; },{"@stdlib/utils/global":318}],371:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; var RE = /./; // EXPORTS // module.exports = RE; },{}],372:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; var typedarray = Int8Array; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = typedarray; },{}],373:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; /** * Determine a value's type. * * @module @stdlib/utils/type-of * * @example * var typeOf = require( '@stdlib/utils/type-of' ); * * var str = typeOf( 'a' ); * // returns 'string' * * str = typeOf( 5 ); * // returns 'number' */ // MODULES // var usePolyfill = require( './check.js' ); var typeOf = require( './typeof.js' ); var polyfill = require( './polyfill.js' ); // MAIN // var main = ( usePolyfill() ) ? polyfill : typeOf; // EXPORTS // module.exports = main; },{"./check.js":369,"./polyfill.js":374,"./typeof.js":375}],374:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var ctorName = require( '@stdlib/utils/constructor-name' ); // MAIN // /** * Determines a value's type. * * @param {*} v - input value * @returns {string} string indicating the value's type */ function typeOf( v ) { return ctorName( v ).toLowerCase(); } // EXPORTS // module.exports = typeOf; },{"@stdlib/utils/constructor-name":289}],375:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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'; // MODULES // var ctorName = require( '@stdlib/utils/constructor-name' ); // NOTES // /* * Built-in `typeof` operator behavior: * * ```text * typeof null => 'object' * typeof undefined => 'undefined' * typeof 'a' => 'string' * typeof 5 => 'number' * typeof NaN => 'number' * typeof true => 'boolean' * typeof false => 'boolean' * typeof {} => 'object' * typeof [] => 'object' * typeof function foo(){} => 'function' * typeof function* foo(){} => 'object' * typeof Symbol() => 'symbol' * ``` * */ // MAIN // /** * Determines a value's type. * * @param {*} v - input value * @returns {string} string indicating the value's type */ function typeOf( v ) { var type; // Address `typeof null` => `object` (see http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null): if ( v === null ) { return 'null'; } type = typeof v; // If the `typeof` operator returned something other than `object`, we are done. Otherwise, we need to check for an internal class name or search for a constructor. if ( type === 'object' ) { return ctorName( v ).toLowerCase(); } return type; } // EXPORTS // module.exports = typeOf; },{"@stdlib/utils/constructor-name":289}],376:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } // Support decoding URL-safe base64 strings, as Node.js does. // See: https://en.wikipedia.org/wiki/Base64#URL_applications revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function getLens (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen = b64.indexOf('=') if (validLen === -1) validLen = len var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4) return [validLen, placeHoldersLen] } // base64 is 4/3 + up to two characters of the original data function byteLength (b64) { var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function _byteLength (b64, validLen, placeHoldersLen) { return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen } function toByteArray (b64) { var tmp var lens = getLens(b64) var validLen = lens[0] var placeHoldersLen = lens[1] var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) var curByte = 0 // if there are placeholders, only get up to the last complete 4 chars var len = placeHoldersLen > 0 ? validLen - 4 : validLen var i for (i = 0; i < len; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[curByte++] = (tmp >> 16) & 0xFF arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[curByte++] = tmp & 0xFF } if (placeHoldersLen === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[curByte++] = (tmp >> 8) & 0xFF arr[curByte++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] parts.push( lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3F] + '==' ) } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1] parts.push( lookup[tmp >> 10] + lookup[(tmp >> 4) & 0x3F] + lookup[(tmp << 2) & 0x3F] + '=' ) } return parts.join('') } },{}],377:[function(require,module,exports){ },{}],378:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var R = typeof Reflect === 'object' ? Reflect : null var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); } var ReflectOwnKeys if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; } function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; module.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === 'function') { emitter.removeListener('error', errorListener); } resolve([].slice.call(arguments)); }; eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error') { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { // EventTarget does not have `error` event semantics like Node // EventEmitters, we do not listen for `error` events here. emitter.addEventListener(name, function wrapListener(arg) { // IE does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } },{}],379:[function(require,module,exports){ (function (Buffer){(function (){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayLike(value) } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } var valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } var b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length ) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return b != null && b._isBuffer === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf) } if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } var len = string.length var mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 } encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (numberIsNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } var strLen = string.length if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset >>> 0 if (isFinite(length)) { length = length >>> 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 byteLength = byteLength >>> 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { var limit = Math.pow(2, (8 * byteLength) - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('Index out of range') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } if (val.length === 1) { var code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding) var len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g function base64clean (str) { // Node takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } }).call(this)}).call(this,require("buffer").Buffer) },{"base64-js":376,"buffer":379,"ieee754":383}],380:[function(require,module,exports){ (function (Buffer){(function (){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":385}],381:[function(require,module,exports){ (function (process){(function (){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } }).call(this)}).call(this,require('_process')) },{"./debug":382,"_process":389}],382:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":387}],383:[function(require,module,exports){ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = (nBytes * 8) - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = ((value * c) - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],384:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } },{}],385:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],386:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],387:[function(require,module,exports){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } },{}],388:[function(require,module,exports){ (function (process){(function (){ 'use strict'; if (typeof process === 'undefined' || !process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; } else { module.exports = process } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this)}).call(this,require('_process')) },{"_process":389}],389:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],390:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /*</replacement>*/ module.exports = Duplex; /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); { // avoid scope creep, the keys array can then be collected var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; },{"./_stream_readable":392,"./_stream_writable":394,"core-util-is":380,"inherits":384,"process-nextick-args":388}],391:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":393,"core-util-is":380,"inherits":384}],392:[function(require,module,exports){ (function (process,global){(function (){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ module.exports = Readable; /*<replacement>*/ var isArray = require('isarray'); /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Readable.ReadableState = ReadableState; /*<replacement>*/ var EE = require('events').EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var debugUtil = require('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /*</replacement>*/ var BufferList = require('./internal/streams/BufferList'); var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; pna.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, unpipeInfo); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; pna.nextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._readableState.highWaterMark; } }); // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; pna.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":390,"./internal/streams/BufferList":395,"./internal/streams/destroy":396,"./internal/streams/stream":397,"_process":389,"core-util-is":380,"events":378,"inherits":384,"isarray":386,"process-nextick-args":388,"safe-buffer":399,"string_decoder/":400,"util":377}],393:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":390,"core-util-is":380,"inherits":384}],394:[function(require,module,exports){ (function (process,global,setImmediate){(function (){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ module.exports = Writable; /* <replacement> */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* </replacement> */ /*<replacement>*/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var util = Object.create(require('core-util-is')); util.inherits = require('inherits'); /*</replacement>*/ /*<replacement>*/ var internalUtil = { deprecate: require('util-deprecate') }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /*</replacement>*/ var destroyImpl = require('./internal/streams/destroy'); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); pna.nextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /*<replacement>*/ asyncWrite(afterWrite, stream, state, finished, cb); /*</replacement>*/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = corkReq; } else { state.corkedRequestsFree = corkReq; } } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) },{"./_stream_duplex":390,"./internal/streams/destroy":396,"./internal/streams/stream":397,"_process":389,"core-util-is":380,"inherits":384,"process-nextick-args":388,"safe-buffer":399,"timers":401,"util-deprecate":402}],395:[function(require,module,exports){ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = require('safe-buffer').Buffer; var util = require('util'); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } },{"safe-buffer":399,"util":377}],396:[function(require,module,exports){ 'use strict'; /*<replacement>*/ var pna = require('process-nextick-args'); /*</replacement>*/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { pna.nextTick(emitErrorNT, this, err); } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { pna.nextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":388}],397:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":378}],398:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":390,"./lib/_stream_passthrough.js":391,"./lib/_stream_readable.js":392,"./lib/_stream_transform.js":393,"./lib/_stream_writable.js":394}],399:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":379}],400:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /*<replacement>*/ var Buffer = require('safe-buffer').Buffer; /*</replacement>*/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":399}],401:[function(require,module,exports){ (function (setImmediate,clearImmediate){(function (){ var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { if (immediateIds[id]) { // fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu if (args) { fn.apply(null, args); } else { fn.call(null); } // Prevent ids from leaking exports.clearImmediate(id); } }); return id; }; exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { delete immediateIds[id]; }; }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) },{"process/browser.js":389,"timers":401}],402:[function(require,module,exports){ (function (global){(function (){ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}]},{},[306]);
stdlib-js/www
public/docs/api/latest/@stdlib/utils/every-by/benchmark_bundle.js
JavaScript
apache-2.0
750,474
google.maps.__gjsload__('drawing', '\'use strict\';function Hj(a){var b=this;a=a||{};a.drawingMode=a.drawingMode||l;b[ub](a);Mf(Re,function(a){new a.b(b)})}L(Hj,T);ig(Hj[H],{map:ye(vg),drawingMode:Ee});Jf.drawing=function(a){eval(a)};dd.google.maps.drawing={DrawingManager:Hj,OverlayType:{MARKER:"marker",POLYGON:"polygon",POLYLINE:"polyline",RECTANGLE:"rectangle",CIRCLE:"circle"}};Nf("drawing",{});\n')
39mi/jtd
WebRoot/mapfiles/api-3/13/1/drawing.js
JavaScript
apache-2.0
404
/** * echarts组件:孤岛数据 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author Kener (@Kener-林峰, [email protected]) * */ define(function (require) { /** * 构造函数 * @param {Object} messageCenter echart消息中心 * @param {ZRender} zr zrender实例 * @param {Object} option 图表选项 */ function Island(messageCenter, zr) { // 基类装饰 var ComponentBase = require('../component/base'); ComponentBase.call(this, zr); // 可计算特性装饰 var CalculableBase = require('./calculableBase'); CalculableBase.call(this, zr); var ecConfig = require('../config'); var ecData = require('../util/ecData'); var zrEvent = require('zrender/tool/event'); var self = this; self.type = ecConfig.CHART_TYPE_ISLAND; var option; var _zlevelBase = self.getZlevelBase(); var _nameConnector; var _valueConnector; var _zrHeight = zr.getHeight(); var _zrWidth = zr.getWidth(); /** * 孤岛合并 * * @param {string} tarShapeIndex 目标索引 * @param {Object} srcShape 源目标,合入目标后删除 */ function _combine(tarShape, srcShape) { var zrColor = require('zrender/tool/color'); var value = ecData.get(tarShape, 'value') + ecData.get(srcShape, 'value'); var name = ecData.get(tarShape, 'name') + _nameConnector + ecData.get(srcShape, 'name'); tarShape.style.text = name + _valueConnector + value; ecData.set(tarShape, 'value', value); ecData.set(tarShape, 'name', name); tarShape.style.r = option.island.r; tarShape.style.color = zrColor.mix( tarShape.style.color, srcShape.style.color ); } /** * 刷新 */ function refresh(newOption) { if (newOption) { newOption.island = self.reformOption(newOption.island); option = newOption; _nameConnector = option.nameConnector; _valueConnector = option.valueConnector; } } function render(newOption) { refresh(newOption); for (var i = 0, l = self.shapeList.length; i < l; i++) { zr.addShape(self.shapeList[i]); } } function getOption() { return option; } function resize() { var newWidth = zr.getWidth(); var newHieght = zr.getHeight(); var xScale = newWidth / (_zrWidth || newWidth); var yScale = newHieght / (_zrHeight || newHieght); if (xScale == 1 && yScale == 1) { return; } _zrWidth = newWidth; _zrHeight = newHieght; for (var i = 0, l = self.shapeList.length; i < l; i++) { zr.modShape( self.shapeList[i].id, { style: { x: Math.round(self.shapeList[i].style.x * xScale), y: Math.round(self.shapeList[i].style.y * yScale) } } ); } } function add(shape) { var name = ecData.get(shape, 'name'); var value = ecData.get(shape, 'value'); var seriesName = typeof ecData.get(shape, 'series') != 'undefined' ? ecData.get(shape, 'series').name : ''; var font = self.getFont(option.island.textStyle); var islandShape = { shape : 'circle', id : zr.newShapeId(self.type), zlevel : _zlevelBase, style : { x : shape.style.x, y : shape.style.y, r : option.island.r, color : shape.style.color || shape.style.strokeColor, text : name + _valueConnector + value, textFont : font }, draggable : true, hoverable : true, onmousewheel : self.shapeHandler.onmousewheel, _type : 'island' }; if (islandShape.style.color == '#fff') { islandShape.style.color = shape.style.strokeColor; } self.setCalculable(islandShape); ecData.pack( islandShape, {name:seriesName}, -1, value, -1, name ); self.shapeList.push(islandShape); zr.addShape(islandShape); } function del(shape) { zr.delShape(shape.id); var newShapeList = []; for (var i = 0, l = self.shapeList.length; i < l; i++) { if (self.shapeList[i].id != shape.id) { newShapeList.push(self.shapeList[i]); } } self.shapeList = newShapeList; } /** * 数据项被拖拽进来, 重载基类方法 */ function ondrop(param, status) { if (!self.isDrop || !param.target) { // 没有在当前实例上发生拖拽行为则直接返回 return; } // 拖拽产生孤岛数据合并 var target = param.target; // 拖拽安放目标 var dragged = param.dragged; // 当前被拖拽的图形对象 _combine(target, dragged); zr.modShape(target.id, target); status.dragIn = true; // 处理完拖拽事件后复位 self.isDrop = false; return; } /** * 数据项被拖拽出去, 重载基类方法 */ function ondragend(param, status) { var target = param.target; // 拖拽安放目标 if (!self.isDragend) { // 拖拽的不是孤岛数据,如果没有图表接受孤岛数据,需要新增孤岛数据 if (!status.dragIn) { target.style.x = zrEvent.getX(param.event); target.style.y = zrEvent.getY(param.event); add(target); status.needRefresh = true; } } else { // 拖拽的是孤岛数据,如果有图表接受了孤岛数据,需要删除孤岛数据 if (status.dragIn) { del(target); status.needRefresh = true; } } // 处理完拖拽事件后复位 self.isDragend = false; return; } /** * 滚轮改变孤岛数据值 */ self.shapeHandler.onmousewheel = function(param) { var shape = param.target; var event = param.event; var delta = zrEvent.getDelta(event); delta = delta > 0 ? (-1) : 1; shape.style.r -= delta; shape.style.r = shape.style.r < 5 ? 5 : shape.style.r; var value = ecData.get(shape, 'value'); var dvalue = value * option.island.calculateStep; if (dvalue > 1) { value = Math.round(value - dvalue * delta); } else { value = (value - dvalue * delta).toFixed(2) - 0; } var name = ecData.get(shape, 'name'); shape.style.text = name + ':' + value; ecData.set(shape, 'value', value); ecData.set(shape, 'name', name); zr.modShape(shape.id, shape); zr.refresh(); zrEvent.stop(event); }; self.refresh = refresh; self.render = render; self.resize = resize; self.getOption = getOption; self.add = add; self.del = del; self.ondrop = ondrop; self.ondragend = ondragend; } // 图表注册 require('../chart').define('island', Island); return Island; });
ghostry/Gadmin
Public/Lib/echarts/chart/island.js
JavaScript
apache-2.0
8,473
'use strict'; /** * @ngdoc function * @name freshcardUiApp.controller:TemplatesCtrl * @description * # TemplatesCtrl * Controller of the freshcardUiApp */ angular.module('freshcardUiApp') .controller('TemplatesCtrl', function ( $scope, $rootScope, $localStorage, $filter, $timeout, FileUploader, OrganizationService, configuration ) { $scope.templateLayoutSaved = false; $scope.templateLayoutError = false; $scope.templateLayoutPublished = false; $scope.templateLayoutPublishError = false; $scope.templateImagePath = $rootScope.currentOrganizationTemplate; $scope.fields = [ false, false, false, false, false, false, false ]; $scope.fieldNames = [ 'NAME', 'EMAIL_ADDRESS', 'STREET_ADDRESS', 'POSTAL_CODE', 'CITY', 'PHONE_NUMBER', 'WEBSITE' ]; $scope.fieldMappings = [ $filter('translate')('NAME'), $filter('translate')('EMAIL_ADDRESS'), $filter('translate')('STREET_ADDRESS'), $filter('translate')('POSTAL_CODE'), $filter('translate')('CITY'), $filter('translate')('PHONE_NUMBER'), $filter('translate')('WEBSITE') ]; $scope.showGrid = false; $scope.snapToGrid = false; $scope.fonts = [ 'Helvetica Neue', 'Open Sans', 'Helvetica', 'Arial', 'Times New Roman' ]; $scope.fontSizes = [ 14, 16, 18, 20, 24, 28 ]; $scope.selectedFont = $scope.fonts[0]; $scope.selectedFontSize = $scope.fontSizes[3]; $scope.templateLayout = { fields: { }, font: $scope.selectedFont, fontSize: $scope.selectedFontSize, showGrid: $scope.showGrid, snapToGrid: $scope.snapToGrid }; OrganizationService.get( { organizationId: $rootScope.user.currentOrganizationId }, function(organization) { if (organization.templateLayout) { $scope.templateLayout = JSON.parse(organization.templateLayout); $scope.selectedFont = $scope.templateLayout.font; $scope.selectedFontSize = $scope.templateLayout.fontSize; $scope.fields = [ false, false, false, false, false, false, false ]; for (var field in $scope.templateLayout.fields) { for (var i = 0; i < $scope.fieldMappings.length; i++) { if ($scope.fieldMappings[i] === $filter('translate')(field)) { $scope.fields[i] = true; } } } } } ); var imageUploader = $scope.imageUploader = new FileUploader( { url: configuration.apiRootURL + 'api/v1/organizations/uploadTemplateImage/' + $rootScope.user.currentOrganizationId, headers: { 'X-Auth-Token': $rootScope.authToken } } ); imageUploader.onAfterAddingFile = function() { $scope.imageUploadCompleted = false; }; imageUploader.onCompleteItem = function(fileItem, response) { if (response.imagePath !== null && response.imagePath !== undefined) { $scope.templateImagePath = $localStorage.currentOrganizationTemplate = $rootScope.currentOrganizationTemplate = response.imagePath; $scope.imageUploadCompleted = true; } }; $scope.saveTemplate = function() { $scope.templateLayout.font = $scope.selectedFont; $scope.templateLayout.fontSize = $scope.selectedFontSize; var svgResult = $scope.canvas.toSVG(); for (var i = 0; i < $scope.fieldMappings.length; i++) { svgResult = svgResult.replace($scope.fieldMappings[i], $scope.fieldNames[i]); } OrganizationService.update( { id: $rootScope.user.currentOrganizationId, templateLayout: JSON.stringify($scope.templateLayout), templateAsSVG: svgResult }, function() { $scope.templateLayoutPublished = false; $scope.templateLayoutPublishError = false; $scope.templateLayoutSaved = true; $scope.templateLayoutError = false; $timeout( function() { $scope.templateLayoutSaved = false; }, 5000 ); }, function() { $scope.templateLayoutPublished = false; $scope.templateLayoutPublishError = false; $scope.templateLayoutSaved = false; $scope.templateLayoutError = true; } ); }; $scope.publishTemplate = function() { OrganizationService.publishTemplate( { id: $rootScope.user.currentOrganizationId }, function() { $scope.templateLayoutPublished = true; $scope.templateLayoutPublishError = false; $scope.templateLayoutSaved = false; $scope.templateLayoutError = false; $timeout( function() { $scope.templateLayoutPublished = false; }, 5000 ); }, function() { $scope.templateLayoutPublished = false; $scope.templateLayoutPublishError = true; $scope.templateLayoutSaved = false; $scope.templateLayoutError = false; } ); }; });
BjoernKW/FreshcardUI
app/scripts/controllers/templates.js
JavaScript
apache-2.0
4,492
// NOTE: this file should only be included when embedding the inspector - no other files should be included (this will do everything) // If gliEmbedDebug == true, split files will be used, otherwise the cat'ed scripts will be inserted (function() { var pathRoot = ""; var useDebug = window["gliEmbedDebug"]; // Find self in the <script> tags var scripts = document.head.getElementsByTagName("script"); for (var n = 0; n < scripts.length; n++) { var scriptTag = scripts[n]; var src = scriptTag.src.toLowerCase(); if (/core\/embed.js$/.test(src)) { // Found ourself - strip our name and set the root var index = src.lastIndexOf("embed.js"); pathRoot = scriptTag.src.substring(0, index); break; } } function insertHeaderNode(node) { var targets = [ document.body, document.head, document.documentElement ]; for (var n = 0; n < targets.length; n++) { var target = targets[n]; if (target) { if (target.firstElementChild) { target.insertBefore(node, target.firstElementChild); } else { target.appendChild(node); } break; } } } ; function insertStylesheet(url) { var link = document.createElement("link"); link.rel = "stylesheet"; link.href = url; insertHeaderNode(link); return link; } ; function insertScript(url) { var script = document.createElement("script"); script.type = "text/javascript"; script.src = url; insertHeaderNode(script); return script; } ; if (useDebug) { // Fall through below and use the loader to get things } else { var jsurl = pathRoot + "lib/gli.all.js"; var cssurl = pathRoot + "lib/gli.all.css"; window.gliCssUrl = cssurl; insertStylesheet(cssurl); insertScript(jsurl); } // Always load the loader if (useDebug) { var script = insertScript(pathRoot + "loader.js"); function scriptLoaded() { gliloader.pathRoot = pathRoot; if (useDebug) { // In debug mode load all the scripts gliloader.load([ "host", "replay", "ui" ]); } } ; script.onreadystatechange = function() { if (("loaded" === script.readyState || "complete" === script.readyState) && !script.loadCalled) { this.loadCalled = true; scriptLoaded(); } }; script.onload = function() { if (!script.loadCalled) { this.loadCalled = true; scriptLoaded(); } }; } // Hook canvas.getContext var originalGetContext = HTMLCanvasElement.prototype.getContext; if (!HTMLCanvasElement.prototype.getContextRaw) { HTMLCanvasElement.prototype.getContextRaw = originalGetContext; } HTMLCanvasElement.prototype.getContext = function() { var ignoreCanvas = this.internalInspectorSurface; if (ignoreCanvas) { return originalGetContext.apply(this, arguments); } var contextNames = [ "moz-webgl", "webkit-3d", "experimental-webgl", "webgl" ]; var requestingWebGL = contextNames.indexOf(arguments[0]) != -1; if (requestingWebGL) { // Page is requesting a WebGL context! // TODO: something } var result = originalGetContext.apply(this, arguments); if (result == null) { return null; } if (requestingWebGL) { // TODO: pull options from somewhere? result = gli.host.inspectContext(this, result); var hostUI = new gli.host.HostUI(result); result.hostUI = hostUI; // just so we can access it later for // debugging } return result; }; })();
freekv/jpip.js
examples/js/embed.js
JavaScript
apache-2.0
4,075
'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": [ "\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0440\u0430\u0437\u043c\u04d5", "\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0444\u04d5\u0441\u0442\u04d5" ], "DAY": [ "\u0445\u0443\u044b\u0446\u0430\u0443\u0431\u043e\u043d", "\u043a\u044a\u0443\u044b\u0440\u0438\u0441\u04d5\u0440", "\u0434\u044b\u0446\u0446\u04d5\u0433", "\u04d5\u0440\u0442\u044b\u0446\u0446\u04d5\u0433", "\u0446\u044b\u043f\u043f\u04d5\u0440\u04d5\u043c", "\u043c\u0430\u0439\u0440\u04d5\u043c\u0431\u043e\u043d", "\u0441\u0430\u0431\u0430\u0442" ], "ERANAMES": [ "\u043d.\u0434.\u0430.", "\u043d.\u0434." ], "ERAS": [ "\u043d.\u0434.\u0430.", "\u043d.\u0434." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "\u044f\u043d\u0432\u0430\u0440\u044b", "\u0444\u0435\u0432\u0440\u0430\u043b\u044b", "\u043c\u0430\u0440\u0442\u044a\u0438\u0439\u044b", "\u0430\u043f\u0440\u0435\u043b\u044b", "\u043c\u0430\u0439\u044b", "\u0438\u044e\u043d\u044b", "\u0438\u044e\u043b\u044b", "\u0430\u0432\u0433\u0443\u0441\u0442\u044b", "\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044b", "\u043e\u043a\u0442\u044f\u0431\u0440\u044b", "\u043d\u043e\u044f\u0431\u0440\u044b", "\u0434\u0435\u043a\u0430\u0431\u0440\u044b" ], "SHORTDAY": [ "\u0445\u0446\u0431", "\u043a\u0440\u0441", "\u0434\u0446\u0433", "\u04d5\u0440\u0442", "\u0446\u043f\u0440", "\u043c\u0440\u0431", "\u0441\u0431\u0442" ], "SHORTMONTH": [ "\u044f\u043d\u0432.", "\u0444\u0435\u0432.", "\u043c\u0430\u0440.", "\u0430\u043f\u0440.", "\u043c\u0430\u044f", "\u0438\u044e\u043d\u044b", "\u0438\u044e\u043b\u044b", "\u0430\u0432\u0433.", "\u0441\u0435\u043d.", "\u043e\u043a\u0442.", "\u043d\u043e\u044f.", "\u0434\u0435\u043a." ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM, y '\u0430\u0437'", "longDate": "d MMMM, y '\u0430\u0437'", "medium": "dd MMM y '\u0430\u0437' HH:mm:ss", "mediumDate": "dd MMM y '\u0430\u0437'", "mediumTime": "HH:mm:ss", "short": "dd.MM.yy HH:mm", "shortDate": "dd.MM.yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "GEL", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "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\u00a0", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "os", "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;} }); }]);
LADOSSIFPB/nutrif
nutrif-web/lib/angular/i18n/angular-locale_os.js
JavaScript
apache-2.0
3,826
document.write('<div id="terminal" class="terminal-content"></div>'); var session = {}; // return a parameter value from the current URL function getParam(sname) { var params = location.search.substr(location.search.indexOf("?") + 1); var sval = ""; params = params.split("&"); // split param and value into individual pieces for (var i = 0; i < params.length; i++) { temp = params[i].split("="); if ([temp[0]] == sname) { sval = temp[1]; } } return sval; } function getBaseURL() { return location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + location.pathname; } function greetings(term) { term.echo(session.welcomeMessage); term.echo(' '); } function createNewSession(expression, snap) { var newSession = []; newSession.expression = expression; newSession.snap = snap; $.ajax({ type: 'POST', async: false, url: '/create', data: (expression ? "expression=" + expression : "") + "&" + (snap ? "snap=" + snap : "") } ).done(function (data) { newSession.clientId = data.id; newSession.welcomeMessage = data.welcomeMessage }); newSession.requesting = false; session = newSession; } function closeSession() { $.ajax({type: 'POST', async: false, url: '/remove', data: 'id=' + session.clientId}) .fail(function (xhr, textStatus, errorThrown) {/* ignore failure when closing */ }); } function restartSession(term) { term.echo("[[;#CC7832;black]Session terminated. Starting new session...]"); closeSession(); createNewSession(session.expression, session.snap) } function readExpressionLine(line, term) { var expression = null; $.ajax({type: 'POST', async: false, url: '/readExpression', data: {id: session.clientId, line: line}}) .done(function (data) { expression = data.expression; }) .fail(function (xhr, textStatus, errorThrown) { restartSession(term) }); return expression; } function makeSnap(term) { var snapUrl = null; $.ajax({type: 'POST', async: false, url: '/snap', data: 'id=' + session.clientId}) .done(function (data) { snapUrl = getBaseURL() + '?snap=' + data.snap; }).fail(function (xhr, textStatus, errorThrown) { restartSession(term) }); return snapUrl; } function messageStyle(style) { return { finalize: function (div) { div.addClass(style); } } } function layoutCompletions(candidates, widthInChars) { var max = 0; for (var i = 0; i < candidates.length; i++) { max = Math.max(max, candidates[i].length); } max += 2; var n = Math.floor(widthInChars / max); var buffer = ""; var col = 0; for (i = 0; i < candidates.length; i++) { var completion = candidates[i]; buffer += candidates[i]; for (var j = completion.length; j < max; j++) { buffer += " "; } if (++col >= n) { buffer += "\n"; col = 0; } } return buffer; } function echoCompletionCandidates(term, candidates) { term.echo(term.get_prompt() + term.get_command()); term.echo(layoutCompletions(candidates, term.width() / 8)); } function handleTerminalCommand(log, term) { if (log.type == "CONTROL") { switch (log.message) { case "CLEAR_SCREEN": term.clear(); term.echo(session.welcomeMessage); term.echo(' '); break; } return true; } return false; } function handleTerminalMessage(log, term) { if (log.type != "CONTROL") { var style = log.type == "ERROR" ? "terminal-message-error" : "terminal-message-success"; term.echo(log.message, messageStyle(style)) return log.type == "ERROR"; } return false; } $(document).ready(function () { jQuery(function ($, undefined) { createNewSession(getParam("expression"), getParam("snap")); $('#terminal').terminal(function (command, term) { if (command == ":snap") { var snapUri = makeSnap(term); term.echo("Created terminal snapshot [[!;;]" + snapUri + "]", messageStyle("terminal-message-success")); return; } var expression = readExpressionLine(command, term); if (expression) { $.ajax({ type: 'POST', async: false, url: '/execute', data: {id: session.clientId, expression: expression} }).done(function (data) { var hadError = false; for (var i = 0; i < data.logs.length; i++) { var log = data.logs[i]; if (!handleTerminalCommand(log, term)) { hadError = handleTerminalMessage(log, term) || hadError; } } if (!hadError) { _gaq.push(["_trackEvent", "console", "evaluation", "success"]); } else { _gaq.push(["_trackEvent", "console", "evaluation", "error"]); } session.requesting = false; }).fail(function (xhr, textStatus, errorThrown) { restartSession(term) }); } else { term.echo(" "); session.requesting = false; } }, { greetings: null, name: 'js_demo', prompt: '[[;white;black]java> ]', onInit: function (term) { greetings(term); }, keydown: function (event, term) { if (event.keyCode == 9) //Tab { var completionResult = []; $.ajax({ type: 'GET', async: false, cache: false, url: '/completions', data: {id: session.clientId, expression: term.get_command()} }) .done(function (data) { completionResult = data; }); var candidates = _.map(completionResult.candidates, function (cand) { return cand.value; }); var candidatesForms = _.map(completionResult.candidates, function (cand) { return cand.forms; }); var promptText = term.get_command(); if (candidates.length == 0) { term.set_command(promptText); return false; } if (candidates.length == 1) { var uniqueForms = _.filter(_.unique(candidatesForms[0]), function (form) { return form != candidates[0] }); var text = term.get_command().substr(0, parseInt(completionResult.position)) + candidates[0]; term.set_command(text); if (uniqueForms.length > 0) { echoCompletionCandidates(term, candidatesForms[0]); } return false; } echoCompletionCandidates(term, candidates); for (var i = candidates[0].length; i > 0; --i) { var prefixedCandidatesCount = _.filter(candidates, function (cand) { return i > cand.length ? false : cand.substr(0, i) == candidates[0].substr(0, i); }).length; if (prefixedCandidatesCount == candidates.length) { term.set_command(promptText.substr(0, parseInt(completionResult.position)) + candidates[0].substr(0, i)); return false; } } term.set_command(promptText); return false; } } }); }); });
albertlatacz/java-repl
src/javarepl/console/ui/term.js
JavaScript
apache-2.0
8,438
angular.module('ssAuth').factory('SessionService', ['$http', '$cookies', '$q', function($http, $cookies, $q){ var currentUser = {}; var currentFetch; currentUser.isAdmin = function() { return currentUser && currentUser.groups && currentUser.groups['Admins']; }; var getCurrentUser = function(forceUpdate) { var deferred = $q.defer(); if(forceUpdate) { return fetchUpdatedUser(); } if(currentUser.lastUpdated) { var diffMS = (new Date()).getTime() - new Date(currentUser.lastUpdated).getTime(); var diffMin = ((diffMS/60)/60); if(diffMin < 5) { deferred.resolve(currentUser); return deferred.promise; } } return fetchUpdatedUser(); }; var restoreFromCookie = function() { var cookie = $cookies['ag-user']; if(!cookie) return; var user = JSON.parse(cookie); angular.extend(currentUser, user); return currentUser; }; var saveToCookie = function() { $cookies['ag-user'] = JSON.stringify(currentUser); }; var fetchUpdatedUser = function() { //we've already made a call for the current user //just hold your horses if(currentFetch) { return currentFetch; } var deferred = $q.defer(); currentFetch = deferred.promise; $http.get('/session').success(function(user){ angular.extend(currentUser, user); currentUser.lastUpdated = new Date(); saveToCookie(); deferred.resolve(currentUser); currentFetch = undefined; }); return deferred.promise; }; return { getCurrentUser: getCurrentUser, restore: restoreFromCookie, userUpdated: currentUser.lastUpdated }; }]);
spaceshipsamurai/samurai-auth
public/app/shared/session.service.js
JavaScript
apache-2.0
1,933
/** * @license Copyright 2017 Google Inc. 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'; /* eslint-env mocha */ const OptimizedImages = require('../../../../gather/gatherers/dobetterweb/optimized-images'); const assert = require('assert'); let options; let optimizedImages; const fakeImageStats = { jpeg: {base64: 100, binary: 80}, webp: {base64: 80, binary: 60}, }; const traceData = { networkRecords: [ { _url: 'http://google.com/image.jpg', _mimeType: 'image/jpeg', _resourceSize: 10000, _resourceType: {_name: 'image'}, finished: true, }, { _url: 'http://google.com/transparent.png', _mimeType: 'image/png', _resourceSize: 11000, _resourceType: {_name: 'image'}, finished: true, }, { _url: 'http://google.com/image.bmp', _mimeType: 'image/bmp', _resourceSize: 12000, _resourceType: {_name: 'image'}, finished: true, }, { _url: 'http://google.com/image.bmp', _mimeType: 'image/bmp', _resourceSize: 12000, _resourceType: {_name: 'image'}, finished: true, }, { _url: 'http://google.com/vector.svg', _mimeType: 'image/svg+xml', _resourceSize: 13000, _resourceType: {_name: 'image'}, finished: true, }, { _url: 'http://gmail.com/image.jpg', _mimeType: 'image/jpeg', _resourceSize: 15000, _resourceType: {_name: 'image'}, finished: true, }, { _url: 'data: image/jpeg ; base64 ,SgVcAT32587935321...', _mimeType: 'image/jpeg', _resourceType: {_name: 'image'}, _resourceSize: 14000, finished: true, }, { _url: 'http://google.com/big-image.bmp', _mimeType: 'image/bmp', _resourceType: {_name: 'image'}, _resourceSize: 12000, finished: false, // ignore for not finishing }, { _url: 'http://google.com/not-an-image.bmp', _mimeType: 'image/bmp', _resourceType: {_name: 'document'}, // ignore for not really being an image _resourceSize: 12000, finished: true, }, ], }; describe('Optimized images', () => { // Reset the Gatherer before each test. beforeEach(() => { optimizedImages = new OptimizedImages(); options = { url: 'http://google.com/', driver: { evaluateAsync: function() { return Promise.resolve(fakeImageStats); }, sendCommand: function() { return Promise.reject(new Error('wasn\'t found')); }, }, }; }); it('returns all images', () => { return optimizedImages.afterPass(options, traceData).then(artifact => { assert.equal(artifact.length, 4); assert.ok(/image.jpg/.test(artifact[0].url)); assert.ok(/transparent.png/.test(artifact[1].url)); assert.ok(/image.bmp/.test(artifact[2].url)); // skip cross-origin for now // assert.ok(/gmail.*image.jpg/.test(artifact[3].url)); assert.ok(/data: image/.test(artifact[3].url)); }); }); it('computes sizes', () => { const checkSizes = (stat, original, webp, jpeg) => { assert.equal(stat.originalSize, original); assert.equal(stat.webpSize, webp); assert.equal(stat.jpegSize, jpeg); }; return optimizedImages.afterPass(options, traceData).then(artifact => { assert.equal(artifact.length, 4); checkSizes(artifact[0], 10000, 60, 80); checkSizes(artifact[1], 11000, 60, 80); checkSizes(artifact[2], 12000, 60, 80); // skip cross-origin for now // checkSizes(artifact[3], 15000, 60, 80); checkSizes(artifact[3], 20, 80, 100); // uses base64 data }); }); it('handles partial driver failure', () => { let calls = 0; options.driver.evaluateAsync = () => { calls++; if (calls > 2) { return Promise.reject(new Error('whoops driver failed')); } else { return Promise.resolve(fakeImageStats); } }; return optimizedImages.afterPass(options, traceData).then(artifact => { const failed = artifact.find(record => record.failed); assert.equal(artifact.length, 4); assert.ok(failed, 'passed along failure'); assert.ok(/whoops/.test(failed.err.message), 'passed along error message'); }); }); it('supports Audits.getEncodedResponse', () => { options.driver.sendCommand = (method, params) => { const encodedSize = params.encoding === 'webp' ? 60 : 80; return Promise.resolve({encodedSize}); }; return optimizedImages.afterPass(options, traceData).then(artifact => { assert.equal(artifact.length, 5); assert.equal(artifact[0].originalSize, 10000); assert.equal(artifact[0].webpSize, 60); assert.equal(artifact[0].jpegSize, 80); // supports cross-origin assert.ok(/gmail.*image.jpg/.test(artifact[3].url)); }); }); });
tkadlec/lighthouse
lighthouse-core/test/gather/gatherers/dobetterweb/optimized-images-test.js
JavaScript
apache-2.0
5,402
// TODO split modules, controllers, services // info separate files and concat/uglify them let remote = require('remote') let fs = require('fs') let mysql = require('promise-mysql') let app = angular.module('ttableinstaller', ['ngRoute']) photon.start(document) app.config(($routeProvider) => { $routeProvider .when('/', { templateUrl: 'templates/main.html', controller: 'MainController' }) .otherwise({ redirectTo: '/' }) })
tTables/tTableInstaller
app/app.js
JavaScript
apache-2.0
467
app.controller('PickerController', function ($scope, $modalInstance, itemColor) { $scope.showCarrierColors = true; $scope.brandColors = [ { name: 'Brand Blue', hex: '#276681' }, { name: 'Brand Green', hex: '#66b245' }, { name: 'Brand Blue Desaturated', hex: '#417c95' }, { name: 'Brand Green Desaturated', hex: '#75b86f' }, { name: 'Bluest', hex: '#5baebf' }, { name: 'Blue', hex: '#66b7bb' }, { name: 'Blue Green', hex: '#76beb6' }, { name: 'Green Blue', hex: '#84c6ae' }, { name: 'Green', hex: '#96cca7' }, { name: 'Greenest', hex: '#a4d49a' }, { name: 'Level 2 Blend', hex: '#7fced8' }, { name: 'Level 2 Blend', hex: '#8fd4d6' }, { name: 'Level 2 Blend', hex: '#a5d7d3' }, { name: 'Level 2 Blend', hex: '#b5dcce' }, { name: 'Level 2 Blend', hex: '#bfe0ca' }, { name: 'Level 2 Blend', hex: '#c8e5c2' }, { name: 'Level 3 Blend', hex: '#b0e2e7' }, { name: 'Level 3 Blend', hex: '#bce5e6' }, { name: 'Level 3 Blend', hex: '#c8e6e4' }, { name: 'Level 3 Blend', hex: '#d3eae2' }, { name: 'Level 3 Blend', hex: '#d8ecdf' }, { name: 'Level 3 Blend', hex: '#ddefda' }, { name: 'Illustration Stroke Darkest', hex: '#54636a' }, { name: 'Illustration Stroke Medium', hex: '#7f8a8f' }, { name: 'Illustration Stroke Light', hex: '#a9b1b4' }, { name: 'Illustration Stroke Lightest', hex: '#d4d8da' }, { name: 'Yellow', hex: '#f5db77' }, { name: 'Medium Yellow', hex: '#f8e499' }, { name: 'Light Yellow', hex: '#faedbb' }, { name: 'Lightest Yellow', hex: '#fdf6dd' }, { name: 'Tang', hex: '#f38871' }, { name: 'Medium Tang', hex: '#f7a593' }, { name: 'Light Tang', hex: '#fbc1b4' }, { name: 'Lightest Tang', hex: '#ffded6' }, { name: 'Black', hex: '#555555' }, { name: 'Dark Gray', hex: '#797979' }, { name: 'Medium Gray', hex: '#9c9c9c' }, { name: 'Light Gray', hex: '#c0c0c0' }, { name: 'Lightest Gray', hex: '#e3e3e3' }, { name: 'Off White', hex: '#f9f9f9' } ]; $scope.carrierColors = [ { carrier: 'Verizon', hex: '#ca5b59' }, { carrier: 'AT&T', hex: '#5694b4' }, { carrier: 'T-Mobile', hex: '#d45da0' }, { carrier: 'Sprint', hex: '#e9b444' }, { carrier: 'Cricket', hex: '#008752' }, { carrier: 'Cricket', hex: '#439474' }, { carrier: 'MetroPCS', hex: '#6764b3' }, { carrier: 'EE', hex: '#2e9a9c' }, { carrier: 'O2', hex: '#2566a8' }, { carrier: 'Orange', hex: '#ff6c42' }, { carrier: 'Three', hex: '#333333' }, { carrier: 'Vodafone', hex: '#eb5247' }, { carrier: 'Bell', hex: '#2876a5' }, { carrier: 'Leap', hex: '#330066' }, { carrier: 'Rogers', hex: '#d63e3e' }, { carrier: 'Telus', hex: '#4e5cb5' }, { carrier: 'Videotron', hex: '#fcc622' }, { carrier: 'Wind', hex: '#ec7c23' }, { carrier: 'Tie', hex: '#999999' } ] $scope.ok = function () { $modalInstance.close(itemColor); }; $scope.closeModal = function(color) { $modalInstance.close(color); } });
seanmthompson/D3-Chart-Generator
src/app/shared/colorpicker/pickerController.js
JavaScript
apache-2.0
3,420
app.service('UserService', ['$http', function($http) { return { getLogged: function(successCallback) { $http.get('/api/user/logged').then(successCallback); }, putPin: function(user, successCallback) { $http.post('/api/user/pin/', user).then(successCallback); } }; }]);
jeffersonvenancio/BarzingaNow
python/web/app/services/user.js
JavaScript
apache-2.0
333
//************************************************************* // Filename: socket.js // // Author: Jake Higgins <[email protected]> //************************************************************* var Socket; function addSocketListeners() { Socket = new io(); Socket.on('sync objects', function(objects, room, caller) { console.log(objects); if(CallerID == caller) { console.log(objects); $.each(objects, function(key, object) { createStroke(object); }); CanvasManager.render(); } }); Socket.on('add object', function(object, room, caller) { if(CallerID != caller && RoomID == room) { createStroke(object); CanvasManager.clearCanvas(); } }); Socket.on('move object', function(object, room, caller) { console.log('move object'); if(CallerID != caller && RoomID == room) { var targetObj = ObjectManager.findObject(object.objectID); console.log(targetObj); if(targetObj != null) { targetObj.max = object.max; targetObj.min = object.min; $(targetObj.container).css({ top: targetObj.min.y, left: targetObj.min.x }); } } }); Socket.on('delete object', function(object, room, caller) { if(CallerID != caller && RoomID == room) { ObjectManager.deleteObject(object.objectID); } }); Socket.on('clear objects', function(room, caller) { console.log('clear'); if(CallerID != caller && RoomID == room) { CanvasManager.clear(true); } }); Socket.on('draw', function(drawData, room, caller) { if(CallerID != caller && RoomID == room) { Drawing.draw(drawData, true); } }); // ======== Chat =============/ // Comes in the format message/roomID/caller // if(roomID == this.roomID) // pseudocode for now // add chat to chat thingy Socket.on('receiveMessage', function(message, room, caller) { if ( RoomID == room ) { // Proceed Chat.write(message, caller); } }); } function createStroke(stroke) { console.log(stroke); var obj = new object("stroke"); obj.initialize(); obj.imageData = stroke.imageData; obj.layer = stroke.layer; obj.max = stroke.max; obj.min = stroke.min; obj.objectID = stroke.objectID; obj.type = "stroke"; obj.objectData = { imageData: obj.imageData, layer: obj.layer, max: obj.max, min: obj.min, objectID: obj.objectID, objectType: obj.type, }; obj.createImage(); ObjectManager.addObject(obj); }
IGME-Production-Studio/driftwoodrp
update/public/static/scripts/socket.js
JavaScript
apache-2.0
2,530
/** * Copyright 2017 dialog LLC <[email protected]> * @flow */ import type { PeerInfo } from '@dlghq/dialog-types'; import type { AvatarSize } from '../Avatar/getAvatarSize'; import type { Gradient } from '../Avatar/getAvatarColor'; import React, { PureComponent } from 'react'; import classNames from 'classnames'; import getAvatarSize from '../Avatar/getAvatarSize'; import getAvatarText from '../Avatar/getAvatarText'; import getAvatarColor from '../Avatar/getAvatarColor'; import createSequence from '../../utils/createSequence'; import styles from '../PeerAvatar/PeerAvatar.css'; export type Props = { className?: string, peerBig: PeerInfo, peerSmall: PeerInfo, size: AvatarSize, onClick?: (event: SyntheticMouseEvent) => any }; type DefaultProps = { size: AvatarSize }; const seq = createSequence(); class DoublePeerAvatar extends PureComponent<DefaultProps, Props, void> { id: string; ids: { big: string, clip: string, small: string }; static defaultProps = { size: 'medium' }; constructor(props: Props) { super(props); this.id = 'double_peer_avatar_' + seq.next(); this.ids = { big: `${this.id}_big`, clip: `${this.id}_big_clip`, small: `${this.id}_small` }; } getAvatarSize(): number { return getAvatarSize(this.props.size); } renderDefsBig(): React.Element<any> { if (this.props.peerBig.avatar) { return ( <pattern id={this.ids.big} width="100%" height="100%" patternUnits="userSpaceOnUse"> <image x="0" y="0" width="100px" height="100px" xlinkHref={this.props.peerBig.avatar} /> </pattern> ); } const colors: Gradient = getAvatarColor(this.props.peerBig.placeholder); return ( <linearGradient id={this.ids.big} gradientUnits="userSpaceOnUse" x1="6.79%" y1="105.31%" x2="93.21%" y2="-5.31%" > <stop stopColor={colors.payload.from} /> <stop offset="1" stopColor={colors.payload.to} /> </linearGradient> ); } renderClipMaskBig(): React.Element<any> { return ( <clipPath id={this.ids.clip}> <path // eslint-disable-next-line d="M58.2070074,99.3297063 C55.5367715,99.7706374 52.795171,100 50,100 C22.3857625,100 0,77.6142375 0,50 C0,22.3857625 22.3857625,0 50,0 C77.6142375,0 100,22.3857625 100,50 C100,52.795171 99.7706374,55.5367715 99.3297063,58.2070074 C94.8434182,55.5348957 89.6009561,54 84,54 C67.4314575,54 54,67.4314575 54,84 C54,89.6009561 55.5348957,94.8434182 58.2070074,99.3297063 Z" /> </clipPath> ); } renderDefsSmall(): React.Element<any> { if (this.props.peerSmall.avatar) { return ( <pattern id={this.ids.small} width="100%" height="100%" x="58" y="58" patternUnits="userSpaceOnUse" > <image x="0" y="0" width="100px" height="100px" xlinkHref={this.props.peerSmall.avatar} transform="scale(0.507046569,0.507046569)" /> </pattern> ); } const colors: Gradient = getAvatarColor(this.props.peerSmall.placeholder); return ( <linearGradient id={this.ids.small} gradientUnits="userSpaceOnUse" x1="6.79%" y1="105.31%" x2="93.21%" y2="-5.31%" > <stop stopColor={colors.payload.from} /> <stop offset="1" stopColor={colors.payload.to} /> </linearGradient> ); } renderSmallAvatar(): React.Element<any> { return ( <circle cx="84" cy="84" r="25" fill={`url(#${this.ids.small})`} /> ); } renderBigAvatar(): React.Element<any> { return ( <path // eslint-disable-next-line d="M58.2070074,99.3297063 C55.5367715,99.7706374 52.795171,100 50,100 C22.3857625,100 0,77.6142375 0,50 C0,22.3857625 22.3857625,0 50,0 C77.6142375,0 100,22.3857625 100,50 C100,52.795171 99.7706374,55.5367715 99.3297063,58.2070074 C94.8434182,55.5348957 89.6009561,54 84,54 C67.4314575,54 54,67.4314575 54,84 C54,89.6009561 55.5348957,94.8434182 58.2070074,99.3297063 Z" fill={`url(#${this.ids.big})`} /> ); } renderPeerSmallText(): ?React.Element<any> { if (this.props.peerSmall.avatar) { return null; } const size = this.getAvatarSize(); const text = size >= 20 ? getAvatarText(this.props.peerSmall.title) : null; const twoChars = Boolean(text && text.length !== 1); const textStyles = { fontSize: twoChars ? 20 : 24 }; return ( <text className={styles.text} x="84" y="84" textAnchor="middle" alignmentBaseline="central" dominantBaseline="central" style={textStyles} > {text} </text> ); } renderPeerBigText(): ?React.Element<any> { if (this.props.peerBig.avatar) { return null; } const size = this.getAvatarSize(); const text = size >= 20 ? getAvatarText(this.props.peerBig.title) : null; const twoChars = Boolean(text && text.length !== 1); const textStyles = { fontSize: twoChars ? 38 : 48 }; return ( <text className={styles.text} x="50" y="50" textAnchor="middle" alignmentBaseline="central" dominantBaseline="central" style={textStyles} clipPath={`url(#${this.ids.clip})`} > {text} </text> ); } render(): React.Element<any> { const className = classNames(styles.container, { [styles.clickable]: this.props.onClick }, this.props.className); const size = this.getAvatarSize(); return ( <svg viewBox="0 0 109 109" width={size} height={size} className={className} onClick={this.props.onClick} > <defs> {this.renderDefsBig()} {this.renderClipMaskBig()} {this.renderDefsSmall()} </defs> {this.renderBigAvatar()} {this.renderSmallAvatar()} {this.renderPeerBigText()} {this.renderPeerSmallText()} </svg> ); } } export default DoublePeerAvatar;
nolawi/champs-dialog-sg
src/components/DoublePeerAvatar/DoublePeerAvatar.js
JavaScript
apache-2.0
6,308
/** * Created by raj on 19/8/14. */ var fs = require('fs'); var content = fs.read ('animeEpisode.json'); console.log(JSON.stringify(JSON.parse(content)[1][0].title)); videolinks=JSON.parse(content); links=[]; function pages(k) { var page = new WebPage(); page.open('http://www.gogoanime.com/', function (status) { console.log('opened gogoanime :++++ ', status); if (status==fail){ page.close(); pages(k); } if (status == success) { page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function () { console.log('jq included') var data = page.evaluate(function (data) { var tempdata=[]; for (var i = 0; i <$('.post div:eq(1) table tbody tr td:eq(0) ul').length; i = i + 1) { data.links.push($('.post div:eq(1) table tbody tr td:eq(0) ul li a').attr('href')); } return JSON.stringify(data); }); links[k][m] = JSON.parse(data); console.log(data); if (m < links[k].length - 1) { page.close(); console.log('next episoide called'); pages(k, m + 1); } ; if (m == links[k].length - 1) { page.close(); console.log('next anime called'); var path = 'links.json'; fs.write(path, links[k], 'w'); pages(k + 1, 1); } if (k == links.length - 1) { var path = 'links.json'; fs.write(path, links, 'w'); } }); } }); } pages(1,1);
msandeepraj211/phantom
recent.js
JavaScript
apache-2.0
1,995
var a02307 = [ [ "GenericVector", "a02307.html#a60d42eebf02708482a8b506edd417990", null ], [ "GenericVector", "a02307.html#a28a69767bcadb6058a2a9df4afecd5fc", null ], [ "GenericVector", "a02307.html#a2b61cd1cd756770518f5ac30f817a9bf", null ], [ "~GenericVector", "a02307.html#a49840c8743a063b87839baef7e19b968", null ], [ "back", "a02307.html#a48b82547ebbaa5fedecfdebe7e2f155a", null ], [ "binary_search", "a02307.html#ad561e19e75a0fb30f0118774d7fa5621", null ], [ "bool_binary_search", "a02307.html#a8c261f66a24da67aac1acca7aa8f650a", null ], [ "choose_nth_item", "a02307.html#a5c4218ef833d0fe5db9b9749abd81ea5", null ], [ "choose_nth_item", "a02307.html#ae1e555b0cdded2c36dd6cf15345f659f", null ], [ "clear", "a02307.html#a9cdbff49b186574b83e43afba606fdd9", null ], [ "compact", "a02307.html#a080f7786e007523bcaa3f69913a82882", null ], [ "compact_sorted", "a02307.html#a8cb22ff55d6dd125d93cd03fd73bf8ad", null ], [ "contains", "a02307.html#a997e0fcaaa6b6533401dc54c0691e2e5", null ], [ "contains_index", "a02307.html#ac1aae0b1c22248f264dad02481123398", null ], [ "delete_data_pointers", "a02307.html#a98f62dccd75224a60437c2761bd215cd", null ], [ "DeSerialize", "a02307.html#aa4f5b1bc0d044fbd1fc77363b798c39c", null ], [ "DeSerialize", "a02307.html#a2e4fca9599eff590b76affc0a0aa0a2b", null ], [ "DeSerializeClasses", "a02307.html#a698ebd328d22f1edc114053ca2eba48e", null ], [ "DeSerializeClasses", "a02307.html#ade729c7d5429fbd5be304e3493a8a95f", null ], [ "dot_product", "a02307.html#a6f6dfbc607499173e7809656c6c505bc", null ], [ "double_the_size", "a02307.html#af0214c8c21da9eb57dfebc78611d0cd6", null ], [ "empty", "a02307.html#a172c4aa23ba397e24319ae095281cbcc", null ], [ "get", "a02307.html#abd0a875f98a1d78613ed3521d96e5300", null ], [ "get_index", "a02307.html#a6dee574daf4a3d4f0fc7048964f8f252", null ], [ "init", "a02307.html#a5b010723588fe15f303e4f3474d8479e", null ], [ "init_to_size", "a02307.html#a6751521fd3eb461d81fc83ef93a0def3", null ], [ "insert", "a02307.html#a57ca5259541548a97bcfd4d0925a27ff", null ], [ "length", "a02307.html#a6af4e0a2a30dda267d19bf783ae22eb7", null ], [ "move", "a02307.html#abae057ce589be25aae9b80958f84e34c", null ], [ "operator+=", "a02307.html#af73fadcdb08f0a12a5615f2bcf6fa6a8", null ], [ "operator+=", "a02307.html#acc7df2256174b32632e4d5b6c8d05d29", null ], [ "operator=", "a02307.html#af6fd5b3891b276c10add96f9411bec05", null ], [ "operator[]", "a02307.html#afd51f3f981284adb20bdf3b0bfd1c1f7", null ], [ "pop_back", "a02307.html#a0621dd57ce58dae3cb5f3d61e76bd233", null ], [ "push_back", "a02307.html#a0dc89fe2a365b04a61017f9d78c1a303", null ], [ "push_back_new", "a02307.html#a393f9f8dcc55ad759a5c7fbdc4840a89", null ], [ "push_front", "a02307.html#ae08e7cece0097ad356b5e565cbb2cf0b", null ], [ "read", "a02307.html#a10a273cab07e56c1654b2167f8aa9408", null ], [ "remove", "a02307.html#a3fd37a240a42f1c3052e8d28614d3702", null ], [ "reserve", "a02307.html#aa225ea3fc9374961482bc804028317eb", null ], [ "resize_no_init", "a02307.html#a09005e8f2b51d033d60eb5690aa5d112", null ], [ "reverse", "a02307.html#a58f6d73009cc3c56d0efb0d96ad35b5b", null ], [ "Serialize", "a02307.html#a206a6fe71c3780d862d97ef7c5fc9546", null ], [ "Serialize", "a02307.html#a3e994fd938468ff4fc4b4a902e970876", null ], [ "SerializeClasses", "a02307.html#ad0e8164e4c5c82e9e367c8a6d9b755b1", null ], [ "SerializeClasses", "a02307.html#a7d0060c687429049a0ea5cf21d067b8e", null ], [ "set", "a02307.html#a067b7833ee66238b7b5e230404525fcb", null ], [ "set_clear_callback", "a02307.html#af2bbca5b3258035a333b62679835a253", null ], [ "set_compare_callback", "a02307.html#aa3ec670c7f68a95f84641a0ded8cb61f", null ], [ "size", "a02307.html#a20cfad5c58c50cb85a9529d8ddbd96af", null ], [ "size_reserved", "a02307.html#a1c273622446ec7b5a6669fa9c9fdd8e5", null ], [ "sort", "a02307.html#a999bbd8ff336c81fe1198ea714c7936d", null ], [ "sort", "a02307.html#a461142d4ff7c61f22119552b7c0b2755", null ], [ "swap", "a02307.html#ac10b1de04fdfd4f5e4b90ac6d03f35b9", null ], [ "truncate", "a02307.html#a980882b5ebc3e72fdedbdbe345196f21", null ], [ "unsigned_size", "a02307.html#a47bd2385b28d536e8b6e87b689d61ede", null ], [ "WithinBounds", "a02307.html#a367914d03777eef59176d48155d06b72", null ], [ "write", "a02307.html#a8745d1d8394e852d12398d0458684dee", null ], [ "clear_cb_", "a02307.html#a57a833bdcc07a53e9a7b57d07cac2131", null ], [ "compare_cb_", "a02307.html#acd69761952fb39cbe7d7b43a6b06a432", null ], [ "data_", "a02307.html#ab88657a46d06c175dcfc76c0fcdaac7d", null ], [ "size_reserved_", "a02307.html#a4a02eb2a4ed31e8454cd8ae06eb8d7c5", null ], [ "size_used_", "a02307.html#a99185b084a6ace7536818ce2f17b11fb", null ] ];
stweil/tesseract-ocr.github.io
4.0.0/a02307.js
JavaScript
apache-2.0
4,880
var crypto = require("crypto"), Request = require("./../request"), Response = require("./../response"); module.exports = sessionCookie; /** * A middleware for storing and retrieving session data using HTTP cookies. * The `options` may be any of the following: * * - secret A secret string to use to verify the cookie's contents, * defaults to `null`. If this is set the session's contents * will be cleared if the cookie has been tampered with * - name The name of the cookie, defaults to "strata.session" * - path The path of the cookie, defaults to "/" * - domain The cookie's domain, defaults to `null` * - expireAfter A number of seconds after which this cookie will expire, * defaults to `null` * - secure True to only send this cookie over HTTPS, defaults to `false` * - httpOnly True to only send this cookie over HTTP, defaults to `true` */ function sessionCookie(app, options) { var readSession = sessionCookieReader(options); var writeSession = sessionCookieWriter(options); return function (env, callback) { if (env.session) { app(env, callback); return; } readSession(env, function (err, session) { if (err) { env.session = {}; } else { env.session = session; } app(env, function (status, headers, body) { var res = new Response(body, headers, status); writeSession(env, res); res.send(callback); }); }); } } function sessionCookieReader(options) { options = sessionCookieOptions(options); return function readSessionCookie(env, callback) { var req = new Request(env); req.cookies(function (err, cookies) { if (err) { callback(err, cookies); return; } var cookie = cookies[options.name]; if (cookie) { cookie = new Buffer(cookie, "base64").toString("utf8"); var parts = cookie.split("--"), data = parts[0], digest = parts[1]; if (digest === sessionDigest(data, options.secret)) { try { callback(null, JSON.parse(data)); return; } catch (e) { // The cookie does not contain valid JSON. callback(e, {}); return; } } } callback(null, {}); }); } } function sessionCookieWriter(options) { options = sessionCookieOptions(options); return function writeSessionCookie(env, res) { var session = env.session; if (session) { var data = JSON.stringify(session); var digest = sessionDigest(data, options.secret); var cookie = new Buffer(data + "--" + digest, "utf8").toString("base64"); if (cookie.length > 4096) { env.error.write("Session cookie data size exceeds 4k; content dropped\n"); return; } var cookieOptions = { value: cookie, path: options.path, domain: options.domain, secure: options.secure, httpOnly: options.httpOnly }; if (options.expireAfter) { // expireAfter is given in seconds. var expires = new Date().getTime() + (options.expireAfter * 1000); cookieOptions.expires = new Date(expires); } res.setCookie(options.name, cookieOptions); } } } function sessionDigest(data, secret) { var shasum = crypto.createHash("sha1"); shasum.update(data); if (secret) { shasum.update(secret); } return shasum.digest("hex"); } /** * Creates a new options object from the given session cookie `options` with * sane defaults. */ function sessionCookieOptions(options) { options = options || {}; var opts = { secret: options.secret || null, name: options.name || "strata.session", path: options.path || "/", domain: options.domain || null, expireAfter: options.expireAfter || null, secure: options.secure || false }; if ("httpOnly" in options) { opts.httpOnly = options.httpOnly || false; } else { opts.httpOnly = true; } return opts; }
mbutler/nfn
node_modules/hem/node_modules/strata/lib/session/cookie.js
JavaScript
apache-2.0
4,665
var angularjs = angular.module('articleDetailModule', ['courseTagServiceModule', 'ngCookies', 'ngVideo']); angularjs.controller('ArticleDetailController', ['$rootScope', '$scope', '$http', '$stateParams', '$state', '$location', 'CourseTagService', '$sce', '$cookies', '$httpParamSerializer', 'video', '$route', function($rootScope, $scope, $http, $stateParams, $state, $location, courseTagSrv, $sce, $cookies, $httpParamSerializer, video, $route) { if ($stateParams.courseId === undefined) { $state.go('home'); } var token = $location.search().token; if (token !== undefined) { console.log('set token on cookie'); $cookies.put('access_token', token); } $scope.showShare = false; $scope.shareImg = "img/share_400_400_2.png"; $scope.courseUrl = $location.absUrl(); console.log('location=', $scope.courseUrl); var util = new DomainNameUtil($location); $scope.originUrl = window.location.href; console.log('get access token:', $cookies.get('access_token')); $scope.favoriteCls = 'fontawesome-heart-empty'; $scope.favoriteText = '收藏'; $http.get(util.getBackendServiceUrl() + '/course/proposal/' + $stateParams.courseId, { headers: { 'access_token': $cookies.get('access_token') } }). success(function(e) { console.log('get course ', e); $scope.course = e; $rootScope.title = e.name; var $body = $('body'); var $iframe = $('<iframe src="/favicon.ico"></iframe>'); $iframe.on('load', function() { setTimeout(function() { $iframe.off('load').remove(); }, 0); }).appendTo($body); $scope.course.videoUrl = $sce.trustAsResourceUrl($scope.course.videoUrl); document.getElementById('article_content').innerHTML = $scope.course.content; // video.addSource('mp4',$scope.course.videoUrl); setFavoriteDom(); configJSAPI(); }).error(function(e) { }); $http.get(util.getBackendServiceUrl() + '/course/proposal/query?number=3&ignore_course_id=' + $stateParams.courseId) .success(function(e) { console.log('get related courses ', e); $scope.relatedCourses = e; }).error(function(e) { }); courseTagSrv.getCourseTags().then(function(e) { $scope.courseTags = e; }); $scope.background = function(course) { return { 'background-image': 'url(' + course.titleImageUrl + ')', 'background-size': '100%' }; } $scope.goToCourseTag = function(tag, $event) { console.log('go to course tag'); $state.go('course_tags', { courseTagId: tag.id, courseName: tag.name }); $event.stopPropagation(); } $scope.share = function() { console.log('share'); $scope.showShare = true; // var ret = recordShareFavorite('SHARE'); // ret.success(function(e){ // }); } $scope.favorite = function() { console.log('favorite'); if ($cookies.get('access_token') === undefined) { var redirect = encodeURI($scope.courseUrl).replace('#', '%23'); console.log('redirect=', encodeURI($scope.courseUrl).replace('#', '%23')); window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfe34c2ab5b5c5813&redirect_uri=http%3a%2f%2fwww.imzao.com%2feducation%2fzaozao%2fwechat%2flogin&response_type=code&scope=snsapi_userinfo&state=WECHAT_SERVICE-' + redirect + '#wechat_redirect'; return; } var promise = recordShareFavorite('FAVORITE'); promise.success(function(e) { console.log('favorite success ', e); $scope.course.favorited = !$scope.course.favorited; setFavoriteDom(); }).error(function(e) { console.log('share failed'); }); } function setFavoriteDom() { if ($scope.course.favorited === true) { $scope.favoriteCls = 'fontawesome-heart'; $scope.favoriteText = '已收藏'; } else { $scope.favoriteCls = 'fontawesome-heart-empty'; $scope.favoriteText = '收藏'; } } $scope.hideShare = function() { $scope.showShare = false; } $scope.showPlayButton = true; $scope.showVideo = false; $scope.playVideo = function(e) { console.log('course video,', $("#course_video")); $("#course_video")[0].play(); } document.getElementById('course_video').addEventListener('webkitendfullscreen', function(e) { // handle end full screen console.log('webkitendfullscreen'); $scope.showVideo = false; $scope.showPlayButton = true; $scope.$apply(); }); document.getElementById('course_video').addEventListener('webkitenterfullscreen', function(e) { // handle end full screen console.log('webkitenterfullscreen'); $scope.showVideo = true; $scope.$apply(); }); // $scope.videoEnded = function(e) { // console.log('video ended '); // $scope.showPlayButton = true; // } // $scope.videoPaused = function(e) { // console.log('video paused '); // $scope.showPlayButton = true; // } function configJSAPI() { console.log('js api config:', $scope.courseUrl); $http.get(util.getBackendServiceUrl() + '/wechat/jsapi?url=' + $scope.courseUrl.split('#')[0].replace('&', '%26')) .success(function(e) { console.log(e); var signature = e; wx.config({ debug: false, appId: e.appid, timestamp: e.timestamp, nonceStr: e.noncestr, signature: e.signature, jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage'] }); wx.ready(function() { console.log('wx ready'); }); wx.error(function(res) { console.log('wx error'); }); wx.onMenuShareTimeline({ title: $scope.course.name, link: $scope.courseUrl, imgUrl: encodeURI($scope.course.titleImageUrl), success: function() { console.log('share success'); scope.showShare = false; recordShareFavorite('SHARE'); }, cancel: function() { console.log('cancel share'); scope.showShare = false; } }); var shareDesc = ''; console.log('share desc:', $scope.course.introduction); if ($scope.course.introduction !== null && $scope.course.introduction !== 'undefined') { shareDesc = $scope.course.introduction; } wx.onMenuShareAppMessage({ title: $scope.course.name, // 分享标题 desc: shareDesc, // 分享描述 link: $scope.courseUrl, // 分享链接 imgUrl: encodeURI($scope.course.titleImageUrl), // 分享图标 // 分享类型,music、video或link,不填默认为link // 如果type是music或video,则要提供数据链接,默认为空 success: function(res) { // 用户确认分享后执行的回调函数 console.log('share success'); recordShareFavorite('SHARE'); scope.showShare = false; }, cancel: function(res) { // 用户取消分享后执行的回调函数 console.log('cancel share'); scope.showShare = false; }, fail: function(res) { } }); }).error(function(e) { }); } function recordShareFavorite(activity) { var link = util.getBackendServiceUrl() + '/course/interactive'; var req = { method: 'POST', url: link, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'access_token': $cookies.get('access_token') //'Content-Type': 'multipart/form-data; charset=utf-8;' }, data: $httpParamSerializer({ course_id: $scope.course.id, flag: activity }) }; return $http(req); } } ]); angularjs.directive('videoLoader', function() { return function(scope, element, attrs) { scope.$watch(attrs.videoLoader, function() { console.log('element:', element); $("#course_video").bind('ended', function() { console.log('video ended.'); // element.removeAttr('controls'); scope.showPlayButton = true; scope.showVideo = false; scope.$apply(); // $(this).unbind('ended'); // if (!this.hasPlayed) { // return; // } }); $("#course_video").bind('pause', function() { console.log('video paused.'); scope.showPlayButton = false; scope.showVideo = true; // element.attr('controls',true); scope.$apply(); // $(this).unbind('paused'); // if (!this.hasPlayed) { // return; // } }); $("#course_video").bind('play', function() { console.log('video played.'); scope.showPlayButton = false; scope.showVideo = true; // element.attr('controls',true); scope.$apply(); // $(this).unbind('played'); // if (!this.hasPlayed) { // return; // } }); $("#course_video").bind('webkitfullscreenchange mozfullscreenchange fullscreenchange', function(event) { console.log('full screen ', event); var state = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; if (state !== undefined) { scope.showVideo = true; } else { scope.showVideo = false; } scope.$apply(); }); }); } });
c2611261/zaozao2
public/js/article_detail.js
JavaScript
apache-2.0
8,955
// Diamond-in-the-Rough // Code Wars program written in JavaScript for the RingoJS environment // // The MIT License (MIT) // // Copyright (c) 2015 Lee Jenkins // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var stdin = require("system").stdin; var stdout = require("system").stdout; "use strict"; (function SpiralTriangles() { function run() { var inputData = readDiamondInfo(); while( inputData.size > 0 ) { printDiamonds( inputData ); inputData = readDiamondInfo(); } }; function printDiamonds( inputData ) { var midSize = inputData.size / 2; for( var gridRow=0; gridRow<inputData.rows; ++gridRow ) { for( var diamondRow=0; diamondRow<inputData.size; ++diamondRow ) { var line = ""; for( var gridCol=0; gridCol<inputData.cols; ++gridCol ) { for( var diamondCol=0; diamondCol<inputData.size; ++diamondCol ) { var c = "#"; if( diamondRow < midSize ) { // top half if( diamondCol >= (midSize-(diamondRow+1)) && diamondCol < midSize ) { c = "/"; } else if( diamondCol >= midSize && diamondCol <= (midSize+diamondRow) ) { c = "\\"; } } else { // bottom half if( diamondCol >= (diamondRow-midSize) && diamondCol < midSize ) { c = "\\"; } else if( diamondCol >= midSize && diamondCol < (inputData.size+midSize-diamondRow) ) { c = "/"; } } line += c; } } print( line ); } } }; function readDiamondInfo() { var tokens = stdin.readLine().split(/\s+/); return { size: parseInt( tokens[0] ), rows: parseInt( tokens[1] ), cols: parseInt( tokens[2] ) }; }; run(); }) ();
p473lr/i-urge-mafia-gear
HP Code Wars Documents/2015/Solutions/prob11_DiamondInTheRough-lee.js
JavaScript
apache-2.0
3,164
/** * @private * @providesModule CustomTabsAndroid * @flow */ 'use strict'; import { NativeModules } from 'react-native'; import type { TabOption } from './TabOption'; const CustomTabsManager = NativeModules.CustomTabsManager; /** * To open the URL of the http or https in Chrome Custom Tabs. * If Chrome is not installed, opens the URL in other browser. */ export default class CustomTabsAndroid { /** * Opens the URL on a Custom Tab. * * @param url the Uri to be opened. * @param option the Option to customize Custom Tabs of look & feel. */ static openURL(url: string, option: TabOption = {}): Promise<boolean> { return CustomTabsManager.openURL(url, option) } }
droibit/react-native-custom-tabs
src/CustomTabsAndroid.js
JavaScript
apache-2.0
701
/** * Copyright 2019, Google LLC * * 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. */ const functions = require('firebase-functions'); const { google } = require('googleapis'); const { firestore } = require('../admin'); /** * Return a Promise to obtain the device from Cloud IoT Core */ function getDevice(client, deviceId) { return new Promise((resolve, reject) => { const projectId = process.env.GCLOUD_PROJECT; const parentName = `projects/${projectId}/locations/${functions.config().cloudiot.region}`; const registryName = `${parentName}/registries/${functions.config().cloudiot.registry}`; const request = { name: `${registryName}/devices/${deviceId}` }; client.projects.locations.registries.devices.get(request, (err, resp) => { if (err) { return reject(err); } else { resolve(resp.data); } }); }); } /** * Validate that the public key provided by the pending device matches * the key currently stored in IoT Core for that device id. * * Method throws an error if the keys do not match. */ function verifyDeviceKey(pendingDevice, deviceKey) { // Convert the pending key into PEM format const chunks = pendingDevice.public_key.match(/(.{1,64})/g); chunks.unshift('-----BEGIN PUBLIC KEY-----'); chunks.push('-----END PUBLIC KEY-----'); const pendingKey = chunks.join('\n'); if (deviceKey !== pendingKey) throw new Error(`Public Key Mismatch:\nExpected: ${deviceKey}\nReceived: ${pendingKey}`); } /** * Cloud Function: Verify IoT device and add to user */ module.exports = functions.firestore.document('pending/{device}').onWrite(async (change, context) => { const deviceId = context.params.device; // Verify this is either a create or update if (!change.after.exists) { console.log(`Pending device removed for ${deviceId}`); return; } console.log(`Pending device created for ${deviceId}`); const pending = change.after.data(); // Create a new Cloud IoT client const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/cloud-platform'] }); const client = google.cloudiot({ version: 'v1', auth: auth }); try { // Verify device does NOT already exist in Firestore const deviceRef = firestore.doc(`devices/${deviceId}`); const deviceDoc = await deviceRef.get(); if (deviceDoc.exists) throw new Error(`${deviceId} is already registered to another user`); // Verify device exists in IoT Core const result = await getDevice(client, deviceId); // Verify the device public key verifyDeviceKey(pending, result.credentials[0].publicKey.key.trim()); // Verify the device type let configValue = null; switch (pending.type) { case 'light': configValue = require('./default-light.json'); break; case 'thermostat': configValue = require('./default-thermostat.json'); break; default: throw new Error(`Invalid device type found in ${deviceId}: ${pending.type}`); } // Commit the following changes together const batch = firestore.batch(); // Insert valid device for the requested owner const device = { name: pending.serial_number, owner: pending.owner, type: pending.type, online: false }; batch.set(deviceRef, device); // Generate a default configuration const configRef = firestore.doc(`device-configs/${deviceId}`); const config = { owner: pending.owner, value: configValue }; batch.set(configRef, config); // Remove the pending device entry batch.delete(change.after.ref); await batch.commit(); console.log(`Added device ${deviceId} for user ${pending.owner}`); } catch (error) { // Device does not exist in IoT Core or key doesn't match console.error('Unable to register new device', error); } });
GoogleCloudPlatform/iot-smart-home-cloud
firebase/functions/device-cloud/register-device.js
JavaScript
apache-2.0
4,394
var assert = require("assert"), expect = require('expect.js'), cda = require("../utils/xml.js").cda, DOMParser = require('xmldom').DOMParser, XmlSerializer = require('xmldom').XMLSerializer, xmlUtils = require("../utils/xml.js").xml, FunctionalStatusSectionCreator = require("../Model/FunctionalStatusSection.js"), FunctionalStatusEntryCreator = require("../Model/FunctionalStatusEntry.js"), FunctionalStatusPainScaleEntryCreator = require("../Model/FunctionalStatusPainScaleEntry.js"), Σ = xmlUtils.CreateNode, A = xmlUtils.CreateAttributeWithNameAndValue, adapter = require("../CDA/ModeltoCDA.js").cda; var createMockEntry = function(num) { var entry = FunctionalStatusEntryCreator.create(); entry.Name = "Name " + num; entry.Value = "Value " + num; entry.EffectiveTime = new Date().toString(); return entry; }; var createMockPainScaleEntry = function (num) { var entry = FunctionalStatusPainScaleEntryCreator.create(); entry.id = num; entry.PainScore = 1; entry.PainScoreEffectiveTime = '2/1/2013'; return entry; }; describe("Build Functional Status Section.", function() { it("Should be able to generate an entry for each type.", function() { var e = new adapter.FunctionalStatusSection(); var document = new DOMParser().parseFromString("<?xml version='1.0' standalone='yes'?><ClinicalDocument xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 CDA/infrastructure/cda/CDA_SDTC.xsd' xmlns='urn:hl7-org:v3' xmlns:cda='urn:hl7-org:v3' xmlns:sdtc='urn:hl7-org:sdtc'></ClinicalDocument>", "text/xml"); var section = FunctionalStatusSectionCreator.create(); section.Capabilities.push(createMockEntry(1)); section.Cognitions.push(createMockEntry(1)); section.DailyLivings.push(createMockEntry(1)); section.PainScales.push(createMockPainScaleEntry(1)); var cdaAdapter = new adapter.FunctionalStatusSection(); var node = cdaAdapter.BuildAll(section, document); assert.equal(node.getElementsByTagName("title")[0].childNodes[0].nodeValue, "FUNCTIONAL STATUS"); assert.equal(node.getElementsByTagName("templateId")[0].getAttributeNode("root").value, "2.16.840.1.113883.10.20.22.2.14"); assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("code").value, "47420-5"); //var output = new XmlSerializer().serializeToString(node); //console.log(output); }); });
lantanagroup/SEE-Tool
test/functionalStatus.js
JavaScript
apache-2.0
2,525
'use strict'; goog.provide('Blockly.JavaScript.serial'); goog.require('Blockly.JavaScript'); Blockly.JavaScript.serial_print = function() { var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"' var code = 'serial.writeString(\'\' + '+content+');\n'; return code; }; Blockly.JavaScript.serial_println = function() { var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"' var code = 'serial.writeLine(\'\' + '+content+');\n'; return code; }; Blockly.JavaScript.serial_print_hex = function() { var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '0'; var code = 'serial.writeLine('+content+'.toString(16));\n'; return code; }; Blockly.JavaScript.serial_receive_data_event = function() { var char_marker = Blockly.JavaScript.valueToCode(this, 'char_marker', Blockly.JavaScript.ORDER_ATOMIC) || ';'; var branch = Blockly.JavaScript.statementToCode(this, 'DO'); Blockly.JavaScript.definitions_['func_serial_receive_data_event_' + char_marker.charCodeAt(1)] = "serial.onDataReceived(" + char_marker + ", () => {\n" + branch + "};\n"; }; Blockly.JavaScript.serial_readstr = function() { var code ="serial.readString()"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_readline = function() { var code ="serial.readLine()"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_readstr_until = function() { var char_marker = this.getFieldValue('char_marker'); var code ="serial.readUntil("+char_marker + ")"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_softserial = function () { var dropdown_pin1 = Blockly.JavaScript.valueToCode(this, 'RX',Blockly.JavaScript.ORDER_ATOMIC); var dropdown_pin2 = Blockly.JavaScript.valueToCode(this, 'TX',Blockly.JavaScript.ORDER_ATOMIC); var baudrate = this.getFieldValue('baudrate'); return "serial.redirect(" + dropdown_pin1 + ", " + dropdown_pin2 + ", BaudRate.BaudRate" + baudrate + ");\n"; };
xbed/Mixly_Arduino
mixly_arduino/blockly/generators/microbit_js/serial.js
JavaScript
apache-2.0
2,128
/** * Blueprint API Configuration * (sails.config.blueprints) * * These settings are for the global configuration of blueprint routes and * request options (which impact the behavior of blueprint actions). * * You may also override any of these settings on a per-controller basis * by defining a '_config' key in your controller defintion, and assigning it * a configuration object with overrides for the settings in this file. * A lot of the configuration options below affect so-called "CRUD methods", * or your controllers' `find`, `create`, `update`, and `destroy` actions. * * It's important to realize that, even if you haven't defined these yourself, as long as * a model exists with the same name as the controller, Sails will respond with built-in CRUD * logic in the form of a JSON API, including support for sort, pagination, and filtering. * * For more information on the blueprint API, check out: * http://sailsjs.org/#/documentation/reference/blueprint-api * * For more information on the settings in this file, see: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html * */ module.exports.blueprints = { /*************************************************************************** * * * Action routes speed up the backend development workflow by * * eliminating the need to manually bind routes. When enabled, GET, POST, * * PUT, and DELETE routes will be generated for every one of a controller's * * actions. * * * * If an `index` action exists, additional naked routes will be created for * * it. Finally, all `actions` blueprints support an optional path * * parameter, `id`, for convenience. * * * * `actions` are enabled by default, and can be OK for production-- * * however, if you'd like to continue to use controller/action autorouting * * in a production deployment, you must take great care not to * * inadvertently expose unsafe/unintentional controller logic to GET * * requests. * * * ***************************************************************************/ actions: true, /*************************************************************************** * * * RESTful routes (`sails.config.blueprints.rest`) * * * * REST blueprints are the automatically generated routes Sails uses to * * expose a conventional REST API on top of a controller's `find`, * * `create`, `update`, and `destroy` actions. * * * * For example, a BoatController with `rest` enabled generates the * * following routes: * * ::::::::::::::::::::::::::::::::::::::::::::::::::::::: * * GET /boat/:id? -> BoatController.find * * POST /boat -> BoatController.create * * PUT /boat/:id -> BoatController.update * * DELETE /boat/:id -> BoatController.destroy * * * * `rest` blueprint routes are enabled by default, and are suitable for use * * in a production scenario, as long you take standard security precautions * * (combine w/ policies, etc.) * * * ***************************************************************************/ rest: true, /*************************************************************************** * * * Shortcut routes are simple helpers to provide access to a * * controller's CRUD methods from your browser's URL bar. When enabled, * * GET, POST, PUT, and DELETE routes will be generated for the * * controller's`find`, `create`, `update`, and `destroy` actions. * * * * `shortcuts` are enabled by default, but should be disabled in * * production. * * * ***************************************************************************/ shortcuts: true, /*************************************************************************** * * * An optional mount path for all blueprint routes on a controller, * * including `rest`, `actions`, and `shortcuts`. This allows you to take * * advantage of blueprint routing, even if you need to namespace your API * * methods. * * * * (NOTE: This only applies to blueprint autoroutes, not manual routes from * * `sails.config.routes`) * * * ***************************************************************************/ prefix: '/api/v1.0', /*************************************************************************** * * * Whether to pluralize controller names in blueprint routes. * * * * (NOTE: This only applies to blueprint autoroutes, not manual routes from * * `sails.config.routes`) * * * * For example, REST blueprints for `FooController` with `pluralize` * * enabled: * * GET /foos/:id? * * POST /foos * * PUT /foos/:id? * * DELETE /foos/:id? * * * ***************************************************************************/ // pluralize: false, /*************************************************************************** * * * Whether the blueprint controllers should populate model fetches with * * data from other models which are linked by associations * * * * If you have a lot of data in one-to-many associations, leaving this on * * may result in very heavy api calls * * * ***************************************************************************/ // populate: true, /**************************************************************************** * * * Whether to run Model.watch() in the find and findOne blueprint actions. * * Can be overridden on a per-model basis. * * * ****************************************************************************/ // autoWatch: true, /**************************************************************************** * * * The default number of records to show in the response from a "find" * * action. Doubles as the default size of populated arrays if populate is * * true. * * * ****************************************************************************/ // defaultLimit: 30 };
kmangutov/leaguemontages
config/blueprints.js
JavaScript
apache-2.0
9,115
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.MessagePopover. sap.ui.define(["jquery.sap.global", "./ResponsivePopover", "./Button", "./Toolbar", "./ToolbarSpacer", "./Bar", "./List", "./StandardListItem", "./library", "sap/ui/core/Control", "./PlacementType", "sap/ui/core/IconPool", "sap/ui/core/HTML", "./Text", "sap/ui/core/Icon", "./SegmentedButton", "./Page", "./NavContainer", "./semantic/SemanticPage", "./Popover", "./MessagePopoverItem", "jquery.sap.dom"], function (jQuery, ResponsivePopover, Button, Toolbar, ToolbarSpacer, Bar, List, StandardListItem, library, Control, PlacementType, IconPool, HTML, Text, Icon, SegmentedButton, Page, NavContainer, SemanticPage, Popover, MessagePopoverItem) { "use strict"; /** * Constructor for a new MessagePopover * * @param {string} [sId] ID for the new control, generated automatically if no id is given * @param {object} [mSettings] Initial settings for the new control * * @class * A MessagePopover is a Popover containing a summarized list with messages. * @extends sap.ui.core.Control * * @author SAP SE * @version 1.36.11 * * @constructor * @public * @since 1.28 * @alias sap.m.MessagePopover * @ui5-metamodel This control also will be described in the legacy UI5 design-time metamodel */ var MessagePopover = Control.extend("sap.m.MessagePopover", /** @lends sap.m.MessagePopover.prototype */ { metadata: { library: "sap.m", properties: { /** * Callback function for resolving a promise after description has been asynchronously loaded inside this function * @callback sap.m.MessagePopover~asyncDescriptionHandler * @param {object} config A single parameter object * @param {MessagePopoverItem} config.item Reference to respective MessagePopoverItem instance * @param {object} config.promise Object grouping a promise's reject and resolve methods * @param {function} config.promise.resolve Method to resolve promise * @param {function} config.promise.reject Method to reject promise */ asyncDescriptionHandler: {type: "any", group: "Behavior", defaultValue: null}, /** * Callback function for resolving a promise after a link has been asynchronously validated inside this function * @callback sap.m.MessagePopover~asyncURLHandler * @param {object} config A single parameter object * @param {string} config.url URL to validate * @param {string|Int} config.id ID of the validation job * @param {object} config.promise Object grouping a promise's reject and resolve methods * @param {function} config.promise.resolve Method to resolve promise * @param {function} config.promise.reject Method to reject promise */ asyncURLHandler: {type: "any", group: "Behavior", defaultValue: null}, /** * Determines the position, where the control will appear on the screen. Possible values are: sap.m.VerticalPlacementType.Top, sap.m.VerticalPlacementType.Bottom and sap.m.VerticalPlacementType.Vertical. * The default value is sap.m.VerticalPlacementType.Vertical. Setting this property while the control is open, will not cause any re-rendering and changing of the position. Changes will only be applied with the next interaction. */ placement: {type: "sap.m.VerticalPlacementType", group: "Behavior", defaultValue: "Vertical"}, /** * Sets the initial state of the control - expanded or collapsed. By default the control opens as expanded */ initiallyExpanded: {type: "boolean", group: "Behavior", defaultValue: true} }, defaultAggregation: "items", aggregations: { /** * A list with message items */ items: {type: "sap.m.MessagePopoverItem", multiple: true, singularName: "item"} }, events: { /** * This event will be fired after the popover is opened */ afterOpen: { parameters: { /** * This refers to the control which opens the popover */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired after the popover is closed */ afterClose: { parameters: { /** * Refers to the control which opens the popover */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired before the popover is opened */ beforeOpen: { parameters: { /** * Refers to the control which opens the popover */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired before the popover is closed */ beforeClose: { parameters: { /** * Refers to the control which opens the popover * See sap.ui.core.MessageType enum values for types */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired when description is shown */ itemSelect: { parameters: { /** * Refers to the message popover item that is being presented */ item: {type: "sap.m.MessagePopoverItem"}, /** * Refers to the type of messages being shown * See sap.ui.core.MessageType values for types */ messageTypeFilter: {type: "sap.ui.core.MessageType"} } }, /** * This event will be fired when one of the lists is shown when (not) filtered by type */ listSelect: { parameters: { /** * This parameter refers to the type of messages being shown. */ messageTypeFilter: {type: "sap.ui.core.MessageType"} } }, /** * This event will be fired when the long text description data from a remote URL is loaded */ longtextLoaded: {}, /** * This event will be fired when a validation of a URL from long text description is ready */ urlValidated: {} } } }); var CSS_CLASS = "sapMMsgPopover", ICONS = { back: IconPool.getIconURI("nav-back"), close: IconPool.getIconURI("decline"), information: IconPool.getIconURI("message-information"), warning: IconPool.getIconURI("message-warning"), error: IconPool.getIconURI("message-error"), success: IconPool.getIconURI("message-success") }, LIST_TYPES = ["all", "error", "warning", "success", "information"], // Property names array ASYNC_HANDLER_NAMES = ["asyncDescriptionHandler", "asyncURLHandler"], // Private class variable used for static method below that sets default async handlers DEFAULT_ASYNC_HANDLERS = { asyncDescriptionHandler: function (config) { var sLongTextUrl = config.item.getLongtextUrl(); if (sLongTextUrl) { jQuery.ajax({ type: "GET", url: sLongTextUrl, success: function (data) { config.item.setDescription(data); config.promise.resolve(); }, error: function() { var sError = "A request has failed for long text data. URL: " + sLongTextUrl; jQuery.sap.log.error(sError); config.promise.reject(sError); } }); } } }; /** * Setter for default description and URL validation callbacks across all instances of MessagePopover * @static * @protected * @param {object} mDefaultHandlers An object setting default callbacks * @param {function} mDefaultHandlers.asyncDescriptionHandler * @param {function} mDefaultHandlers.asyncURLHandler */ MessagePopover.setDefaultHandlers = function (mDefaultHandlers) { ASYNC_HANDLER_NAMES.forEach(function (sFuncName) { if (mDefaultHandlers.hasOwnProperty(sFuncName)) { DEFAULT_ASYNC_HANDLERS[sFuncName] = mDefaultHandlers[sFuncName]; } }); }; /** * Initializes the control * * @override * @private */ MessagePopover.prototype.init = function () { var that = this; var oPopupControl; this._oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"); this._oPopover = new ResponsivePopover(this.getId() + "-messagePopover", { showHeader: false, contentWidth: "440px", placement: this.getPlacement(), showCloseButton: false, modal: false, afterOpen: function (oEvent) { that.fireAfterOpen({openBy: oEvent.getParameter("openBy")}); }, afterClose: function (oEvent) { that._navContainer.backToTop(); that.fireAfterClose({openBy: oEvent.getParameter("openBy")}); }, beforeOpen: function (oEvent) { that.fireBeforeOpen({openBy: oEvent.getParameter("openBy")}); }, beforeClose: function (oEvent) { that.fireBeforeClose({openBy: oEvent.getParameter("openBy")}); } }).addStyleClass(CSS_CLASS); this._createNavigationPages(); this._createLists(); oPopupControl = this._oPopover.getAggregation("_popup"); oPopupControl.oPopup.setAutoClose(false); oPopupControl.addEventDelegate({ onBeforeRendering: this.onBeforeRenderingPopover, onkeypress: this._onkeypress }, this); if (sap.ui.Device.system.phone) { this._oPopover.setBeginButton(new Button({ text: this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"), press: this.close.bind(this) })); } // Check for default async handlers and set them appropriately ASYNC_HANDLER_NAMES.forEach(function (sFuncName) { if (DEFAULT_ASYNC_HANDLERS.hasOwnProperty(sFuncName)) { that.setProperty(sFuncName, DEFAULT_ASYNC_HANDLERS[sFuncName]); } }); }; /** * Called when the control is destroyed * * @private */ MessagePopover.prototype.exit = function () { this._oResourceBundle = null; this._oListHeader = null; this._oDetailsHeader = null; this._oSegmentedButton = null; this._oBackButton = null; this._navContainer = null; this._listPage = null; this._detailsPage = null; this._sCurrentList = null; if (this._oLists) { this._destroyLists(); } // Destroys ResponsivePopover control that is used by MessagePopover // This will walk through all aggregations in the Popover and destroy them (in our case this is NavContainer) // Next this will walk through all aggregations in the NavContainer, etc. if (this._oPopover) { this._oPopover.destroy(); this._oPopover = null; } }; /** * Required adaptations before rendering MessagePopover * * @private */ MessagePopover.prototype.onBeforeRenderingPopover = function () { // Bind automatically to the MessageModel if no items are bound if (!this.getBindingInfo("items")) { this._makeAutomaticBinding(); } // Update lists only if 'items' aggregation is changed if (this._bItemsChanged) { this._clearLists(); this._fillLists(this.getItems()); this._clearSegmentedButton(); this._fillSegmentedButton(); this._bItemsChanged = false; } this._setInitialFocus(); }; /** * Makes automatic binding to the Message Model with default template * * @private */ MessagePopover.prototype._makeAutomaticBinding = function () { this.setModel(sap.ui.getCore().getMessageManager().getMessageModel(), "message"); this.bindAggregation("items", { path: "message>/", template: new MessagePopoverItem({ type: "{message>type}", title: "{message>title}", description: "{message>description}", longtextUrl: "{message>longtextUrl}" }) } ); }; /** * Handles keyup event * * @param {jQuery.Event} oEvent - keyup event object * @private */ MessagePopover.prototype._onkeypress = function (oEvent) { if (oEvent.shiftKey && oEvent.keyCode == jQuery.sap.KeyCodes.ENTER) { this._fnHandleBackPress(); } }; /** * Returns header of the MessagePopover's ListPage * * @returns {sap.m.Toolbar} ListPage header * @private */ MessagePopover.prototype._getListHeader = function () { return this._oListHeader || this._createListHeader(); }; /** * Returns header of the MessagePopover's ListPage * * @returns {sap.m.Toolbar} DetailsPage header * @private */ MessagePopover.prototype._getDetailsHeader = function () { return this._oDetailsHeader || this._createDetailsHeader(); }; /** * Creates header of MessagePopover's ListPage * * @returns {sap.m.Toolbar} ListPage header * @private */ MessagePopover.prototype._createListHeader = function () { var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"); var sCloseBtnDescrId = this.getId() + "-CloseBtnDescr"; var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, { content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>" }); var sHeadingDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_HEADING"); var sHeadingDescrId = this.getId() + "-HeadingDescr"; var oHeadingARIAHiddenDescr = new HTML(sHeadingDescrId, { content: "<span id=\"" + sHeadingDescrId + "\" style=\"display: none;\" role=\"heading\">" + sHeadingDescr + "</span>" }); this._oPopover.addAssociation("ariaDescribedBy", sHeadingDescrId, true); var oCloseBtn = new Button({ icon: ICONS["close"], visible: !sap.ui.Device.system.phone, ariaLabelledBy: oCloseBtnARIAHiddenDescr, tooltip: sCloseBtnDescr, press: this.close.bind(this) }).addStyleClass(CSS_CLASS + "CloseBtn"); this._oSegmentedButton = new SegmentedButton(this.getId() + "-segmented", {}).addStyleClass("sapMSegmentedButtonNoAutoWidth"); this._oListHeader = new Toolbar({ content: [this._oSegmentedButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oHeadingARIAHiddenDescr] }); return this._oListHeader; }; /** * Creates header of MessagePopover's ListPage * * @returns {sap.m.Toolbar} DetailsPage header * @private */ MessagePopover.prototype._createDetailsHeader = function () { var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"); var sCloseBtnDescrId = this.getId() + "-CloseBtnDetDescr"; var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, { content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>" }); var sBackBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_BACK_BUTTON"); var sBackBtnDescrId = this.getId() + "-BackBtnDetDescr"; var oBackBtnARIAHiddenDescr = new HTML(sBackBtnDescrId, { content: "<span id=\"" + sBackBtnDescrId + "\" style=\"display: none;\">" + sBackBtnDescr + "</span>" }); var oCloseBtn = new Button({ icon: ICONS["close"], visible: !sap.ui.Device.system.phone, ariaLabelledBy: oCloseBtnARIAHiddenDescr, tooltip: sCloseBtnDescr, press: this.close.bind(this) }).addStyleClass(CSS_CLASS + "CloseBtn"); this._oBackButton = new Button({ icon: ICONS["back"], press: this._fnHandleBackPress.bind(this), ariaLabelledBy: oBackBtnARIAHiddenDescr, tooltip: sBackBtnDescr }); this._oDetailsHeader = new Toolbar({ content: [this._oBackButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oBackBtnARIAHiddenDescr] }); return this._oDetailsHeader; }; /** * Creates navigation pages * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._createNavigationPages = function () { // Create two main pages this._listPage = new Page(this.getId() + "listPage", { customHeader: this._getListHeader() }); this._detailsPage = new Page(this.getId() + "-detailsPage", { customHeader: this._getDetailsHeader() }); // TODO: check if this is the best location for this // Disable clicks on disabled and/or pending links this._detailsPage.addEventDelegate({ onclick: function(oEvent) { var target = oEvent.target; if (target.nodeName.toUpperCase() === 'A' && (target.className.indexOf('sapMMsgPopoverItemDisabledLink') !== -1 || target.className.indexOf('sapMMsgPopoverItemPendingLink') !== -1)) { oEvent.preventDefault(); } } }); // Initialize nav container with two main pages this._navContainer = new NavContainer(this.getId() + "-navContainer", { initialPage: this.getId() + "listPage", pages: [this._listPage, this._detailsPage], navigate: this._navigate.bind(this), afterNavigate: this._afterNavigate.bind(this) }); // Assign nav container to content of _oPopover this._oPopover.addContent(this._navContainer); return this; }; /** * Creates Lists of the MessagePopover * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._createLists = function () { this._oLists = {}; LIST_TYPES.forEach(function (sListName) { this._oLists[sListName] = new List({ itemPress: this._fnHandleItemPress.bind(this), visible: false }); // no re-rendering this._listPage.addAggregation("content", this._oLists[sListName], true); }, this); return this; }; /** * Destroy items in the MessagePopover's Lists * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._clearLists = function () { LIST_TYPES.forEach(function (sListName) { if (this._oLists[sListName]) { this._oLists[sListName].destroyAggregation("items", true); } }, this); return this; }; /** * Destroys internal Lists of the MessagePopover * * @private */ MessagePopover.prototype._destroyLists = function () { LIST_TYPES.forEach(function (sListName) { this._oLists[sListName] = null; }, this); this._oLists = null; }; /** * Fill the list with items * * @param {array} aItems An array with items type of sap.ui.core.Item. * @private */ MessagePopover.prototype._fillLists = function (aItems) { aItems.forEach(function (oMessagePopoverItem) { var oListItem = this._mapItemToListItem(oMessagePopoverItem), oCloneListItem = this._mapItemToListItem(oMessagePopoverItem); // add the mapped item to the List this._oLists["all"].addAggregation("items", oListItem, true); this._oLists[oMessagePopoverItem.getType().toLowerCase()].addAggregation("items", oCloneListItem, true); }, this); }; /** * Map a MessagePopoverItem to StandardListItem * * @param {sap.m.MessagePopoverItem} oMessagePopoverItem Base information to generate the list items * @returns {sap.m.StandardListItem | null} oListItem List item which will be displayed * @private */ MessagePopover.prototype._mapItemToListItem = function (oMessagePopoverItem) { if (!oMessagePopoverItem) { return null; } var sType = oMessagePopoverItem.getType(), oListItem = new StandardListItem({ title: oMessagePopoverItem.getTitle(), icon: this._mapIcon(sType), type: sap.m.ListType.Navigation }).addStyleClass(CSS_CLASS + "Item").addStyleClass(CSS_CLASS + "Item" + sType); oListItem._oMessagePopoverItem = oMessagePopoverItem; return oListItem; }; /** * Map an MessageType to the Icon URL. * * @param {sap.ui.core.ValueState} sIcon Type of Error * @returns {string | null} Icon string * @private */ MessagePopover.prototype._mapIcon = function (sIcon) { if (!sIcon) { return null; } return ICONS[sIcon.toLowerCase()]; }; /** * Destroy the buttons in the SegmentedButton * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._clearSegmentedButton = function () { if (this._oSegmentedButton) { this._oSegmentedButton.destroyAggregation("buttons", true); } return this; }; /** * Fill SegmentedButton with needed Buttons for filtering * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._fillSegmentedButton = function () { var that = this; var pressClosure = function (sListName) { return function () { that._fnFilterList(sListName); }; }; LIST_TYPES.forEach(function (sListName) { var oList = this._oLists[sListName], iCount = oList.getItems().length, oButton; if (iCount > 0) { oButton = new Button(this.getId() + "-" + sListName, { text: sListName == "all" ? this._oResourceBundle.getText("MESSAGEPOPOVER_ALL") : iCount, icon: ICONS[sListName], press: pressClosure(sListName) }).addStyleClass(CSS_CLASS + "Btn" + sListName.charAt(0).toUpperCase() + sListName.slice(1)); this._oSegmentedButton.addButton(oButton, true); } }, this); return this; }; /** * Sets icon in details page * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @param {sap.m.StandardListItem} oListItem * @private */ MessagePopover.prototype._setIcon = function (oMessagePopoverItem, oListItem) { this._previousIconTypeClass = CSS_CLASS + "DescIcon" + oMessagePopoverItem.getType(); this._oMessageIcon = new Icon({ src: oListItem.getIcon() }) .addStyleClass(CSS_CLASS + "DescIcon") .addStyleClass(this._previousIconTypeClass); this._detailsPage.addContent(this._oMessageIcon); }; /** * Sets title part of details page * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @private */ MessagePopover.prototype._setTitle = function (oMessagePopoverItem) { this._oMessageTitleText = new Text(this.getId() + 'MessageTitleText', { text: oMessagePopoverItem.getTitle() }).addStyleClass('sapMMsgPopoverTitleText'); this._detailsPage.addAggregation("content", this._oMessageTitleText); }; /** * Sets description text part of details page * When markup description is used it is sanitized within it's container's setter method (MessagePopoverItem) * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @private */ MessagePopover.prototype._setDescription = function (oMessagePopoverItem) { if (oMessagePopoverItem.getMarkupDescription()) { // description is sanitized in MessagePopoverItem.setDescription() this._oMessageDescriptionText = new HTML(this.getId() + 'MarkupDescription', { content: "<div class='markupDescription'>" + oMessagePopoverItem.getDescription() + "</div>" }); } else { this._oMessageDescriptionText = new Text(this.getId() + 'MessageDescriptionText', { text: oMessagePopoverItem.getDescription() }).addStyleClass('sapMMsgPopoverDescriptionText'); } this._detailsPage.addContent(this._oMessageDescriptionText); }; MessagePopover.prototype._iNextValidationTaskId = 0; MessagePopover.prototype._validateURL = function (sUrl) { if (jQuery.sap.validateUrl(sUrl)) { return sUrl; } jQuery.sap.log.warning("You have entered invalid URL"); return ''; }; MessagePopover.prototype._queueValidation = function (href) { var fnAsyncURLHandler = this.getAsyncURLHandler(); var iValidationTaskId = ++this._iNextValidationTaskId; var oPromiseArgument = {}; var oPromise = new window.Promise(function(resolve, reject) { oPromiseArgument.resolve = resolve; oPromiseArgument.reject = reject; var config = { url: href, id: iValidationTaskId, promise: oPromiseArgument }; fnAsyncURLHandler(config); }); oPromise.id = iValidationTaskId; return oPromise; }; MessagePopover.prototype._getTagPolicy = function () { var that = this, i; /*global html*/ var defaultTagPolicy = html.makeTagPolicy(this._validateURL()); return function customTagPolicy(tagName, attrs) { var href, validateLink = false; if (tagName.toUpperCase() === "A") { for (i = 0; i < attrs.length;) { // if there is href the link should be validated, href's value is on position(i+1) if (attrs[i] === "href") { validateLink = true; href = attrs[i + 1]; attrs.splice(0, 2); continue; } i += 2; } } // let the default sanitizer do its work // it won't see the href attribute attrs = defaultTagPolicy(tagName, attrs); // if we detected a link before, we modify the <A> tag // and keep the link in a dataset attribute if (validateLink && typeof that.getAsyncURLHandler() === "function") { attrs = attrs || []; var done = false; // first check if there is a class attribute and enrich it with 'sapMMsgPopoverItemDisabledLink' for (i = 0; i < attrs.length; i += 2) { if (attrs[i] === "class") { attrs[i + 1] += "sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink"; done = true; break; } } // check for existing id var indexOfId = attrs.indexOf("id"); if (indexOfId > -1) { // we start backwards attrs.splice(indexOfId + 1, 1); attrs.splice(indexOfId, 1); } // if no class attribute was found, add one if (!done) { attrs.unshift("sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink"); attrs.unshift("class"); } var oValidation = that._queueValidation(href); // add other attributes attrs.push("href"); // the link is deactivated via class names later read by event delegate on the description page attrs.push(href); // let the page open in another window, so state is preserved attrs.push("target"); attrs.push("_blank"); // use id here as data attributes are not passing through caja attrs.push("id"); attrs.push("sap-ui-" + that.getId() + "-link-under-validation-" + oValidation.id); oValidation .then(function (result) { // Update link in output var $link = jQuery.sap.byId("sap-ui-" + that.getId() + "-link-under-validation-" + result.id); if (result.allowed) { jQuery.sap.log.info("Allow link " + href); } else { jQuery.sap.log.info("Disallow link " + href); } // Adapt the link style $link.removeClass('sapMMsgPopoverItemPendingLink'); $link.toggleClass('sapMMsgPopoverItemDisabledLink', !result.allowed); that.fireUrlValidated(); }) .catch(function () { jQuery.sap.log.warning("Async URL validation could not be performed."); }); } return attrs; }; }; /** * Perform description sanitization based on Caja HTML sanitizer * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @private */ MessagePopover.prototype._sanitizeDescription = function (oMessagePopoverItem) { jQuery.sap.require("jquery.sap.encoder"); jQuery.sap.require("sap.ui.thirdparty.caja-html-sanitizer"); var tagPolicy = this._getTagPolicy(); /*global html*/ var sanitized = html.sanitizeWithPolicy(oMessagePopoverItem.getDescription(), tagPolicy); oMessagePopoverItem.setDescription(sanitized); this._setDescription(oMessagePopoverItem); }; /** * Handles click of the ListItems * * @param {jQuery.Event} oEvent ListItem click event object * @private */ MessagePopover.prototype._fnHandleItemPress = function (oEvent) { var oListItem = oEvent.getParameter("listItem"), oMessagePopoverItem = oListItem._oMessagePopoverItem; var asyncDescHandler = this.getAsyncDescriptionHandler(); var loadAndNavigateToDetailsPage = function (suppressNavigate) { this._setTitle(oMessagePopoverItem); this._sanitizeDescription(oMessagePopoverItem); this._setIcon(oMessagePopoverItem, oListItem); this.fireLongtextLoaded(); if (!suppressNavigate) { this._navContainer.to(this._detailsPage); } }.bind(this); this._previousIconTypeClass = this._previousIconTypeClass || ''; this.fireItemSelect({ item: oMessagePopoverItem, messageTypeFilter: this._getCurrentMessageTypeFilter() }); this._detailsPage.destroyContent(); if (typeof asyncDescHandler === "function" && !!oMessagePopoverItem.getLongtextUrl()) { // Set markupDescription to true as markup description should be processed as markup oMessagePopoverItem.setMarkupDescription(true); var oPromiseArgument = {}; var oPromise = new window.Promise(function (resolve, reject) { oPromiseArgument.resolve = resolve; oPromiseArgument.reject = reject; }); var proceed = function () { this._detailsPage.setBusy(false); loadAndNavigateToDetailsPage(true); }.bind(this); oPromise .then(function () { proceed(); }) .catch(function () { jQuery.sap.log.warning("Async description loading could not be performed."); proceed(); }); this._navContainer.to(this._detailsPage); this._detailsPage.setBusy(true); asyncDescHandler({ promise: oPromiseArgument, item: oMessagePopoverItem }); } else { loadAndNavigateToDetailsPage(); } this._listPage.$().attr("aria-hidden", "true"); }; /** * Handles click of the BackButton * * @private */ MessagePopover.prototype._fnHandleBackPress = function () { this._listPage.$().removeAttr("aria-hidden"); this._navContainer.back(); }; /** * Handles click of the SegmentedButton * * @param {string} sCurrentListName ListName to be shown * @private */ MessagePopover.prototype._fnFilterList = function (sCurrentListName) { LIST_TYPES.forEach(function (sListIterName) { if (sListIterName != sCurrentListName && this._oLists[sListIterName].getVisible()) { // Hide Lists if they are visible and their name is not the same as current list name this._oLists[sListIterName].setVisible(false); } }, this); this._sCurrentList = sCurrentListName; this._oLists[sCurrentListName].setVisible(true); this._expandMsgPopover(); this.fireListSelect({messageTypeFilter: this._getCurrentMessageTypeFilter()}); }; /** * Returns current selected List name * * @returns {string} Current list name * @private */ MessagePopover.prototype._getCurrentMessageTypeFilter = function () { return this._sCurrentList == "all" ? "" : this._sCurrentList; }; /** * Handles navigate event of the NavContainer * * @private */ MessagePopover.prototype._navigate = function () { if (this._isListPage()) { this._oRestoreFocus = jQuery(document.activeElement); } }; /** * Handles navigate event of the NavContainer * * @private */ MessagePopover.prototype._afterNavigate = function () { // Just wait for the next tick to apply the focus jQuery.sap.delayedCall(0, this, this._restoreFocus); }; /** * Checks whether the current page is ListPage * * @returns {boolean} Whether the current page is ListPage * @private */ MessagePopover.prototype._isListPage = function () { return (this._navContainer.getCurrentPage() == this._listPage); }; /** * Sets initial focus of the control * * @private */ MessagePopover.prototype._setInitialFocus = function () { if (this._isListPage()) { // if current page is the list page - set initial focus to the list. // otherwise use default functionality built-in the popover this._oPopover.setInitialFocus(this._oLists[this._sCurrentList]); } }; /** * Restores the focus after navigation * * @private */ MessagePopover.prototype._restoreFocus = function () { if (this._isListPage()) { var oRestoreFocus = this._oRestoreFocus && this._oRestoreFocus.control(0); if (oRestoreFocus) { oRestoreFocus.focus(); } } else { this._oBackButton.focus(); } }; /** * Restores the state defined by the initiallyExpanded property of the MessagePopover * @private */ MessagePopover.prototype._restoreExpansionDefaults = function () { if (this.getInitiallyExpanded()) { this._fnFilterList("all"); this._oSegmentedButton.setSelectedButton(null); } else { this._collapseMsgPopover(); } }; /** * Expands the MessagePopover so that the width and height are equal * @private */ MessagePopover.prototype._expandMsgPopover = function () { this._oPopover .setContentHeight(this._oPopover.getContentWidth()) .removeStyleClass(CSS_CLASS + "-init"); }; /** * Sets the height of the MessagePopover to auto so that only the header with * the SegmentedButton is visible * @private */ MessagePopover.prototype._collapseMsgPopover = function () { LIST_TYPES.forEach(function (sListName) { this._oLists[sListName].setVisible(false); }, this); this._oPopover .addStyleClass(CSS_CLASS + "-init") .setContentHeight("auto"); this._oSegmentedButton.setSelectedButton("none"); }; /** * Opens the MessagePopover * * @param {sap.ui.core.Control} oControl Control which opens the MessagePopover * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @public * @ui5-metamodel */ MessagePopover.prototype.openBy = function (oControl) { var oResponsivePopoverControl = this._oPopover.getAggregation("_popup"), oParent = oControl.getParent(); // If MessagePopover is opened from an instance of sap.m.Toolbar and is instance of sap.m.Popover remove the Arrow if (oResponsivePopoverControl instanceof Popover) { if ((oParent instanceof Toolbar || oParent instanceof Bar || oParent instanceof SemanticPage)) { oResponsivePopoverControl.setShowArrow(false); } else { oResponsivePopoverControl.setShowArrow(true); } } if (this._oPopover) { this._restoreExpansionDefaults(); this._oPopover.openBy(oControl); } return this; }; /** * Closes the MessagePopover * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @public */ MessagePopover.prototype.close = function () { if (this._oPopover) { this._oPopover.close(); } return this; }; /** * The method checks if the MessagePopover is open. It returns true when the MessagePopover is currently open * (this includes opening and closing animations), otherwise it returns false * * @public * @returns {boolean} Whether the MessagePopover is open */ MessagePopover.prototype.isOpen = function () { return this._oPopover.isOpen(); }; /** * This method toggles between open and closed state of the MessagePopover instance. * oControl parameter is mandatory in the same way as in 'openBy' method * * @param {sap.ui.core.Control} oControl Control which opens the MessagePopover * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @public */ MessagePopover.prototype.toggle = function (oControl) { if (this.isOpen()) { this.close(); } else { this.openBy(oControl); } return this; }; /** * The method sets the placement position of the MessagePopover. Only accepted Values are: * sap.m.PlacementType.Top, sap.m.PlacementType.Bottom and sap.m.PlacementType.Vertical * * @param {sap.m.PlacementType} sPlacement Placement type * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes */ MessagePopover.prototype.setPlacement = function (sPlacement) { this.setProperty("placement", sPlacement, true); this._oPopover.setPlacement(sPlacement); return this; }; MessagePopover.prototype.getDomRef = function (sSuffix) { return this._oPopover && this._oPopover.getAggregation("_popup").getDomRef(sSuffix); }; ["addStyleClass", "removeStyleClass", "toggleStyleClass", "hasStyleClass", "getBusyIndicatorDelay", "setBusyIndicatorDelay", "getVisible", "setVisible", "getBusy", "setBusy"].forEach(function(sName){ MessagePopover.prototype[sName] = function() { if (this._oPopover && this._oPopover[sName]) { var oPopover = this._oPopover; var res = oPopover[sName].apply(oPopover, arguments); return res === oPopover ? this : res; } }; }); // The following inherited methods of this control are extended because this control uses ResponsivePopover for rendering ["setModel", "bindAggregation", "setAggregation", "insertAggregation", "addAggregation", "removeAggregation", "removeAllAggregation", "destroyAggregation"].forEach(function (sFuncName) { // First, they are saved for later reference MessagePopover.prototype["_" + sFuncName + "Old"] = MessagePopover.prototype[sFuncName]; // Once they are called MessagePopover.prototype[sFuncName] = function () { // We immediately call the saved method first var result = MessagePopover.prototype["_" + sFuncName + "Old"].apply(this, arguments); // Then there is additional logic // Mark items aggregation as changed and invalidate popover to trigger rendering // See 'MessagePopover.prototype.onBeforeRenderingPopover' this._bItemsChanged = true; // If Popover dependency has already been instantiated ... if (this._oPopover) { // ... invalidate it this._oPopover.invalidate(); } // If the called method is 'removeAggregation' or 'removeAllAggregation' ... if (["removeAggregation", "removeAllAggregation"].indexOf(sFuncName) !== -1) { // ... return the result of the operation return result; } return this; }; }); return MessagePopover; }, /* bExport= */ true);
pro100den/openui5-bundle
Resources/public/sap/m/MessagePopover-dbg.js
JavaScript
apache-2.0
37,700
/*jslint browser: true*/ /*global $, jQuery, alert*/ (function ($) { "use strict"; $(document).ready(function () { $("input[name=dob]").datepicker({ dateFormat: 'yy-mm-dd', inline: true, showOtherMonths: true }); }); $(document).ready(function () { $("input[name='rep_password']").focusout(function () { var p1 = $('input[name="password"]').val(), p2 = $('input[name="rep_password"]').val(); if (p1 !== p2) { $('#passDM').show(300); } else if (p1 === "") { $('#passDM').show(300); } else { $('#passDM').hide(300); } }); }); $(document).ready(function () { $("input[name=password]").focusin(function () { $('#passDM').hide(300); }); $("input[name=rep_password]").focusin(function () { $('#passDM').hide(300); }); }); }(jQuery));
manoj2509/Sensa
js/logIn.js
JavaScript
apache-2.0
1,018
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'chapter4-components', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created }, contentSecurityPolicy: { 'default-src': "'none'", 'script-src': "'self' 'unsafe-inline' 'unsafe-eval' *", 'font-src': "'self' *", 'connect-src': "'self' *", 'img-src': "'self' *", 'style-src': "'self' 'unsafe-inline' *", 'frame-src': "*" } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
ubuntuvim/my_emberjs_code
chapter4_components/config/environment.js
JavaScript
apache-2.0
1,376
// ==UserScript== // @name tabtweet // @namespace http://chiptheglasses.com // @description add a classic RT button to tweets // @include http://*twitter.com* // ==/UserScript== // contains jQuery 1.4.1; It is patched. /*! * jQuery JavaScript Library v1.4.1 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Mon Jan 25 19:43:33 2010 -0500 */ (function(z,v){function la(){if(!c.isReady){try{r.documentElement.doScroll("left")}catch(a){setTimeout(la,1);return}c.ready()}}function Ma(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,i){var j=a.length;if(typeof b==="object"){for(var n in b)X(a,n,b[n],f,e,d);return a}if(d!==v){f=!i&&f&&c.isFunction(d);for(n=0;n<j;n++)e(a[n],b,f?d.call(a[n],n,e(a[n],b)):d,i);return a}return j? e(a[0],b):null}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function ma(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function na(a){var b,d=[],f=[],e=arguments,i,j,n,o,m,s,x=c.extend({},c.data(this,"events").live);if(!(a.button&&a.type==="click")){for(o in x){j=x[o];if(j.live===a.type||j.altLive&&c.inArray(a.type,j.altLive)>-1){i=j.data;i.beforeFilter&&i.beforeFilter[a.type]&&!i.beforeFilter[a.type](a)||f.push(j.selector)}else delete x[o]}i=c(a.target).closest(f, a.currentTarget);m=0;for(s=i.length;m<s;m++)for(o in x){j=x[o];n=i[m].elem;f=null;if(i[m].selector===j.selector){if(j.live==="mouseenter"||j.live==="mouseleave")f=c(a.relatedTarget).closest(j.selector)[0];if(!f||f!==n)d.push({elem:n,fn:j})}}m=0;for(s=d.length;m<s;m++){i=d[m];a.currentTarget=i.elem;a.data=i.fn.data;if(i.fn.apply(i.elem,e)===false){b=false;break}}return b}}function oa(a,b){return"live."+(a?a+".":"")+b.replace(/\./g,"`").replace(/ /g,"&")}function pa(a){return!a||!a.parentNode||a.parentNode.nodeType=== 11}function qa(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var i in f)for(var j in f[i])c.event.add(this,i,f[i][j],f[i][j].data)}}})}function ra(a,b,d){var f,e,i;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&a[0].indexOf("<option")<0&&(c.support.checkClone||!sa.test(a[0]))){e=true;if(i=c.fragments[a[0]])if(i!==1)f=i}if(!f){b=b&&b[0]?b[0].ownerDocument||b[0]:r;f=b.createDocumentFragment(); c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=i?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(ta.concat.apply([],ta.slice(0,b)),function(){d[this]=a});return d}function ua(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Na=z.jQuery,Oa=z.$,r=z.document,S,Pa=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Qa=/^.[^:#\[\.,]*$/,Ra=/\S/,Sa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Ta=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,O=navigator.userAgent, va=false,P=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,Q=Array.prototype.slice,wa=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(typeof a==="string")if((d=Pa.exec(a))&&(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:r;if(a=Ta.exec(a))if(c.isPlainObject(b)){a=[r.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=ra([d[1]], [f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}}else{if(b=r.getElementById(d[2])){if(b.id!==d[2])return S.find(a);this.length=1;this[0]=b}this.context=r;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=r;a=r.getElementsByTagName(a)}else return!b||b.jquery?(b||S).find(a):c(b).find(a);else if(c.isFunction(a))return S.ready(a);if(a.selector!==v){this.selector=a.selector;this.context=a.context}return c.isArray(a)?this.setArray(a):c.makeArray(a, this)},selector:"",jquery:"1.4.1",length:0,size:function(){return this.length},toArray:function(){return Q.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){a=c(a||null);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+d;else if(b)a.selector=this.selector+"."+b+"("+d+")";return a},setArray:function(a){this.length=0;ba.apply(this,a);return this},each:function(a,b){return c.each(this, a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(r,c);else P&&P.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(Q.apply(this,arguments),"slice",Q.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice}; c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,i,j,n;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(i in e){j=a[i];n=e[i];if(a!==n)if(f&&n&&(c.isPlainObject(n)||c.isArray(n))){j=j&&(c.isPlainObject(j)||c.isArray(j))?j:c.isArray(n)?[]:{};a[i]=c.extend(f,j,n)}else if(n!==v)a[i]=n}return a};c.extend({noConflict:function(a){z.$= Oa;if(a)z.jQuery=Na;return c},isReady:false,ready:function(){if(!c.isReady){if(!r.body)return setTimeout(c.ready,13);c.isReady=true;if(P){for(var a,b=0;a=P[b++];)a.call(r,c);P=null}c.fn.triggerHandler&&c(r).triggerHandler("ready")}},bindReady:function(){if(!va){va=true;if(r.readyState==="complete")return c.ready();if(r.addEventListener){r.addEventListener("DOMContentLoaded",L,false);z.addEventListener("load",c.ready,false)}else if(r.attachEvent){r.attachEvent("onreadystatechange",L);z.attachEvent("onload", c.ready);var a=false;try{a=z.frameElement==null}catch(b){}r.documentElement.doScroll&&a&&la()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,"isPrototypeOf"))return false;var b;for(b in a);return b===v||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false; return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return z.JSON&&z.JSON.parse?z.JSON.parse(a):(new Function("return "+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Ra.test(a)){var b=r.getElementsByTagName("head")[0]|| r.documentElement,d=r.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(r.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,i=a.length,j=i===v||c.isFunction(a);if(d)if(j)for(f in a){if(b.apply(a[f],d)===false)break}else for(;e<i;){if(b.apply(a[e++],d)===false)break}else if(j)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d= a[0];e<i&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Sa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!== v;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,i=a.length;e<i;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,i=0,j=a.length;i<j;i++){e=b(a[i],i,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=v}else if(b&&!c.isFunction(b)){d=b;b=v}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b}, uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});O=c.uaMatch(O);if(O.browser){c.browser[O.browser]=true;c.browser.version=O.version}if(c.browser.webkit)c.browser.safari=true;if(wa)c.inArray=function(a,b){return wa.call(b,a)};S=c(r);if(r.addEventListener)L=function(){r.removeEventListener("DOMContentLoaded", L,false);c.ready()};else if(r.attachEvent)L=function(){if(r.readyState==="complete"){r.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=r.documentElement,b=r.createElement("script"),d=r.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=d.getElementsByTagName("*"),i=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!i)){c.support= {leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55$/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:r.createElement("select").appendChild(r.createElement("option")).selected,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null}; b.type="text/javascript";try{b.appendChild(r.createTextNode("window."+f+"=1;"))}catch(j){}a.insertBefore(b,a.firstChild);if(z[f]){c.support.scriptEval=true;delete z[f]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function n(){c.support.noCloneEvent=false;d.detachEvent("onclick",n)});d.cloneNode(true).fireEvent("onclick")}d=r.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=r.createDocumentFragment();a.appendChild(d.firstChild); c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var n=r.createElement("div");n.style.width=n.style.paddingLeft="1px";r.body.appendChild(n);c.boxModel=c.support.boxModel=n.offsetWidth===2;r.body.removeChild(n).style.display="none"});a=function(n){var o=r.createElement("div");n="on"+n;var m=true;if(!m){o.setAttribute(n,"return;");m=typeof o[n]==="function"}return m};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=i=null}})();c.props= {"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ua=0,xa={},Va={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var f=a[G],e=c.cache;if(!b&&!f)return null;f||(f=++Ua);if(typeof b==="object"){a[G]=f;e=e[f]=c.extend(true, {},b)}else e=e[f]?e[f]:typeof d==="undefined"?Va:(e[f]={});if(d!==v){a[G]=f;e[b]=d}return typeof b==="string"?e[b]:e}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==z?xa:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{try{delete a[G]}catch(i){a.removeAttribute&&a.removeAttribute(G)}delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this, a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===v){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===v&&this.length)f=c.data(this[0],a);return f===v&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d); return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===v)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]|| a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var ya=/[\n\t]/g,ca=/\s+/,Wa=/\r/g,Xa=/href|src|style/,Ya=/(button|input)/i,Za=/(button|input|object|select|textarea)/i,$a=/^(a|area)$/i,za=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(o){var m= c(this);m.addClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className)for(var i=" "+e.className+" ",j=0,n=b.length;j<n;j++){if(i.indexOf(" "+b[j]+" ")<0)e.className+=" "+b[j]}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var m=c(this);m.removeClass(a.call(this,o,m.attr("class")))});if(a&&typeof a==="string"||a===v)for(var b=(a||"").split(ca), d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var i=(" "+e.className+" ").replace(ya," "),j=0,n=b.length;j<n;j++)i=i.replace(" "+b[j]+" "," ");e.className=i.substring(1,i.length-1)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var i=c(this);i.toggleClass(a.call(this,e,i.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,i=0,j=c(this),n=b,o= a.split(ca);e=o[i++];){n=f?n:!j.hasClass(e);j[n?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(ya," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===v){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value|| {}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var i=b?d:0;for(d=b?d+1:e.length;i<d;i++){var j=e[i];if(j.selected){a=c(j).val();if(b)return a;f.push(a)}}return f}if(za.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Wa,"")}return v}var n=c.isFunction(a);return this.each(function(o){var m=c(this),s=a;if(this.nodeType===1){if(n)s=a.call(this,o,m.val()); if(typeof s==="number")s+="";if(c.isArray(s)&&za.test(this.type))this.checked=c.inArray(m.val(),s)>=0;else if(c.nodeName(this,"select")){var x=c.makeArray(s);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),x)>=0});if(!x.length)this.selectedIndex=-1}else this.value=s}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return v;if(f&&b in c.attrFn)return c(a)[b](d); f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==v;b=f&&c.props[b]||b;if(a.nodeType===1){var i=Xa.test(b);if(b in a&&f&&!i){if(e){b==="type"&&Ya.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Za.test(a.nodeName)||$a.test(a.nodeName)&&a.href?0:v;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText= ""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&i?a.getAttribute(b,2):a.getAttribute(b);return a===null?v:a}return c.style(a,b,d)}});var ab=function(a){return a.replace(/[^\w\s\.\|`]/g,function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==z&&!a.frameElement)a=z;if(!d.guid)d.guid=c.guid++;if(f!==v){d=c.proxy(d);d.data=f}var e=c.data(a,"events")||c.data(a,"events",{}),i=c.data(a,"handle"),j;if(!i){j= function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(j.elem,arguments):v};i=c.data(a,"handle",j)}if(i){i.elem=a;b=b.split(/\s+/);for(var n,o=0;n=b[o++];){var m=n.split(".");n=m.shift();if(o>1){d=c.proxy(d);if(f!==v)d.data=f}d.type=m.slice(0).sort().join(".");var s=e[n],x=this.special[n]||{};if(!s){s=e[n]={};if(!x.setup||x.setup.call(a,f,m,d)===false)if(a.addEventListener)a.addEventListener(n,i,false);else a.attachEvent&&a.attachEvent("on"+n,i)}if(x.add)if((m=x.add.call(a, d,f,m,s))&&c.isFunction(m)){m.guid=m.guid||d.guid;m.data=m.data||d.data;m.type=m.type||d.type;d=m}s[d.guid]=d;this.global[n]=true}a=null}}},global:{},remove:function(a,b,d){if(!(a.nodeType===3||a.nodeType===8)){var f=c.data(a,"events"),e,i,j;if(f){if(b===v||typeof b==="string"&&b.charAt(0)===".")for(i in f)this.remove(a,i+(b||""));else{if(b.type){d=b.handler;b=b.type}b=b.split(/\s+/);for(var n=0;i=b[n++];){var o=i.split(".");i=o.shift();var m=!o.length,s=c.map(o.slice(0).sort(),ab);s=new RegExp("(^|\\.)"+ s.join("\\.(?:.*\\.)?")+"(\\.|$)");var x=this.special[i]||{};if(f[i]){if(d){j=f[i][d.guid];delete f[i][d.guid]}else for(var A in f[i])if(m||s.test(f[i][A].type))delete f[i][A];x.remove&&x.remove.call(a,o,j);for(e in f[i])break;if(!e){if(!x.teardown||x.teardown.call(a,o)===false)if(a.removeEventListener)a.removeEventListener(i,c.data(a,"handle"),false);else a.detachEvent&&a.detachEvent("on"+i,c.data(a,"handle"));e=null;delete f[i]}}}}for(e in f)break;if(!e){if(A=c.data(a,"handle"))A.elem=null;c.removeData(a, "events");c.removeData(a,"handle")}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();this.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return v;a.result=v;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d, b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(i){}if(!a.isPropagationStopped()&&f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){d=a.target;var j;if(!(c.nodeName(d,"a")&&e==="click")&&!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()])){try{if(d[e]){if(j=d["on"+e])d["on"+e]=null;this.triggered=true;d[e]()}}catch(n){}if(j)d["on"+e]=j;this.triggered=false}}},handle:function(a){var b, d;a=arguments[0]=c.event.fix(a||z.event);a.currentTarget=this;d=a.type.split(".");a.type=d.shift();b=!d.length&&!a.exclusive;var f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)");d=(c.data(this,"events")||{})[a.type];for(var e in d){var i=d[e];if(b||f.test(i.type)){a.handler=i;a.data=i.data;i=i.apply(this,arguments);if(i!==v){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||r;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=r.documentElement;d=r.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==v)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a,b){c.extend(a,b||{});a.guid+=b.selector+b.live;b.liveProxy=a;c.event.add(this,b.live,na,b)},remove:function(a){if(a.length){var b= 0,d=new RegExp("(^|\\.)"+a[0]+"(\\.|$)");c.each(c.data(this,"events").live||{},function(){d.test(this.type)&&b++});b<1&&c.event.remove(this,a[0],na)}},special:{}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true}; c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y};var Aa=function(a){for(var b= a.relatedTarget;b&&b!==this;)try{b=b.parentNode}catch(d){break}if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}},Ba=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ba:Aa,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ba:Aa)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(a,b,d){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="submit"||i==="image")&&c(e).closest("form").length)return ma("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="text"||i==="password")&&c(e).closest("form").length&&f.keyCode===13)return ma("submit",this,arguments)})}else return false},remove:function(a,b){c.event.remove(this,"click.specialSubmit"+(b?"."+b.guid:""));c.event.remove(this, "keypress.specialSubmit"+(b?"."+b.guid:""))}};if(!c.support.changeBubbles){var da=/textarea|input|select/i;function Ca(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d}function ea(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Ca(d);if(a.type!=="focusout"|| d.type!=="radio")c.data(d,"_change_data",e);if(!(f===v||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}}c.event.special.change={filters:{focusout:ea,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return ea.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return ea.call(this,a)},beforeactivate:function(a){a= a.target;a.nodeName.toLowerCase()==="input"&&a.type==="radio"&&c.data(a,"_change_data",Ca(a))}},setup:function(a,b,d){for(var f in T)c.event.add(this,f+".specialChange."+d.guid,T[f]);return da.test(this.nodeName)},remove:function(a,b){for(var d in T)c.event.remove(this,d+".specialChange"+(b?"."+b.guid:""),T[d]);return da.test(this.nodeName)}};var T=c.event.special.change.filters}r.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this, f)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var i in d)this[b](i,f,d[i],e);return this}if(c.isFunction(f)){e=f;f=v}var j=b==="one"?c.proxy(e,function(n){c(this).unbind(n,j);return e.apply(this,arguments)}):e;return d==="unload"&&b!=="one"?this.one(d,f,e):this.each(function(){c.event.add(this,d,j,f)})}});c.fn.extend({unbind:function(a, b){if(typeof a==="object"&&!a.preventDefault){for(var d in a)this.unbind(d,a[d]);return this}return this.each(function(){c.event.remove(this,a,b)})},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+ a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e){var i,j=0;if(c.isFunction(f)){e=f;f=v}for(d=(d||"").split(/\s+/);(i=d[j++])!=null;){i=i==="focus"?"focusin":i==="blur"?"focusout":i==="hover"?d.push("mouseleave")&&"mouseenter":i;b==="live"?c(this.context).bind(oa(i,this.selector),{data:f,selector:this.selector, live:i},e):c(this.context).unbind(oa(i,this.selector),e?{guid:e.guid+this.selector+i}:null)}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});z.attachEvent&&!z.addEventListener&&z.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g){for(var h="",k,l=0;g[l];l++){k=g[l];if(k.nodeType===3||k.nodeType===4)h+=k.nodeValue;else if(k.nodeType!==8)h+=a(k.childNodes)}return h}function b(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===k){y=l[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=k;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}l[q]=y}}}function d(g,h,k,l,q,p){q=0;for(var u=l.length;q<u;q++){var t=l[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache=== k){y=l[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=k;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(o.filter(h,[t]).length>0){y=t;break}}t=t[g]}l[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,i=Object.prototype.toString,j=false,n=true;[0,0].sort(function(){n=false;return 0});var o=function(g,h,k,l){k=k||[];var q=h=h||r;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g|| typeof g!=="string")return k;for(var p=[],u,t,y,R,H=true,M=w(h),I=g;(f.exec(""),u=f.exec(I))!==null;){I=u[3];p.push(u[1]);if(u[2]){R=u[3];break}}if(p.length>1&&s.exec(g))if(p.length===2&&m.relative[p[0]])t=fa(p[0]+p[1],h);else for(t=m.relative[p[0]]?[h]:o(p.shift(),h);p.length;){g=p.shift();if(m.relative[g])g+=p.shift();t=fa(g,t)}else{if(!l&&p.length>1&&h.nodeType===9&&!M&&m.match.ID.test(p[0])&&!m.match.ID.test(p[p.length-1])){u=o.find(p.shift(),h,M);h=u.expr?o.filter(u.expr,u.set)[0]:u.set[0]}if(h){u= l?{expr:p.pop(),set:A(l)}:o.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=u.expr?o.filter(u.expr,u.set):u.set;if(p.length>0)y=A(t);else H=false;for(;p.length;){var D=p.pop();u=D;if(m.relative[D])u=p.pop();else D="";if(u==null)u=h;m.relative[D](y,u,M)}}else y=[]}y||(y=t);y||o.error(D||g);if(i.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))k.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&& y[g].nodeType===1&&k.push(t[g]);else k.push.apply(k,y);else A(y,k);if(R){o(R,q,k,l);o.uniqueSort(k)}return k};o.uniqueSort=function(g){if(C){j=n;g.sort(C);if(j)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};o.matches=function(g,h){return o(g,null,null,h)};o.find=function(g,h,k){var l,q;if(!g)return[];for(var p=0,u=m.order.length;p<u;p++){var t=m.order[p];if(q=m.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");l=m.find[t](q, h,k);if(l!=null){g=g.replace(m.match[t],"");break}}}}l||(l=h.getElementsByTagName("*"));return{set:l,expr:g}};o.filter=function(g,h,k,l){for(var q=g,p=[],u=h,t,y,R=h&&h[0]&&w(h[0]);g&&h.length;){for(var H in m.filter)if((t=m.leftMatch[H].exec(g))!=null&&t[2]){var M=m.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(u===p)p=[];if(m.preFilter[H])if(t=m.preFilter[H](t,u,k,p,l,R)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=u[U])!=null;U++)if(D){I=M(D,t,U,u);var Da= l^!!I;if(k&&I!=null)if(Da)y=true;else u[U]=false;else if(Da){p.push(D);y=true}}if(I!==v){k||(u=p);g=g.replace(m.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)o.error(g);else break;q=g}return u};o.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var m=o.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,h){var k=typeof h==="string",l=k&&!/\W/.test(h);k=k&&!l;if(l)h=h.toLowerCase();l=0;for(var q=g.length, p;l<q;l++)if(p=g[l]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[l]=k||p&&p.nodeName.toLowerCase()===h?p||false:p===h}k&&o.filter(h,g,true)},">":function(g,h){var k=typeof h==="string";if(k&&!/\W/.test(h)){h=h.toLowerCase();for(var l=0,q=g.length;l<q;l++){var p=g[l];if(p){k=p.parentNode;g[l]=k.nodeName.toLowerCase()===h?k:false}}}else{l=0;for(q=g.length;l<q;l++)if(p=g[l])g[l]=k?p.parentNode:p.parentNode===h;k&&o.filter(h,g,true)}},"":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p= h=h.toLowerCase();q=b}q("parentNode",h,l,g,p,k)},"~":function(g,h,k){var l=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,l,g,p,k)}},find:{ID:function(g,h,k){if(typeof h.getElementById!=="undefined"&&!k)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var k=[];h=h.getElementsByName(g[1]);for(var l=0,q=h.length;l<q;l++)h[l].getAttribute("name")===g[1]&&k.push(h[l]);return k.length===0?null:k}}, TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,k,l,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var u;(u=h[p])!=null;p++)if(u)if(q^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))k||l.push(u);else if(k)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&& "2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,k,l,q,p){h=g[1].replace(/\\/g,"");if(!p&&m.attrMap[h])g[1]=m.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,k,l,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=o(g[3],null,null,h);else{g=o.filter(g[3],h,k,true^q);k||l.push.apply(l,g);return false}else if(m.match.POS.test(g[0])||m.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true); return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,k){return!!o(k[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"=== g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,h){return h===0},last:function(g,h,k,l){return h===l.length-1},even:function(g,h){return h%2=== 0},odd:function(g,h){return h%2===1},lt:function(g,h,k){return h<k[3]-0},gt:function(g,h,k){return h>k[3]-0},nth:function(g,h,k){return k[3]-0===h},eq:function(g,h,k){return k[3]-0===h}},filter:{PSEUDO:function(g,h,k,l){var q=h[1],p=m.filters[q];if(p)return p(g,k,h,l);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=h[3];k=0;for(l=h.length;k<l;k++)if(h[k]===g)return false;return true}else o.error("Syntax error, unrecognized expression: "+ q)},CHILD:function(g,h){var k=h[1],l=g;switch(k){case "only":case "first":for(;l=l.previousSibling;)if(l.nodeType===1)return false;if(k==="first")return true;l=g;case "last":for(;l=l.nextSibling;)if(l.nodeType===1)return false;return true;case "nth":k=h[2];var q=h[3];if(k===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var u=0;for(l=p.firstChild;l;l=l.nextSibling)if(l.nodeType===1)l.nodeIndex=++u;p.sizcache=h}g=g.nodeIndex-q;return k===0?g===0:g%k===0&&g/k>= 0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var k=h[1];g=m.attrHandle[k]?m.attrHandle[k](g):g[k]!=null?g[k]:g.getAttribute(k);k=g+"";var l=h[2];h=h[4];return g==null?l==="!=":l==="="?k===h:l==="*="?k.indexOf(h)>=0:l==="~="?(" "+k+" ").indexOf(h)>=0:!h?k&&g!==false:l==="!="?k!==h:l==="^="? k.indexOf(h)===0:l==="$="?k.substr(k.length-h.length)===h:l==="|="?k===h||k.substr(0,h.length+1)===h+"-":false},POS:function(g,h,k,l){var q=m.setFilters[h[2]];if(q)return q(g,k,h,l)}}},s=m.match.POS;for(var x in m.match){m.match[x]=new RegExp(m.match[x].source+/(?![^\[]*\])(?![^\(]*\))/.source);m.leftMatch[x]=new RegExp(/(^(?:.|\r|\n)*?)/.source+m.match[x].source.replace(/\\(\d+)/g,function(g,h){return"\\"+(h-0+1)}))}var A=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g}; try{Array.prototype.slice.call(r.documentElement.childNodes,0)}catch(B){A=function(g,h){h=h||[];if(i.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var k=0,l=g.length;k<l;k++)h.push(g[k]);else for(k=0;g[k];k++)h.push(g[k]);return h}}var C;if(r.documentElement.compareDocumentPosition)C=function(g,h){if(!g.compareDocumentPosition||!h.compareDocumentPosition){if(g==h)j=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g=== h?0:1;if(g===0)j=true;return g};else if("sourceIndex"in r.documentElement)C=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)j=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)j=true;return g};else if(r.createRange)C=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)j=true;return g.ownerDocument?-1:1}var k=g.ownerDocument.createRange(),l=h.ownerDocument.createRange();k.setStart(g,0);k.setEnd(g,0);l.setStart(h,0);l.setEnd(h,0);g=k.compareBoundaryPoints(Range.START_TO_END, l);if(g===0)j=true;return g};(function(){var g=r.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var k=r.documentElement;k.insertBefore(g,k.firstChild);if(r.getElementById(h)){m.find.ID=function(l,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(l[1]))?q.id===l[1]||typeof q.getAttributeNode!=="undefined"&&q.getAttributeNode("id").nodeValue===l[1]?[q]:v:[]};m.filter.ID=function(l,q){var p=typeof l.getAttributeNode!=="undefined"&&l.getAttributeNode("id"); return l.nodeType===1&&p&&p.nodeValue===q}}k.removeChild(g);k=g=null})();(function(){var g=r.createElement("div");g.appendChild(r.createComment(""));if(g.getElementsByTagName("*").length>0)m.find.TAG=function(h,k){k=k.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var l=0;k[l];l++)k[l].nodeType===1&&h.push(k[l]);k=h}return k};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")m.attrHandle.href=function(h){return h.getAttribute("href", 2)};g=null})();r.querySelectorAll&&function(){var g=o,h=r.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){o=function(l,q,p,u){q=q||r;if(!u&&q.nodeType===9&&!w(q))try{return A(q.querySelectorAll(l),p)}catch(t){}return g(l,q,p,u)};for(var k in g)o[k]=g[k];h=null}}();(function(){var g=r.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length=== 0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){m.order.splice(1,0,"CLASS");m.find.CLASS=function(h,k,l){if(typeof k.getElementsByClassName!=="undefined"&&!l)return k.getElementsByClassName(h[1])};g=null}}})();var E=r.compareDocumentPosition?function(g,h){return g.compareDocumentPosition(h)&16}:function(g,h){return g!==h&&(g.contains?g.contains(h):true)},w=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},fa=function(g,h){var k=[], l="",q;for(h=h.nodeType?[h]:h;q=m.match.PSEUDO.exec(g);){l+=q[0];g=g.replace(m.match.PSEUDO,"")}g=m.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)o(g,h[q],k);return o.filter(l,k)};c.find=o;c.expr=o.selectors;c.expr[":"]=c.expr.filters;c.unique=o.uniqueSort;c.getText=a;c.isXMLDoc=w;c.contains=E})();var bb=/Until$/,cb=/^(?:parents|prevUntil|prevAll)/,db=/,/;Q=Array.prototype.slice;var Ea=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,i){return!!b.call(e,i,e)===d});else if(b.nodeType)return c.grep(a, function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Qa.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;c.find(a,this[f],b);if(f>0)for(var i=d;i<b.length;i++)for(var j=0;j<d;j++)if(b[j]===b[i]){b.splice(i--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d= 0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ea(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ea(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,i={},j;if(f&&a.length){e=0;for(var n=a.length;e<n;e++){j=a[e];i[j]||(i[j]=c.expr.match.POS.test(j)?c(j,b||this.context):j)}for(;f&&f.ownerDocument&&f!==b;){for(j in i){e=i[j];if(e.jquery?e.index(f)> -1:c(f).is(e)){d.push({selector:j,elem:f});delete i[j]}}f=f.parentNode}}return d}var o=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(m,s){for(;s&&s.ownerDocument&&s!==b;){if(o?o.index(s)>-1:c(s).is(a))return s;s=s.parentNode}return null})},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(), a);return this.pushStack(pa(a[0])||pa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")}, nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);bb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e): e;if((this.length>1||db.test(f))&&cb.test(a))e=e.reverse();return this.pushStack(e,a,Q.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===v||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!== b&&d.push(a);return d}});var Fa=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ga=/(<([\w:]+)[^>]*?)\/>/g,eb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,Ha=/<([\w:]+)/,fb=/<tbody/i,gb=/<|&\w+;/,sa=/checked\s*(?:[^=]|=\s*.checked.)/i,Ia=function(a,b,d){return eb.test(d)?a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"], col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==v)return this.empty().append((this[0]&&this[0].ownerDocument||r).createTextNode(a));return c.getText(this)}, wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length? d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments, false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&& !c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Fa,"").replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){qa(this,b);qa(this.find("*"),b.find("*"))}return b},html:function(a){if(a===v)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Fa,""):null;else if(typeof a==="string"&&!/<script/i.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(Ha.exec(a)|| ["",""])[1].toLowerCase()]){a=a.replace(Ga,Ia);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var i=c(this),j=i.html();i.empty().append(function(){return a.call(this,e,j)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this, b,f))});else a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(s){return c.nodeName(s,"table")?s.getElementsByTagName("tbody")[0]||s.appendChild(s.ownerDocument.createElement("tbody")):s}var e,i,j=a[0],n=[];if(!c.support.checkClone&&arguments.length===3&&typeof j=== "string"&&sa.test(j))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(j))return this.each(function(s){var x=c(this);a[0]=j.call(this,s,b?x.html():v);x.domManip(a,b,d)});if(this[0]){e=a[0]&&a[0].parentNode&&a[0].parentNode.nodeType===11?{fragment:a[0].parentNode}:ra(a,this,n);if(i=e.fragment.firstChild){b=b&&c.nodeName(i,"tr");for(var o=0,m=this.length;o<m;o++)d.call(b?f(this[o],i):this[o],e.cacheable||this.length>1||o>0?e.fragment.cloneNode(true):e.fragment)}n&&c.each(n, Ma)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);for(var e=0,i=d.length;e<i;e++){var j=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),j);f=f.concat(j)}return this.pushStack(f,a,d.selector)}});c.each({remove:function(a,b){if(!a||c.filter(a,[this]).length){if(!b&&this.nodeType===1){c.cleanData(this.getElementsByTagName("*"));c.cleanData([this])}this.parentNode&& this.parentNode.removeChild(this)}},empty:function(){for(this.nodeType===1&&c.cleanData(this.getElementsByTagName("*"));this.firstChild;)this.removeChild(this.firstChild)}},function(a,b){c.fn[a]=function(){return this.each(b,arguments)}});c.extend({clean:function(a,b,d,f){b=b||r;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||r;var e=[];c.each(a,function(i,j){if(typeof j==="number")j+="";if(j){if(typeof j==="string"&&!gb.test(j))j=b.createTextNode(j);else if(typeof j=== "string"){j=j.replace(Ga,Ia);var n=(Ha.exec(j)||["",""])[1].toLowerCase(),o=F[n]||F._default,m=o[0];i=b.createElement("div");for(i.innerHTML=o[1]+j+o[2];m--;)i=i.lastChild;if(!c.support.tbody){m=fb.test(j);n=n==="table"&&!m?i.firstChild&&i.firstChild.childNodes:o[1]==="<table>"&&!m?i.childNodes:[];for(o=n.length-1;o>=0;--o)c.nodeName(n[o],"tbody")&&!n[o].childNodes.length&&n[o].parentNode.removeChild(n[o])}!c.support.leadingWhitespace&&V.test(j)&&i.insertBefore(b.createTextNode(V.exec(j)[0]),i.firstChild); j=c.makeArray(i.childNodes)}if(j.nodeType)e.push(j);else e=c.merge(e,j)}});if(d)for(a=0;e[a];a++)if(f&&c.nodeName(e[a],"script")&&(!e[a].type||e[a].type.toLowerCase()==="text/javascript"))f.push(e[a].parentNode?e[a].parentNode.removeChild(e[a]):e[a]);else{e[a].nodeType===1&&e.splice.apply(e,[a+1,0].concat(c.makeArray(e[a].getElementsByTagName("script"))));d.appendChild(e[a])}return e},cleanData:function(a){for(var b=0,d;(d=a[b])!=null;b++){c.event.remove(d);c.removeData(d)}}});var hb=/z-?index|font-?weight|opacity|zoom|line-?height/i, Ja=/alpha\([^)]*\)/,Ka=/opacity=([^)]*)/,ga=/float/i,ha=/-([a-z])/ig,ib=/([A-Z])/g,jb=/^-?\d+(?:px)?$/i,kb=/^-?\d/,lb={position:"absolute",visibility:"hidden",display:"block"},mb=["Left","Right"],nb=["Top","Bottom"],ob=r.defaultView&&r.defaultView.getComputedStyle,La=c.support.cssFloat?"cssFloat":"styleFloat",ia=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===v)return c.curCSS(d,f);if(typeof e==="number"&&!hb.test(f))e+="px";c.style(d,f,e)})}; c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return v;if((b==="width"||b==="height")&&parseFloat(d)<0)d=v;var f=a.style||a,e=d!==v;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=Ja.test(a)?a.replace(Ja,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Ka.exec(f.filter)[1])/100+"":""}if(ga.test(b))b=La;b=b.replace(ha,ia);if(e)f[b]=d;return f[b]},css:function(a, b,d,f){if(b==="width"||b==="height"){var e,i=b==="width"?mb:nb;function j(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(i,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,"border"+this+"Width",true))||0})}a.offsetWidth!==0?j():c.swap(a,lb,j);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&& a.currentStyle){f=Ka.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ga.test(b))b=La;if(!d&&e&&e[b])f=e[b];else if(ob){if(ga.test(b))b="float";b=b.replace(ib,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ha,ia);f=a.currentStyle[b]||a.currentStyle[d];if(!jb.test(f)&&kb.test(f)){b=e.left;var i=a.runtimeStyle.left;a.runtimeStyle.left= a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=i}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var pb= J(),qb=/<script(.|\s)*?\/script>/gi,rb=/select|textarea/i,sb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ja=/\?/,tb=/(\?|&)_=.*?(&|$)/,ub=/^(\w+:)?\/\/([^\/?#]+)/,vb=/%20/g;c.fn.extend({_load:c.fn.load,load:function(a,b,d){if(typeof a!=="string")return this._load(a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b= c.param(b,c.ajaxSettings.traditional);f="POST"}var i=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(j,n){if(n==="success"||n==="notmodified")i.html(e?c("<div />").append(j.responseText.replace(qb,"")).find(e):j.responseText);d&&i.each(d,[j.responseText,n,j])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&& (this.checked||rb.test(this.nodeName)||sb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a, b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:z.XMLHttpRequest&&(z.location.protocol!=="file:"||!z.ActiveXObject)?function(){return new z.XMLHttpRequest}: function(){try{return new z.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&e.success.call(o,n,j,w);e.global&&f("ajaxSuccess",[w,e])}function d(){e.complete&&e.complete.call(o,w,j);e.global&&f("ajaxComplete",[w,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")} function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),i,j,n,o=a&&a.context||e,m=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(m==="GET")N.test(e.url)||(e.url+=(ja.test(e.url)?"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)|| N.test(e.url))){i=e.jsonpCallback||"jsonp"+pb++;if(e.data)e.data=(e.data+"").replace(N,"="+i+"$1");e.url=e.url.replace(N,"="+i+"$1");e.dataType="script";z[i]=z[i]||function(q){n=q;b();d();z[i]=v;try{delete z[i]}catch(p){}A&&A.removeChild(B)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===false&&m==="GET"){var s=J(),x=e.url.replace(tb,"$1_="+s+"$2");e.url=x+(x===e.url?(ja.test(e.url)?"&":"?")+"_="+s:"")}if(e.data&&m==="GET")e.url+=(ja.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&& c.event.trigger("ajaxStart");s=(s=ub.exec(e.url))&&(s[1]&&s[1]!==location.protocol||s[2]!==location.host);if(e.dataType==="script"&&m==="GET"&&s){var A=r.getElementsByTagName("head")[0]||r.documentElement,B=r.createElement("script");B.src=e.url;if(e.scriptCharset)B.charset=e.scriptCharset;if(!i){var C=false;B.onload=B.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;b();d();B.onload=B.onreadystatechange=null;A&&B.parentNode&& A.removeChild(B)}}}A.insertBefore(B,A.firstChild);return v}var E=false,w=e.xhr();if(w){e.username?w.open(m,e.url,e.async,e.username,e.password):w.open(m,e.url,e.async);try{if(e.data||a&&a.contentType)w.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[e.url]);c.etag[e.url]&&w.setRequestHeader("If-None-Match",c.etag[e.url])}s||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept", e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(fa){}if(e.beforeSend&&e.beforeSend.call(o,w,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");w.abort();return false}e.global&&f("ajaxSend",[w,e]);var g=w.onreadystatechange=function(q){if(!w||w.readyState===0||q==="abort"){E||d();E=true;if(w)w.onreadystatechange=c.noop}else if(!E&&w&&(w.readyState===4||q==="timeout")){E=true;w.onreadystatechange=c.noop;j=q==="timeout"?"timeout":!c.httpSuccess(w)? "error":e.ifModified&&c.httpNotModified(w,e.url)?"notmodified":"success";var p;if(j==="success")try{n=c.httpData(w,e.dataType,e)}catch(u){j="parsererror";p=u}if(j==="success"||j==="notmodified")i||b();else c.handleError(e,w,j,p);d();q==="timeout"&&w.abort();if(e.async)w=null}};try{var h=w.abort;w.abort=function(){w&&h.call(w);g("abort")}}catch(k){}e.async&&e.timeout>0&&setTimeout(function(){w&&!E&&g("timeout")},e.timeout);try{w.send(m==="POST"||m==="PUT"||m==="DELETE"?e.data:null)}catch(l){c.handleError(e, w,null,l);d()}e.async||g();return w}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]= f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(j,n){if(c.isArray(n))c.each(n, function(o,m){b?f(j,m):d(j+"["+(typeof m==="object"||c.isArray(m)?o:"")+"]",m)});else!b&&n!=null&&typeof n==="object"?c.each(n,function(o,m){d(j+"["+o+"]",m)}):f(j,n)}function f(j,n){n=c.isFunction(n)?n():n;e[e.length]=encodeURIComponent(j)+"="+encodeURIComponent(n)}var e=[];if(b===v)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var i in a)d(i,a[i]);return e.join("&").replace(vb,"+")}});var ka={},wb=/toggle|show|hide/,xb=/^([+-]=)?([\d+-.]+)(.*)$/, W,ta=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(ka[d])f=ka[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove(); ka[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&& c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var i=c.extend({},e),j,n=this.nodeType===1&&c(this).is(":hidden"), o=this;for(j in a){var m=j.replace(ha,ia);if(j!==m){a[m]=a[j];delete a[j];j=m}if(a[j]==="hide"&&n||a[j]==="show"&&!n)return i.complete.call(this);if((j==="height"||j==="width")&&this.style){i.display=c.css(this,"display");i.overflow=this.style.overflow}if(c.isArray(a[j])){(i.specialEasing=i.specialEasing||{})[j]=a[j][1];a[j]=a[j][0]}}if(i.overflow!=null)this.style.overflow="hidden";i.curAnim=c.extend({},a);c.each(a,function(s,x){var A=new c.fx(o,i,s);if(wb.test(x))A[x==="toggle"?n?"show":"hide":x](a); else{var B=xb.exec(x),C=A.cur(true)||0;if(B){x=parseFloat(B[2]);var E=B[3]||"px";if(E!=="px"){o.style[s]=(x||1)+E;C=(x||1)/A.cur(true)*C;o.style[s]=C+E}if(B[1])x=(B[1]==="-="?-1:1)*x+C;A.custom(C,x,E)}else A.custom(C,x,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle", 1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration==="number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a, b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]== null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(i){return e.step(i)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop=== "width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow= this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos= c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!= null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in r.documentElement?function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(), f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(s){c.offset.setOffset(this,a,s)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f= b,e=b.ownerDocument,i,j=e.documentElement,n=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var o=b.offsetTop,m=b.offsetLeft;(b=b.parentNode)&&b!==n&&b!==j;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;i=e?e.getComputedStyle(b,null):b.currentStyle;o-=b.scrollTop;m-=b.scrollLeft;if(b===d){o+=b.offsetTop;m+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){o+=parseFloat(i.borderTopWidth)|| 0;m+=parseFloat(i.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&i.overflow!=="visible"){o+=parseFloat(i.borderTopWidth)||0;m+=parseFloat(i.borderLeftWidth)||0}f=i}if(f.position==="relative"||f.position==="static"){o+=n.offsetTop;m+=n.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){o+=Math.max(j.scrollTop,n.scrollTop);m+=Math.max(j.scrollLeft,n.scrollLeft)}return{top:o,left:m}};c.offset={initialize:function(){var a=r.body,b=r.createElement("div"), d,f,e,i=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild); d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i;a.removeChild(b);c.offset.initialize=c.noop}, bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),i=parseInt(c.curCSS(a,"top",true),10)||0,j=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,d,e);d={top:b.top-e.top+i,left:b.left- e.left+j};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a= this.offsetParent||r.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],i;if(!e)return null;if(f!==v)return this.each(function(){if(i=ua(this))i.scrollTo(!a?f:c(i).scrollLeft(),a?f:c(i).scrollTop());else this[d]=f});else return(i=ua(e))?"pageXOffset"in i?i[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&i.document.documentElement[d]||i.document.body[d]:e[d]}}); c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(i){var j=c(this);j[d](f.call(this,i,j[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]|| e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===v?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});z.jQuery=z.$=c})(window); $(".actions-hover").append($('<li style="margin-left:5px"><span class="classicrt_icon">♲ </span><a href="#" class="classicrt"> Classic RT</a></li>')); $(".classicrt").mouseover(function (e) { $(this).siblings(".classicrt_icon").text("♻ "); }); $(".classicrt").mouseout(function (e) { $(this).siblings(".classicrt_icon").text("♲ "); }); $(".classicrt").click( function(e) { var tweeter = $(this).parents(".status-body").children().children(":first").text(); var tweet = $(this).parents(".status-body").children().children(".entry-content").text(); tweet.substr(1, tweet.length -1); // strip "" $("#status").attr("value", "RT @"+tweeter+" "+tweet); });
nathanielksmith/classicrt
grease/tabtweet.user.js
JavaScript
artistic-2.0
71,750
var HLSP = { /* set squareness to 0 for a flat land */ // intensità colore land audioreattivab più bassa mizu: { cameraPositionY: 10, seaLevel: 0, displayText: '<b>CHAPTER ONE, MIZU</b><br/><i>TO BE TRAPPED INTO THE MORNING UNDERTOW</i>', speed: 10, modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0], tiles: 62, repeatUV: 1, bFactor: 0.5, cFactor: 0.07594379703811609, buildFreq: 10, natural: 0.6834941733430447, rainbow: 0.5641539208545766, squareness: 0.022450016948639295, map: 'white', landRGB: 1966335, horizonRGB: 0, skyMap: 'sky4', }, // fft1 più speedup moveSpeed solar_valley: { cameraPositionY: -180, seaLevel: -450, fogDensity: 0.00054, displayText: '<b>CHAPTER TWO, SOLAR VALLEY</b><br><i>FIRE EXECUTION STOPPED BY CLOUDS</i>', speed: 10, modelsParams: ['stones', function(){return 1+Math.random()*5}, 40, true, false, -750], tiles: 200, repeatUV: 7, bFactor: 0.6617959456178687, cFactor: 0.3471716436028164, buildFreq: 10, natural: 0.18443493566399619, rainbow: 0.03254734158776403, squareness: 0.00001, map: 'land3', landRGB: 9675935, horizonRGB: 3231404, skyMap: 'sky4', }, // camera underwater escher_surfers: { cameraPositionY: 40, seaLevel: 50, displayText: '<b>CHAPTER THREE, ESCHER SURFERS</b><br><i>TAKING REST ON K 11</i>', speed: 15, modelsParams: ['cube', 3, 1, true, true, 0 ], tiles: 73, repeatUV: 112, bFactor: 1.001, cFactor: 0, buildFreq: 10, natural: 0, rainbow: 0.16273670793882017, squareness: 0.08945796327125173, map: 'pattern1', landRGB: 16727705, horizonRGB: 7935, skyMap: 'sky1', }, // sea level più basso // modelli: cubid currybox: { cameraPositionY: 100,//HLE.WORLD_HEIGHT*.5, seaLevel: -100, displayText: '<b>CHAPTER FOUR, CURRYBOX</b><br><i>A FLAKE ON THE ROAD AND A KING AND HIS BONES</i>', speed: 5, modelsParams: [['cube'], function(){return 1+Math.random()*5}, 1, true, false,-100], tiles: 145, repeatUV: 1, bFactor: 0.751, cFactor: 0.054245569312940056, buildFreq: 10, natural: 0.176420247632921, rainbow: 0.21934025248846812, squareness: 0.01, map: 'white', landRGB: 13766158, horizonRGB: 2665099, skyMap: 'sky1', }, // sealevel basso galaxy_glacier: { cameraPositionY: 50, seaLevel: -100, displayText: '<b>CHAPTER FIVE, GALAXY GLACIER</b><br><i>HITTING ICEBERGS BLAMES</i>', speed: 2, modelsParams: [null, 1, true, true], tiles: 160, repeatUV: 1, bFactor: 0.287989180087759, cFactor: 0.6148319562024518, buildFreq: 61.5837970429, natural: 0.4861551769529205, rainbow: 0.099628324585666777, squareness: 0.01198280149135716, map: 'pattern5', //% landRGB: 11187452, horizonRGB: 6705, skyMap: 'sky1', }, firefly: { cameraPositionY: 50, displayText: '<b>CHAPTER SIX, FIREFLY</b>', speed: 10, modelsParams: ['sea', 1, true, true], tiles: 100, repeatUV: 1, bFactor: 1, cFactor: 1, buildFreq: 1, natural: 1, rainbow: 0, squareness: 0, map: 'white', landRGB: 2763306, horizonRGB: 0, skyMap: 'sky1', }, //camera position.y -400 // partire sopra acqua, e poi gradualmente finire sott'acqua //G drift: { cameraPositionY: -450, seaLevel: 0, displayText: '<b>CHAPTER SEVEN, DRIFT</b><br><i>LEAVING THE BOAT</i>', speed: 3, modelsParams: [['ducky'], function(){return 1+Math.random()*2}, 2, true, true, 0], tiles: 128, repeatUV: 0, bFactor: 0.24952961883952426, cFactor: 0.31, buildFreq: 15.188759407623216, natural: 0.3471716436028164, rainbow: 1.001, squareness: 0.00001, map: 'land1', landRGB: 16777215, horizonRGB: 6039170, skyMap: 'sky2', }, //H hyperocean: { cameraPositionY: 50, displayText: '<b>CHAPTER EIGHT, HYPEROCEAN</b><br><i>CRAVING FOR LOVE LASTS FOR LIFE</i>', speed: 8,//18, modelsParams: ['space', 2, 40, true, false, 200], tiles: 200, repeatUV: 12, bFactor: 1.001, cFactor: 0.21934025248846812, buildFreq: 15.188759407623216, natural: 0.7051924010682208, rainbow: 0.1952840495265842, squareness: 0.00001, map: 'land5', landRGB: 14798516, horizonRGB: 7173242, skyMap: 'sky2', }, // balene // capovolgere di conseguenza modelli balene //I twin_horizon: { cameraPositionY: 100, displayText: '<b>CHAPTER NINE, TWIN HORIZON</b><br><i>ON THE RIGHT VISION TO THE RIGHT SEASON</i>', speed: 10, modelsParams: ['sea', function(){return 20+Math.random()*20}, 20, false, false, 550], tiles: 99, repeatUV: 1, bFactor: 0.20445411338494512, cFactor: 0.33632252974022836, buildFreq: 45.50809304437684, natural: 0.4448136683661085, rainbow: 0, squareness: 0.0013619887944460984, map: 'white', landRGB: 0x000fff, horizonRGB: 16728899, skyMap: 'sky1', }, // da un certo punto random colors (quando il pezzo aumenta) // da stesso punto aumenta velocità // sea level basso // modelli elettrodomestici / elettronica //J else: { cameraPositionY: 50, displayText: '<b>CHAPTER TEN, ELSE</b><br><i>DIE LIKE AN ELECTRIC MACHINE</i>', speed: 10, modelsParams: [['ducky'], function(){return 2+Math.random()*20}, 3, true, true, 0], tiles: 104, repeatUV: 128, bFactor: 0.5641539208545766, cFactor: 0, buildFreq: 30.804098302357595, natural: 0.0, rainbow: 0.6458797021572349, squareness: 0.013562721707765414, map: 'pattern2', landRGB: 65399, horizonRGB: 0x000000, skyMap: 'sky3', }, // quando iniziano i kick randomizza landscape // odissea nello spazio // cielo stellato (via lattea) //K roger_water: { cameraPositionY: 50, displayText: '<b>CHAPTER ELEVEN, ROGER WATER</b><br><i>PROTECT WATER</i>', speed: 10, modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0], tiles: 80, repeatUV: 1, bFactor: 0, cFactor: 0.20613316338917223, buildFreq: 10, natural: 1.001, rainbow: 0.1735858218014082, squareness: 0.00001, map: 'white', landRGB: 2105376, horizonRGB: 0, skyMap: 'sky1', }, //L alpha_11: { cameraPositionY: 50, displayText: '<b>CHAPTER TWELVE, ALPHA 11</b><br><i>A MASSIVE WAVE IS DRIVING ME HOME</i>', speed: 1, modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0], tiles: 6, repeatUV: 1, bFactor: 0, cFactor: 0, buildFreq: 44.48136683661085, natural: 0, rainbow: 0, squareness: 0.00001, map: 'white', landRGB: 0, horizonRGB: 3980219, skyMap: 'sky1', }, //M blackpool: { displayText: 'BLACKPOOL', speed: -10, modelsParams: ['space', 2, 400, true, false, 200], cameraPositionY: 110, seaLevel: 10, // speed: 4, // modelsParams: ['sea', 1, true, true], tiles: 182, repeatUV: 16.555478741450983, bFactor: 0.6048772396441062, cFactor: 0.016358953883098624, buildFreq: 73.3797815423632, natural: 0.9833741906510363, rainbow: 0.10821609644148733, squareness: 0.00599663055740593, map: 'land3', landRGB: 12105440, horizonRGB: 2571781, skyMap: 'sky1', }, intro: { cameraPositionY: 650, seaLevel:0, displayText: 'INTRO', speed: 0, modelsParams: ['sea', 1, true, true], tiles: 100, repeatUV: 1, bFactor: 0, cFactor: 0, buildFreq: 10, natural: 1, rainbow: 0, squareness: 0, map: 'sky1', landRGB: 0x111111, horizonRGB: 0x6f6f6f, skyMap: 'sky3' } }
stmaccarelli/HYPERLAND
src/sceneParams_0.js
JavaScript
artistic-2.0
9,148
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-init-unresolvable.case // - src/dstr-binding/error/for-of-let.template /*--- description: Destructuring initializer is an unresolvable reference (for-of statement) esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation es6id: 13.7.5.11 features: [destructuring-binding] flags: [generated] info: | IterationStatement : for ( ForDeclaration of AssignmentExpression ) Statement [...] 3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...] 3. Let destructuring be IsDestructuring of lhs. [...] 5. Repeat [...] h. If destructuring is false, then [...] i. Else i. If lhsKind is assignment, then [...] ii. Else if lhsKind is varBinding, then [...] iii. Else, 1. Assert: lhsKind is lexicalBinding. 2. Assert: lhs is a ForDeclaration. 3. Let status be the result of performing BindingInitialization for lhs passing nextValue and iterationEnv as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then a. Let defaultValue be the result of evaluating Initializer. b. Let v be GetValue(defaultValue). c. ReturnIfAbrupt(v). 6.2.3.1 GetValue (V) 1. ReturnIfAbrupt(V). 2. If Type(V) is not Reference, return V. 3. Let base be GetBase(V). 4. If IsUnresolvableReference(V), throw a ReferenceError exception. ---*/ assert.throws(ReferenceError, function() { for (let { x = unresolvableReference } of [{}]) { return; } });
sebastienros/jint
Jint.Tests.Test262/test/language/statements/for-of/dstr-let-obj-ptrn-id-init-unresolvable.js
JavaScript
bsd-2-clause
1,939
// Copyright (C) 2016 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-white-space description: > Mongolian Vowel Separator is not recognized as white space. info: | 11.2 White Space WhiteSpace :: <TAB> <VT> <FF> <SP> <NBSP> <ZWNBSP> <USP> <USP> :: Other category “Zs” code points General Category of U+180E is “Cf” (Format). negative: phase: parse type: SyntaxError features: [u180e] ---*/ throw "Test262: This statement should not be evaluated."; // U+180E between "var" and "foo"; UTF8(0x180E) = 0xE1 0xA0 0x8E var᠎foo;
sebastienros/jint
Jint.Tests.Test262/test/language/white-space/mongolian-vowel-separator.js
JavaScript
bsd-2-clause
659
// This file was procedurally generated from the following sources: // - src/async-generators/yield-as-identifier-reference-escaped.case // - src/async-generators/syntax/async-class-expr-method.template /*--- description: yield is a reserved keyword within generator function bodies and may not be used as an identifier reference. (Async generator method as a ClassExpression element) esid: prod-AsyncGeneratorMethod features: [async-iteration] flags: [generated] negative: phase: parse type: SyntaxError info: | ClassElement : MethodDefinition MethodDefinition : AsyncGeneratorMethod Async Generator Function Definitions AsyncGeneratorMethod : async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody } IdentifierReference : Identifier It is a Syntax Error if this production has a [Yield] parameter and StringValue of Identifier is "yield". ---*/ throw "Test262: This statement should not be evaluated."; var C = class { async *gen() { void yi\u0065ld; }};
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/class/async-gen-method-yield-as-identifier-reference-escaped.js
JavaScript
bsd-2-clause
1,059
L.CommunistWorker = L.AbstractWorker.extend({ statics: { // number of web workers, not using web workers when falsy NUM_WORKERS: 2 }, initialize: function (workerFunc) { this.workerFunc = workerFunc; }, onAdd: function (map) { this._workers = L.CommunistWorker.createWorkers(this.workerFunc); }, onRemove: function (map) { if (this._workers) { // TODO do not close when other layers are still using the static instance //this._workers.close(); } }, process: function(tile, callback) { if (this._workers){ tile._worker = this._workers.data(tile.datum).then(function(parsed) { if (tile._worker) { tile._worker = null; tile.parsed = parsed; tile.datum = null; callback(null, tile); } else { // tile has been unloaded, don't continue with adding //console.log('worker aborted ' + tile.key); } }); } else { callback(null, tile); } }, abort: function(tile) { if (tile._worker) { // TODO abort worker, would need to recreate after close //tile._worker.close(); tile._worker = null; } } }); L.communistWorker = function (workerFunc) { return new L.CommunistWorker(workerFunc); }; L.extend(L.CommunistWorker, { createWorkers: function(workerFunc) { if ( L.CommunistWorker.NUM_WORKERS && typeof Worker === "function" && typeof communist === "function" && !("workers" in L.CommunistWorker)) { L.CommunistWorker.workers = communist({ //data : L.TileLayer.Vector.parseData data : workerFunc }, L.CommunistWorker.NUM_WORKERS); } return L.CommunistWorker.workers; } });
nrenner/leaflet-tilelayer-vector
CommunistWorker.js
JavaScript
bsd-2-clause
1,976
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var types = require("ast-types"); var n = types.namedTypes; var b = types.builders; var inherits = require("util").inherits; function Entry() { assert.ok(this instanceof Entry); } function FunctionEntry(returnLoc) { Entry.call(this); n.Literal.assert(returnLoc); Object.defineProperties(this, { returnLoc: { value: returnLoc } }); } inherits(FunctionEntry, Entry); exports.FunctionEntry = FunctionEntry; function LoopEntry(breakLoc, continueLoc, label) { Entry.call(this); n.Literal.assert(breakLoc); n.Literal.assert(continueLoc); if (label) { n.Identifier.assert(label); } else { label = null; } Object.defineProperties(this, { breakLoc: { value: breakLoc }, continueLoc: { value: continueLoc }, label: { value: label } }); } inherits(LoopEntry, Entry); exports.LoopEntry = LoopEntry; function SwitchEntry(breakLoc) { Entry.call(this); n.Literal.assert(breakLoc); Object.defineProperties(this, { breakLoc: { value: breakLoc } }); } inherits(SwitchEntry, Entry); exports.SwitchEntry = SwitchEntry; function TryEntry(catchEntry, finallyEntry) { Entry.call(this); if (catchEntry) { assert.ok(catchEntry instanceof CatchEntry); } else { catchEntry = null; } if (finallyEntry) { assert.ok(finallyEntry instanceof FinallyEntry); } else { finallyEntry = null; } Object.defineProperties(this, { catchEntry: { value: catchEntry }, finallyEntry: { value: finallyEntry } }); } inherits(TryEntry, Entry); exports.TryEntry = TryEntry; function CatchEntry(firstLoc, paramId) { Entry.call(this); n.Literal.assert(firstLoc); n.Identifier.assert(paramId); Object.defineProperties(this, { firstLoc: { value: firstLoc }, paramId: { value: paramId } }); } inherits(CatchEntry, Entry); exports.CatchEntry = CatchEntry; function FinallyEntry(firstLoc, nextLocTempVar) { Entry.call(this); n.Literal.assert(firstLoc); n.Identifier.assert(nextLocTempVar); Object.defineProperties(this, { firstLoc: { value: firstLoc }, nextLocTempVar: { value: nextLocTempVar } }); } inherits(FinallyEntry, Entry); exports.FinallyEntry = FinallyEntry; function LeapManager(emitter) { assert.ok(this instanceof LeapManager); var Emitter = require("./emit").Emitter; assert.ok(emitter instanceof Emitter); Object.defineProperties(this, { emitter: { value: emitter }, entryStack: { value: [new FunctionEntry(emitter.finalLoc)] } }); } var LMp = LeapManager.prototype; exports.LeapManager = LeapManager; LMp.withEntry = function(entry, callback) { assert.ok(entry instanceof Entry); this.entryStack.push(entry); try { callback.call(this.emitter); } finally { var popped = this.entryStack.pop(); assert.strictEqual(popped, entry); } }; LMp._leapToEntry = function(predicate, defaultLoc) { var entry, loc; var finallyEntries = []; var skipNextTryEntry = null; for (var i = this.entryStack.length - 1; i >= 0; --i) { entry = this.entryStack[i]; if (entry instanceof CatchEntry || entry instanceof FinallyEntry) { // If we are inside of a catch or finally block, then we must // have exited the try block already, so we shouldn't consider // the next TryStatement as a handler for this throw. skipNextTryEntry = entry; } else if (entry instanceof TryEntry) { if (skipNextTryEntry) { // If an exception was thrown from inside a catch block and this // try statement has a finally block, make sure we execute that // finally block. if (skipNextTryEntry instanceof CatchEntry && entry.finallyEntry) { finallyEntries.push(entry.finallyEntry); } skipNextTryEntry = null; } else if ((loc = predicate.call(this, entry))) { break; } else if (entry.finallyEntry) { finallyEntries.push(entry.finallyEntry); } } else if ((loc = predicate.call(this, entry))) { break; } } if (loc) { // fall through } else if (defaultLoc) { loc = defaultLoc; } else { return null; } n.Literal.assert(loc); var finallyEntry; while ((finallyEntry = finallyEntries.pop())) { this.emitter.emitAssign(finallyEntry.nextLocTempVar, loc); loc = finallyEntry.firstLoc; } return loc; }; function getLeapLocation(entry, property, label) { var loc = entry[property]; if (loc) { if (label) { if (entry.label && entry.label.name === label.name) { return loc; } } else { return loc; } } return null; } LMp.emitBreak = function(label) { var loc = this._leapToEntry(function(entry) { return getLeapLocation(entry, "breakLoc", label); }); if (loc === null) { throw new Error("illegal break statement"); } this.emitter.clearPendingException(); this.emitter.jump(loc); }; LMp.emitContinue = function(label) { var loc = this._leapToEntry(function(entry) { return getLeapLocation(entry, "continueLoc", label); }); if (loc === null) { throw new Error("illegal continue statement"); } this.emitter.clearPendingException(); this.emitter.jump(loc); };
jlongster/unwinder
lib/leap.js
JavaScript
bsd-2-clause
5,549
var http = require('http') var url = require('url') var path = require('path') var sleep = require('sleep-ref') var Router = require("routes-router") var concat = require('concat-stream') var ldj = require('ldjson-stream') var manifest = require('level-manifest') var multilevel = require('multilevel') var extend = require('extend') var prettyBytes = require('pretty-bytes') var jsonStream = require('JSONStream') var prebuiltEditor = require('dat-editor-prebuilt') var debug = require('debug')('rest-handler') var auth = require('./auth.js') var pump = require('pump') var zlib = require('zlib') var through = require('through2') module.exports = RestHandler function RestHandler(dat) { if (!(this instanceof RestHandler)) return new RestHandler(dat) this.dat = dat this.auth = auth(dat.options) this.router = this.createRoutes() this.sleep = sleep(function(opts) { opts.decode = true if (opts.live === 'true') opts.live = true if (opts.tail === 'true') opts.tail = true return dat.createChangesReadStream(opts) }, {style: 'newline'}) } RestHandler.prototype.createRoutes = function() { var router = Router() router.addRoute("/", this.dataTable.bind(this)) router.addRoute("/api/session", this.session.bind(this)) router.addRoute("/api/login", this.login.bind(this)) router.addRoute("/api/logout", this.logout.bind(this)) router.addRoute("/api/pull", this.pull.bind(this)) router.addRoute("/api/push", this.push.bind(this)) router.addRoute("/api/changes", this.changes.bind(this)) router.addRoute("/api/stats", this.stats.bind(this)) router.addRoute("/api/bulk", this.bulk.bind(this)) router.addRoute("/api/metadata", this.package.bind(this)) router.addRoute("/api/manifest", this.manifest.bind(this)) router.addRoute("/api/rpc", this.rpc.bind(this)) router.addRoute("/api/csv", this.exportCsv.bind(this)) router.addRoute("/api", this.hello.bind(this)) router.addRoute("/api/rows", this.document.bind(this)) router.addRoute("/api/rows/:key", this.document.bind(this)) router.addRoute("/api/rows/:key/:filename", this.blob.bind(this)) router.addRoute("/api/blobs/:key", this.blobs.bind(this)) router.addRoute("*", this.notFound.bind(this)) return router } RestHandler.prototype.session = function(req, res) { var self = this this.auth.handle(req, res, function(err, session) { debug('session', [err, session]) var data = {} if (err) return self.auth.error(req, res) if (session) data.session = session else data.loggedOut = true self.json(res, data) }) } RestHandler.prototype.login = function(req, res) { var self = this this.auth.handle(req, res, function(err, session) { debug('login', [err, session]) if (err) { res.setHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"") self.auth.error(req, res) return } self.json(res, {session: session}) }) } RestHandler.prototype.logout = function(req, res) { return this.auth.error(req, res) } RestHandler.prototype.blob = function(req, res, opts) { var self = this if (req.method === 'GET') { var key = opts.key var blob = self.dat.createBlobReadStream(opts.key, opts.filename, opts) blob.on('error', function(err) { return self.error(res, 404, {"error": "Not Found"}) }) pump(blob, res) return } if (req.method === "POST") { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query var doc = { key: opts.key, version: qs.version } self.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) var key = doc.key self.dat.get(key, { version: doc.version }, function(err, existing) { if (existing) { doc = existing } var ws = self.dat.createBlobWriteStream(opts.filename, doc, function(err, updated) { if (err) return self.error(res, 500, err) self.json(res, updated) }) pump(req, ws) }) return }) return } self.error(res, 405, {error: 'method not supported'}) } RestHandler.prototype.blobs = function(req, res, opts) { var self = this if (req.method === 'HEAD') { var key = opts.key var blob = self.dat.blobs.backend.exists(opts, function(err, exists) { res.statusCode = exists ? 200 : 404 res.setHeader('content-length', 0) res.end() }) return } if (req.method === 'GET') { res.statusCode = 200 return pump(self.dat.blobs.backend.createReadStream(opts), res) } self.error(res, 405, {error: 'method not supported'}) } var unzip = function(req) { return req.headers['content-encoding'] === 'gzip' ? zlib.createGunzip() : through() } var zip = function(req, res) { if (!/gzip/.test(req.headers['accept-encoding'] || '')) return through() res.setHeader('Content-Encoding', 'gzip') return zlib.createGzip() } RestHandler.prototype.push = function(req, res) { var self = this this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) pump(req, unzip(req), self.dat.replicator.receive(), function(err) { if (err) { res.statusCode = err.status || 500 res.end(err.message) return } res.end() }) }) } RestHandler.prototype.pull = function(req, res) { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query var send = this.dat.replicator.send({ since: parseInt(qs.since, 10) || 0, blobs: qs.blobs !== 'false', live: !!qs.live }) pump(send, zip(req, res), res) } RestHandler.prototype.changes = function(req, res) { this.sleep.httpHandler(req, res) } RestHandler.prototype.stats = function(req, res) { var statsStream = this.dat.createStatsStream() statsStream.on('error', function(err) { var errObj = { type: 'statsStreamError', message: err.message } res.statusCode = 400 serializer.write(errObj) serializer.end() }) var serializer = ldj.serialize() pump(statsStream, serializer, res) } RestHandler.prototype.package = function(req, res) { var meta = {changes: this.dat.storage.change, liveBackup: this.dat.supportsLiveBackup()} meta.columns = this.dat.schema.headers() this.json(res, meta) } RestHandler.prototype.manifest = function(req, res) { this.json(res, manifest(this.dat.storage)) } RestHandler.prototype.rpc = function(req, res) { var self = this this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) var mserver = multilevel.server(self.dat.storage) pump(req, mserver, res) }) } RestHandler.prototype.exportCsv = function(req, res) { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query qs.csv = true var readStream = this.dat.createReadStream(qs) res.writeHead(200, {'content-type': 'text/csv'}) pump(readStream, res) } RestHandler.prototype.exportJson = function(req, res) { var reqUrl = url.parse(req.url, true) var qs = reqUrl.query if (typeof qs.limit === 'undefined') qs.limit = 50 else qs.limit = +qs.limit var readStream = this.dat.createReadStream(qs) res.writeHead(200, {'content-type': 'application/json'}) pump(readStream, jsonStream.stringify('{"rows": [\n', '\n,\n', '\n]}\n'), res) } RestHandler.prototype.handle = function(req, res) { debug(req.connection.remoteAddress + ' - ' + req.method + ' - ' + req.url + ' - ') this.router(req, res) } RestHandler.prototype.error = function(res, status, message) { if (!status) status = res.statusCode if (message) { if (message.status) status = message.status if (typeof message === "object") message.status = status if (typeof message === "string") message = {error: status, message: message} } res.statusCode = status || 500 this.json(res, message) } RestHandler.prototype.notFound = function(req, res) { this.error(res, 404, {"error": "Not Found"}) } RestHandler.prototype.hello = function(req, res) { var self = this var stats = { "dat": "Hello", "version": this.dat.version, "changes": this.dat.storage.change, "name": this.dat.options.name } this.dat.storage.stat(function(err, stat) { if (err) return self.json(res, stats) stats.rows = stat.rows self.dat.storage.approximateSize(function(err, size) { if (err) return self.json(res, stats) stats.approximateSize = { rows: prettyBytes(size) } self.json(res, stats) }) }) } RestHandler.prototype.dataTable = function(req, res) { res.setHeader('content-type', 'text/html; charset=utf-8') res.end(prebuiltEditor) } RestHandler.prototype.json = function(res, json) { res.setHeader('content-type', 'application/json') res.end(JSON.stringify(json) + '\n') } RestHandler.prototype.get = function(req, res, opts) { var self = this this.dat.get(opts.key, url.parse(req.url, true).query || {}, function(err, json) { if (err && err.message === 'range not found') return self.error(res, 404, {error: "Not Found"}) if (err) return self.error(res, 500, err.message) if (json === null) return self.error(res, 404, {error: "Not Found"}) self.json(res, json) }) } RestHandler.prototype.post = function(req, res) { var self = this self.bufferJSON(req, function(err, json) { if (err) return self.error(res, 500, err) if (!json) json = {} self.dat.put(json, function(err, stored) { if (err) { if (err.conflict) return self.error(res, 409, {conflict: true, error: "Document update conflict. Invalid version"}) return self.error(res, 500, err) } res.statusCode = 201 self.json(res, stored) }) }) } RestHandler.prototype.delete = function(req, res, opts) { var self = this self.dat.delete(opts.key, function(err, stored) { if (err) return self.error(res, 500, err) self.json(res, {deleted: true}) }) } RestHandler.prototype.bulk = function(req, res) { var self = this var opts = {} var ct = req.headers['content-type'] if (ct === 'application/json') opts.json = true else if (ct === 'text/csv') opts.csv = true else return self.error(res, 400, {error: 'missing or unsupported content-type'}) opts.results = true debug('/api/bulk', opts) this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) var writeStream = self.dat.createWriteStream(opts) writeStream.on('error', function(writeErr) { var errObj = { type: 'writeStreamError', message: writeErr.message } res.statusCode = 400 serializer.write(errObj) serializer.end() }) var serializer = ldj.serialize() pump(req, writeStream, serializer, res) }) } RestHandler.prototype.document = function(req, res, opts) { var self = this if (req.method === "GET" || req.method === "HEAD") { if (opts.key) return this.get(req, res, opts) else return this.exportJson(req, res) } this.auth.handle(req, res, function(err) { if (err) return self.auth.error(req, res) if (req.method === "POST") return self.post(req, res, opts) if (req.method === "DELETE") return self.delete(req, res, opts) self.error(res, 405, {error: 'method not supported'}) }) } RestHandler.prototype.bufferJSON = function(req, cb) { var self = this req.on('error', function(err) { cb(err) }) req.pipe(concat(function(buff) { var json if (buff && buff.length === 0) return cb() if (buff) { try { json = JSON.parse(buff) } catch(err) { return cb(err) } } if (!json) return cb(err) cb(null, json) })) }
giantoak/dat
lib/rest-handler.js
JavaScript
bsd-2-clause
11,585
/** * The main application class. An instance of this class is created by app.js when it calls * Ext.application(). This is the ideal place to handle application launch and initialization * details. * * */ Ext.define('Sample.Application', { extend: 'Devon.App', name: 'Sample', requires:[ 'Sample.Simlets' ], controllers: [ 'Sample.controller.main.MainController', 'Sample.controller.table.TablesController', 'Sample.controller.cook.CookController' ], launch: function() { Devon.Log.trace('Sample.app launch'); console.log('Sample.app launch'); if (document.location.toString().indexOf('useSimlets')>=0){ Sample.Simlets.useSimlets(); } this.callParent(arguments); } });
CoEValencia/chirr
demos/workspace/ExtSample/app/Application.js
JavaScript
bsd-2-clause
796
// Copyright (C) 2018 Andrew Paprocki. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-date.parse es6id: 20.3.3.2 description: > Date.parse return value is limited to specified time value maximum range info: | Date.parse ( string ) parse interprets the resulting String as a date and time; it returns a Number, the UTC time value corresponding to the date and time. A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly -100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC. includes: [propertyHelper.js] ---*/ const minDateStr = "-271821-04-20T00:00:00.000Z"; const minDate = new Date(-8640000000000000); assert.sameValue(minDate.toISOString(), minDateStr, "minDateStr"); assert.sameValue(Date.parse(minDateStr), minDate.valueOf(), "parse minDateStr"); const maxDateStr = "+275760-09-13T00:00:00.000Z"; const maxDate = new Date(8640000000000000); assert.sameValue(maxDate.toISOString(), maxDateStr, "maxDateStr"); assert.sameValue(Date.parse(maxDateStr), maxDate.valueOf(), "parse maxDateStr"); const belowRange = "-271821-04-19T23:59:59.999Z"; const aboveRange = "+275760-09-13T00:00:00.001Z"; assert.sameValue(Date.parse(belowRange), NaN, "parse below minimum time value"); assert.sameValue(Date.parse(aboveRange), NaN, "parse above maximum time value");
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Date/parse/time-value-maximum-range.js
JavaScript
bsd-2-clause
1,673
var crypto = require('crypto'); var Canvas = require('canvas'); var _ = require('lodash'); var bu = require('./bufutil'); var fmt = require('util').format; var unpack = require('./unpack'); var bright = require('./bright'); function fprint(buf, len) { if (len > 64) throw new Error(fmt("sha512 can only generate 64B of data: %dB requested", len)); return _(crypto.createHash('sha512').update(buf).digest()) .groupBy(function (x, k) { return Math.floor(k/len); }) .reduce(bu.xor); } function idhash(str, n, minFill, maxFill) { var buf = new Buffer(str.length + 1); buf.write(str); for (var i=0; i<0x100; i++) { buf[buf.length - 1] = i; var f = fprint(buf, Math.ceil(n/8)+6); var pixels = _(f.slice(6)) .map(function (x) { return unpack(x); }) .flatten().take(n); var setPixels = pixels.filter().size(); var c = [ f.slice(0, 3), f.slice(3, 6)]; c.sort(bright.cmp); if (setPixels > (minFill * n) && setPixels < (maxFill * n)) return { colors: c.map(function (x) { return x.toString('hex'); }), pixels: pixels.value() }; } throw new Error(fmt("String '''%s''' unhashable in single-byte search space.", str)); } function reflect(id, dimension) { var mid = Math.ceil(dimension / 2); var odd = Boolean(dimension % 2); var pic = []; for (var row=0; row<dimension; row++) { pic[row] = []; for (var col=0; col<dimension; col++) { var p = (row * mid) + col; if (col>=mid) { var d = mid - (odd ? 1 : 0) - col; var ad = Math.abs(d); p = (row * mid) + mid - 1 - ad; } pic[row][col] = id.pixels[p]; // console.error(fmt("looking for %d, of %d for %d,%d", p, id.pixels.length, row, col)) } } return pic; } function retricon(str, opts) { opts = _.merge({}, retricon.defaults, opts); var dimension = opts.tiles; var pixelSize = opts.pixelSize; var border = opts.pixelPadding; var mid = Math.ceil(dimension / 2); var id = idhash(str, mid * dimension, opts.minFill, opts.maxFill); var pic = reflect(id, dimension); var csize = (pixelSize * dimension) + (opts.imagePadding * 2); var c = Canvas.createCanvas(csize, csize); var ctx = c.getContext('2d'); if (_.isString(opts.bgColor)) { ctx.fillStyle = opts.bgColor; } else if (_.isNumber(opts.bgColor)) { ctx.fillStyle = '#' + id.colors[opts.bgColor]; } if (! _.isNull(opts.bgColor)) ctx.fillRect(0, 0, csize, csize); var drawOp = ctx.fillRect.bind(ctx); if (_.isString(opts.pixelColor)) { ctx.fillStyle = opts.pixelColor; } else if (_.isNumber(opts.pixelColor)) { ctx.fillStyle = '#' + id.colors[opts.pixelColor]; } else { drawOp = ctx.clearRect.bind(ctx); } for (var x=0; x<dimension; x++) for (var y=0; y<dimension; y++) if (pic[y][x]) drawOp((x*pixelSize) + border + opts.imagePadding, (y*pixelSize) + border + opts.imagePadding, pixelSize - (border * 2), pixelSize - (border * 2)); return c; } retricon.defaults = { pixelSize: 10, bgColor: null, pixelPadding: 0, imagePadding: 0, tiles: 5, minFill: 0.3, maxFill: 0.90, pixelColor: 0 }; retricon.style = { github: { pixelSize: 70, bgColor: '#F0F0F0', pixelPadding: -1, imagePadding: 35, tiles: 5 }, gravatar: { tiles: 8, bgColor: 1 }, mono: { bgColor: '#F0F0F0', pixelColor: '#000000', tiles: 6, pixelSize: 12, pixelPadding: -1, imagePadding: 6 }, mosaic: { imagePadding: 2, pixelPadding: 1, pixelSize: 16, bgColor: '#F0F0F0' }, mini: { pixelSize: 10, pixelPadding: 1, tiles: 3, bgColor: 0, pixelColor: 1 }, window: { pixelColor: null, bgColor: 0, imagePadding: 2, pixelPadding: 1, pixelSize: 16 } }; module.exports = retricon;
sehrgut/node-retricon
lib/index.js
JavaScript
bsd-2-clause
3,668
var compilerSupport=require('../../src/compilerSupport');var main = function () { var __builder = new compilerSupport.TaskBuilder(), __state = 0, __continue = __builder.CONT, __ex; var data; return __builder.run(function () { switch (__state) { case 0: { data = 12345; console.log("data: " + data); __state = -1; __builder.ret(data); break; } default: throw 'Internal error: encountered wrong state'; } }); }; main().then(function(x) { console.log("returned: " + x); }, function(y) { console.log("failed: " + y); });
omgtehlion/asjs
tests/00-misc/00-fulfills-promise.exp.js
JavaScript
bsd-2-clause
678
var searchData= [ ['lcd_2ec',['lcd.c',['../lcd_8c.html',1,'']]], ['lcd_2eh',['lcd.h',['../lcd_8h.html',1,'']]], ['light_2ec',['light.c',['../light_8c.html',1,'']]], ['light_2eh',['light.h',['../light_8h.html',1,'']]] ];
bplainia/galaxyLightingSystem
doxygen/html/search/files_4.js
JavaScript
bsd-2-clause
228
var files = [ [ "Code", "dir_a44bec13de8698b1b3f25058862347f8.html", "dir_a44bec13de8698b1b3f25058862347f8" ] ];
crurik/GrapeFS
Doxygen/html/files.js
JavaScript
bsd-2-clause
116
/** * @license AngularJS v1.3.0-build.2480+sha.fb6062f * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /* jshint maxlen: false */ /** * @ngdoc module * @name ngAnimate * @description * * # ngAnimate * * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives. * * * <div doc-module-components="ngAnimate"></div> * * # Usage * * To see animations in action, all that is required is to define the appropriate CSS classes * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation * by using the `$animate` service. * * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: * * | Directive | Supported Animations | * |---------------------------------------------------------- |----------------------------------------------------| * | {@link ng.directive:ngRepeat#usage_animations ngRepeat} | enter, leave and move | * | {@link ngRoute.directive:ngView#usage_animations ngView} | enter and leave | * | {@link ng.directive:ngInclude#usage_animations ngInclude} | enter and leave | * | {@link ng.directive:ngSwitch#usage_animations ngSwitch} | enter and leave | * | {@link ng.directive:ngIf#usage_animations ngIf} | enter and leave | * | {@link ng.directive:ngClass#usage_animations ngClass} | add and remove | * | {@link ng.directive:ngShow#usage_animations ngShow & ngHide} | add and remove (the ng-hide class value) | * | {@link ng.directive:form#usage_animations form} | add and remove (dirty, pristine, valid, invalid & all other validations) | * | {@link ng.directive:ngModel#usage_animations ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | * * You can find out more information about animations upon visiting each directive page. * * Below is an example of how to apply animations to a directive that supports animation hooks: * * ```html * <style type="text/css"> * .slide.ng-enter, .slide.ng-leave { * -webkit-transition:0.5s linear all; * transition:0.5s linear all; * } * * .slide.ng-enter { } /&#42; starting animations for enter &#42;/ * .slide.ng-enter-active { } /&#42; terminal animations for enter &#42;/ * .slide.ng-leave { } /&#42; starting animations for leave &#42;/ * .slide.ng-leave-active { } /&#42; terminal animations for leave &#42;/ * </style> * * <!-- * the animate service will automatically add .ng-enter and .ng-leave to the element * to trigger the CSS transition/animations * --> * <ANY class="slide" ng-include="..."></ANY> * ``` * * Keep in mind that if an animation is running, any child elements cannot be animated until the parent element's * animation has completed. * * <h2>CSS-defined Animations</h2> * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported * and can be used to play along with this naming structure. * * The following code below demonstrates how to perform animations using **CSS transitions** with Angular: * * ```html * <style type="text/css"> * /&#42; * The animate class is apart of the element and the ng-enter class * is attached to the element once the enter animation event is triggered * &#42;/ * .reveal-animation.ng-enter { * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/ * transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/ * * /&#42; The animation preparation code &#42;/ * opacity: 0; * } * * /&#42; * Keep in mind that you want to combine both CSS * classes together to avoid any CSS-specificity * conflicts * &#42;/ * .reveal-animation.ng-enter.ng-enter-active { * /&#42; The animation code itself &#42;/ * opacity: 1; * } * </style> * * <div class="view-container"> * <div ng-view class="reveal-animation"></div> * </div> * ``` * * The following code below demonstrates how to perform animations using **CSS animations** with Angular: * * ```html * <style type="text/css"> * .reveal-animation.ng-enter { * -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/ * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/ * } * &#64-webkit-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * </style> * * <div class="view-container"> * <div ng-view class="reveal-animation"></div> * </div> * ``` * * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. * * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element * has no CSS transition/animation classes applied to it. * * <h3>CSS Staggering Animations</h3> * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a * curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for * the animation. The style property expected within the stagger class can either be a **transition-delay** or an * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). * * ```css * .my-animation.ng-enter { * /&#42; standard transition code &#42;/ * -webkit-transition: 1s linear all; * transition: 1s linear all; * opacity:0; * } * .my-animation.ng-enter-stagger { * /&#42; this will have a 100ms delay between each successive leave animation &#42;/ * -webkit-transition-delay: 0.1s; * transition-delay: 0.1s; * * /&#42; in case the stagger doesn't work then these two values * must be set to 0 to avoid an accidental CSS inheritance &#42;/ * -webkit-transition-duration: 0s; * transition-duration: 0s; * } * .my-animation.ng-enter.ng-enter-active { * /&#42; standard transition styles &#42;/ * opacity:1; * } * ``` * * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation * will also be reset if more than 10ms has passed after the last animation has been fired. * * The following code will issue the **ng-leave-stagger** event on the element provided: * * ```js * var kids = parent.children(); * * $animate.leave(kids[0]); //stagger index=0 * $animate.leave(kids[1]); //stagger index=1 * $animate.leave(kids[2]); //stagger index=2 * $animate.leave(kids[3]); //stagger index=3 * $animate.leave(kids[4]); //stagger index=4 * * $timeout(function() { * //stagger has reset itself * $animate.leave(kids[5]); //stagger index=0 * $animate.leave(kids[6]); //stagger index=1 * }, 100, false); * ``` * * Stagger animations are currently only supported within CSS-defined animations. * * <h2>JavaScript-defined Animations</h2> * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. * * ```js * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. * var ngModule = angular.module('YourApp', ['ngAnimate']); * ngModule.animation('.my-crazy-animation', function() { * return { * enter: function(element, done) { * //run the animation here and call done when the animation is complete * return function(cancelled) { * //this (optional) function will be called when the animation * //completes or when the animation is cancelled (the cancelled * //flag will be set to true if cancelled). * }; * }, * leave: function(element, done) { }, * move: function(element, done) { }, * * //animation that can be triggered before the class is added * beforeAddClass: function(element, className, done) { }, * * //animation that can be triggered after the class is added * addClass: function(element, className, done) { }, * * //animation that can be triggered before the class is removed * beforeRemoveClass: function(element, className, done) { }, * * //animation that can be triggered after the class is removed * removeClass: function(element, className, done) { } * }; * }); * ``` * * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits * the element's CSS class attribute value and then run the matching animation event function (if found). * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). * * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation * or transition code that is defined via a stylesheet). * */ angular.module('ngAnimate', ['ng']) /** * @ngdoc provider * @name $animateProvider * @description * * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. * When an animation is triggered, the $animate service will query the $animate service to find any animations that match * the provided name value. * * Requires the {@link ngAnimate `ngAnimate`} module to be installed. * * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. * */ //this private service is only used within CSS-enabled animations //IE8 + IE9 do not support rAF natively, but that is fine since they //also don't support transitions and keyframes which means that the code //below will never be used by the two browsers. .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) { var bod = $document[0].body; return function(fn) { //the returned function acts as the cancellation function return $$rAF(function() { //the line below will force the browser to perform a repaint //so that all the animated elements within the animation frame //will be properly updated and drawn on screen. This is //required to perform multi-class CSS based animations with //Firefox. DO NOT REMOVE THIS LINE. var a = bod.offsetWidth + 1; fn(); }); }; }]) .config(['$provide', '$animateProvider', function($provide, $animateProvider) { var noop = angular.noop; var forEach = angular.forEach; var selectors = $animateProvider.$$selectors; var ELEMENT_NODE = 1; var NG_ANIMATE_STATE = '$$ngAnimateState'; var NG_ANIMATE_CLASS_NAME = 'ng-animate'; var rootAnimateState = {running: true}; function extractElementNode(element) { for(var i = 0; i < element.length; i++) { var elm = element[i]; if(elm.nodeType == ELEMENT_NODE) { return elm; } } } function stripCommentsFromElement(element) { return angular.element(extractElementNode(element)); } function isMatchingElement(elm1, elm2) { return extractElementNode(elm1) == extractElementNode(elm2); } $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', function($delegate, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document) { var globalAnimationCounter = 0; $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); // disable animations during bootstrap, but once we bootstrapped, wait again // for another digest until enabling animations. The reason why we digest twice // is because all structural animations (enter, leave and move) all perform a // post digest operation before animating. If we only wait for a single digest // to pass then the structural animation would render its animation on page load. // (which is what we're trying to avoid when the application first boots up.) $rootScope.$$postDigest(function() { $rootScope.$$postDigest(function() { rootAnimateState.running = false; }); }); var classNameFilter = $animateProvider.classNameFilter(); var isAnimatableClassName = !classNameFilter ? function() { return true; } : function(className) { return classNameFilter.test(className); }; function lookup(name) { if (name) { var matches = [], flagMap = {}, classes = name.substr(1).split('.'); //the empty string value is the default animation //operation which performs CSS transition and keyframe //animations sniffing. This is always included for each //element animation procedure if the browser supports //transitions and/or keyframe animations if ($sniffer.transitions || $sniffer.animations) { classes.push(''); } for(var i=0; i < classes.length; i++) { var klass = classes[i], selectorFactoryName = selectors[klass]; if(selectorFactoryName && !flagMap[klass]) { matches.push($injector.get(selectorFactoryName)); flagMap[klass] = true; } } return matches; } } function animationRunner(element, animationEvent, className) { //transcluded directives may sometimes fire an animation using only comment nodes //best to catch this early on to prevent any animation operations from occurring var node = element[0]; if(!node) { return; } var isSetClassOperation = animationEvent == 'setClass'; var isClassBased = isSetClassOperation || animationEvent == 'addClass' || animationEvent == 'removeClass'; var classNameAdd, classNameRemove; if(angular.isArray(className)) { classNameAdd = className[0]; classNameRemove = className[1]; className = classNameAdd + ' ' + classNameRemove; } var currentClassName = element.attr('class'); var classes = currentClassName + ' ' + className; if(!isAnimatableClassName(classes)) { return; } var beforeComplete = noop, beforeCancel = [], before = [], afterComplete = noop, afterCancel = [], after = []; var animationLookup = (' ' + classes).replace(/\s+/g,'.'); forEach(lookup(animationLookup), function(animationFactory) { var created = registerAnimation(animationFactory, animationEvent); if(!created && isSetClassOperation) { registerAnimation(animationFactory, 'addClass'); registerAnimation(animationFactory, 'removeClass'); } }); function registerAnimation(animationFactory, event) { var afterFn = animationFactory[event]; var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)]; if(afterFn || beforeFn) { if(event == 'leave') { beforeFn = afterFn; //when set as null then animation knows to skip this phase afterFn = null; } after.push({ event : event, fn : afterFn }); before.push({ event : event, fn : beforeFn }); return true; } } function run(fns, cancellations, allCompleteFn) { var animations = []; forEach(fns, function(animation) { animation.fn && animations.push(animation); }); var count = 0; function afterAnimationComplete(index) { if(cancellations) { (cancellations[index] || noop)(); if(++count < animations.length) return; cancellations = null; } allCompleteFn(); } //The code below adds directly to the array in order to work with //both sync and async animations. Sync animations are when the done() //operation is called right away. DO NOT REFACTOR! forEach(animations, function(animation, index) { var progress = function() { afterAnimationComplete(index); }; switch(animation.event) { case 'setClass': cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress)); break; case 'addClass': cancellations.push(animation.fn(element, classNameAdd || className, progress)); break; case 'removeClass': cancellations.push(animation.fn(element, classNameRemove || className, progress)); break; default: cancellations.push(animation.fn(element, progress)); break; } }); if(cancellations && cancellations.length === 0) { allCompleteFn(); } } return { node : node, event : animationEvent, className : className, isClassBased : isClassBased, isSetClassOperation : isSetClassOperation, before : function(allCompleteFn) { beforeComplete = allCompleteFn; run(before, beforeCancel, function() { beforeComplete = noop; allCompleteFn(); }); }, after : function(allCompleteFn) { afterComplete = allCompleteFn; run(after, afterCancel, function() { afterComplete = noop; allCompleteFn(); }); }, cancel : function() { if(beforeCancel) { forEach(beforeCancel, function(cancelFn) { (cancelFn || noop)(true); }); beforeComplete(true); } if(afterCancel) { forEach(afterCancel, function(cancelFn) { (cancelFn || noop)(true); }); afterComplete(true); } } }; } /** * @ngdoc service * @name $animate * @function * * @description * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. * When any of these operations are run, the $animate service * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. * * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives * will work out of the box without any extra configuration. * * Requires the {@link ngAnimate `ngAnimate`} module to be installed. * * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. * */ return { /** * @ngdoc method * @name $animate#enter * @function * * @description * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once * the animation is started, the following CSS classes will be present on the element for the duration of the animation: * * Below is a breakdown of each step that occurs during enter animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.enter(...) is called | class="my-animation" | * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 4. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-enter" | * | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | * * @param {DOMElement} element the element that will be the focus of the enter animation * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ enter : function(element, parentElement, afterElement, doneCallback) { this.enabled(false, element); $delegate.enter(element, parentElement, afterElement); $rootScope.$$postDigest(function() { element = stripCommentsFromElement(element); performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback); }); }, /** * @ngdoc method * @name $animate#leave * @function * * @description * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once * the animation is started, the following CSS classes will be added for the duration of the animation: * * Below is a breakdown of each step that occurs during leave animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.leave(...) is called | class="my-animation" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 3. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-leave" | * | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 9. The element is removed from the DOM | ... | * | 10. The doneCallback() callback is fired (if provided) | ... | * * @param {DOMElement} element the element that will be the focus of the leave animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ leave : function(element, doneCallback) { cancelChildAnimations(element); this.enabled(false, element); $rootScope.$$postDigest(function() { performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() { $delegate.leave(element); }, doneCallback); }); }, /** * @ngdoc method * @name $animate#move * @function * * @description * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or * add the element directly after the afterElement element if present. Then the move animation will be run. Once * the animation is started, the following CSS classes will be added for the duration of the animation: * * Below is a breakdown of each step that occurs during move animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.move(...) is called | class="my-animation" | * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 4. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-move" | * | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | * * @param {DOMElement} element the element that will be the focus of the move animation * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ move : function(element, parentElement, afterElement, doneCallback) { cancelChildAnimations(element); this.enabled(false, element); $delegate.move(element, parentElement, afterElement); $rootScope.$$postDigest(function() { element = stripCommentsFromElement(element); performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback); }); }, /** * @ngdoc method * @name $animate#addClass * * @description * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions * or keyframes are defined on the -add or base CSS class). * * Below is a breakdown of each step that occurs during addClass animation: * * | Animation Step | What the element class attribute looks like | * |------------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.addClass(element, 'super') is called | class="my-animation" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 3. the .super-add class are added to the element | class="my-animation ng-animate super-add" | * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate super-add" | * | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation super super-add super-add-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | * | 9. The super class is kept on the element | class="my-animation super" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | * * @param {DOMElement} element the element that will be animated * @param {string} className the CSS class that will be added to the element and then animated * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ addClass : function(element, className, doneCallback) { element = stripCommentsFromElement(element); performAnimation('addClass', className, element, null, null, function() { $delegate.addClass(element, className); }, doneCallback); }, /** * @ngdoc method * @name $animate#removeClass * * @description * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if * no CSS transitions or keyframes are defined on the -remove or base CSS classes). * * Below is a breakdown of each step that occurs during removeClass animation: * * | Animation Step | What the element class attribute looks like | * |-----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation super ng-animate" | * | 3. the .super-remove class are added to the element | class="my-animation super ng-animate super-remove"| * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation super ng-animate super-remove" | * | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | * * * @param {DOMElement} element the element that will be animated * @param {string} className the CSS class that will be animated and then removed from the element * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ removeClass : function(element, className, doneCallback) { element = stripCommentsFromElement(element); performAnimation('removeClass', className, element, null, null, function() { $delegate.removeClass(element, className); }, doneCallback); }, /** * * @ngdoc function * @name $animate#setClass * @function * @description Adds and/or removes the given CSS classes to and from the element. * Once complete, the done() callback will be fired (if provided). * @param {DOMElement} element the element which will it's CSS classes changed * removed from it * @param {string} add the CSS classes which will be added to the element * @param {string} remove the CSS class which will be removed from the element * @param {Function=} done the callback function (if provided) that will be fired after the * CSS classes have been set on the element */ setClass : function(element, add, remove, doneCallback) { element = stripCommentsFromElement(element); performAnimation('setClass', [add, remove], element, null, null, function() { $delegate.setClass(element, add, remove); }, doneCallback); }, /** * @ngdoc method * @name $animate#enabled * @function * * @param {boolean=} value If provided then set the animation on or off. * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation * @return {boolean} Current animation state. * * @description * Globally enables/disables animations. * */ enabled : function(value, element) { switch(arguments.length) { case 2: if(value) { cleanup(element); } else { var data = element.data(NG_ANIMATE_STATE) || {}; data.disabled = true; element.data(NG_ANIMATE_STATE, data); } break; case 1: rootAnimateState.disabled = !value; break; default: value = !rootAnimateState.disabled; break; } return !!value; } }; /* all animations call this shared animation triggering function internally. The animationEvent variable refers to the JavaScript animation event that will be triggered and the className value is the name of the animation that will be applied within the CSS code. Element, parentElement and afterElement are provided DOM elements for the animation and the onComplete callback will be fired once the animation is fully complete. */ function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) { var runner = animationRunner(element, animationEvent, className); if(!runner) { fireDOMOperation(); fireBeforeCallbackAsync(); fireAfterCallbackAsync(); closeAnimation(); return; } className = runner.className; var elementEvents = angular.element._data(runner.node); elementEvents = elementEvents && elementEvents.events; if (!parentElement) { parentElement = afterElement ? afterElement.parent() : element.parent(); } var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; var runningAnimations = ngAnimateState.active || {}; var totalActiveAnimations = ngAnimateState.totalActive || 0; var lastAnimation = ngAnimateState.last; //only allow animations if the currently running animation is not structural //or if there is no animation running at all var skipAnimations = runner.isClassBased ? ngAnimateState.disabled || (lastAnimation && !lastAnimation.isClassBased) : false; //skip the animation if animations are disabled, a parent is already being animated, //the element is not currently attached to the document body or then completely close //the animation if any matching animations are not found at all. //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found. if (skipAnimations || animationsDisabled(element, parentElement)) { fireDOMOperation(); fireBeforeCallbackAsync(); fireAfterCallbackAsync(); closeAnimation(); return; } var skipAnimation = false; if(totalActiveAnimations > 0) { var animationsToCancel = []; if(!runner.isClassBased) { if(animationEvent == 'leave' && runningAnimations['ng-leave']) { skipAnimation = true; } else { //cancel all animations when a structural animation takes place for(var klass in runningAnimations) { animationsToCancel.push(runningAnimations[klass]); cleanup(element, klass); } runningAnimations = {}; totalActiveAnimations = 0; } } else if(lastAnimation.event == 'setClass') { animationsToCancel.push(lastAnimation); cleanup(element, className); } else if(runningAnimations[className]) { var current = runningAnimations[className]; if(current.event == animationEvent) { skipAnimation = true; } else { animationsToCancel.push(current); cleanup(element, className); } } if(animationsToCancel.length > 0) { forEach(animationsToCancel, function(operation) { operation.cancel(); }); } } if(runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) { skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR } if(skipAnimation) { fireBeforeCallbackAsync(); fireAfterCallbackAsync(); fireDoneCallbackAsync(); return; } if(animationEvent == 'leave') { //there's no need to ever remove the listener since the element //will be removed (destroyed) after the leave animation ends or //is cancelled midway element.one('$destroy', function(e) { var element = angular.element(this); var state = element.data(NG_ANIMATE_STATE); if(state) { var activeLeaveAnimation = state.active['ng-leave']; if(activeLeaveAnimation) { activeLeaveAnimation.cancel(); cleanup(element, 'ng-leave'); } } }); } //the ng-animate class does nothing, but it's here to allow for //parent animations to find and cancel child animations when needed element.addClass(NG_ANIMATE_CLASS_NAME); var localAnimationCount = globalAnimationCounter++; totalActiveAnimations++; runningAnimations[className] = runner; element.data(NG_ANIMATE_STATE, { last : runner, active : runningAnimations, index : localAnimationCount, totalActive : totalActiveAnimations }); //first we run the before animations and when all of those are complete //then we perform the DOM operation and run the next set of animations fireBeforeCallbackAsync(); runner.before(function(cancelled) { var data = element.data(NG_ANIMATE_STATE); cancelled = cancelled || !data || !data.active[className] || (runner.isClassBased && data.active[className].event != animationEvent); fireDOMOperation(); if(cancelled === true) { closeAnimation(); } else { fireAfterCallbackAsync(); runner.after(closeAnimation); } }); function fireDOMCallback(animationPhase) { var eventName = '$animate:' + animationPhase; if(elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) { $$asyncCallback(function() { element.triggerHandler(eventName, { event : animationEvent, className : className }); }); } } function fireBeforeCallbackAsync() { fireDOMCallback('before'); } function fireAfterCallbackAsync() { fireDOMCallback('after'); } function fireDoneCallbackAsync() { fireDOMCallback('close'); if(doneCallback) { $$asyncCallback(function() { doneCallback(); }); } } //it is less complicated to use a flag than managing and canceling //timeouts containing multiple callbacks. function fireDOMOperation() { if(!fireDOMOperation.hasBeenRun) { fireDOMOperation.hasBeenRun = true; domOperation(); } } function closeAnimation() { if(!closeAnimation.hasBeenRun) { closeAnimation.hasBeenRun = true; var data = element.data(NG_ANIMATE_STATE); if(data) { /* only structural animations wait for reflow before removing an animation, but class-based animations don't. An example of this failing would be when a parent HTML tag has a ng-class attribute causing ALL directives below to skip animations during the digest */ if(runner && runner.isClassBased) { cleanup(element, className); } else { $$asyncCallback(function() { var data = element.data(NG_ANIMATE_STATE) || {}; if(localAnimationCount == data.index) { cleanup(element, className, animationEvent); } }); element.data(NG_ANIMATE_STATE, data); } } fireDoneCallbackAsync(); } } } function cancelChildAnimations(element) { var node = extractElementNode(element); if (node) { var nodes = angular.isFunction(node.getElementsByClassName) ? node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) : node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME); forEach(nodes, function(element) { element = angular.element(element); var data = element.data(NG_ANIMATE_STATE); if(data && data.active) { forEach(data.active, function(runner) { runner.cancel(); }); } }); } } function cleanup(element, className) { if(isMatchingElement(element, $rootElement)) { if(!rootAnimateState.disabled) { rootAnimateState.running = false; rootAnimateState.structural = false; } } else if(className) { var data = element.data(NG_ANIMATE_STATE) || {}; var removeAnimations = className === true; if(!removeAnimations && data.active && data.active[className]) { data.totalActive--; delete data.active[className]; } if(removeAnimations || !data.totalActive) { element.removeClass(NG_ANIMATE_CLASS_NAME); element.removeData(NG_ANIMATE_STATE); } } } function animationsDisabled(element, parentElement) { if (rootAnimateState.disabled) return true; if(isMatchingElement(element, $rootElement)) { return rootAnimateState.disabled || rootAnimateState.running; } do { //the element did not reach the root element which means that it //is not apart of the DOM. Therefore there is no reason to do //any animations on it if(parentElement.length === 0) break; var isRoot = isMatchingElement(parentElement, $rootElement); var state = isRoot ? rootAnimateState : parentElement.data(NG_ANIMATE_STATE); var result = state && (!!state.disabled || state.running || state.totalActive > 0); if(isRoot || result) { return result; } if(isRoot) return true; } while(parentElement = parentElement.parent()); return true; } }]); $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow', function($window, $sniffer, $timeout, $$animateReflow) { // Detect proper transitionend/animationend event names. var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; // If unprefixed events are not supported but webkit-prefixed are, use the latter. // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. // Register both events in case `window.onanimationend` is not supported because of that, // do the same for `transitionend` as Safari is likely to exhibit similar behavior. // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { CSS_PREFIX = '-webkit-'; TRANSITION_PROP = 'WebkitTransition'; TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; } else { TRANSITION_PROP = 'transition'; TRANSITIONEND_EVENT = 'transitionend'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { CSS_PREFIX = '-webkit-'; ANIMATION_PROP = 'WebkitAnimation'; ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; } else { ANIMATION_PROP = 'animation'; ANIMATIONEND_EVENT = 'animationend'; } var DURATION_KEY = 'Duration'; var PROPERTY_KEY = 'Property'; var DELAY_KEY = 'Delay'; var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; var NG_ANIMATE_BLOCK_CLASS_NAME = 'ng-animate-block-transitions'; var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3; var CLOSING_TIME_BUFFER = 1.5; var ONE_SECOND = 1000; var lookupCache = {}; var parentCounter = 0; var animationReflowQueue = []; var cancelAnimationReflow; function afterReflow(element, callback) { if(cancelAnimationReflow) { cancelAnimationReflow(); } animationReflowQueue.push(callback); cancelAnimationReflow = $$animateReflow(function() { forEach(animationReflowQueue, function(fn) { fn(); }); animationReflowQueue = []; cancelAnimationReflow = null; lookupCache = {}; }); } var closingTimer = null; var closingTimestamp = 0; var animationElementQueue = []; function animationCloseHandler(element, totalTime) { var node = extractElementNode(element); element = angular.element(node); //this item will be garbage collected by the closing //animation timeout animationElementQueue.push(element); //but it may not need to cancel out the existing timeout //if the timestamp is less than the previous one var futureTimestamp = Date.now() + (totalTime * 1000); if(futureTimestamp <= closingTimestamp) { return; } $timeout.cancel(closingTimer); closingTimestamp = futureTimestamp; closingTimer = $timeout(function() { closeAllAnimations(animationElementQueue); animationElementQueue = []; }, totalTime, false); } function closeAllAnimations(elements) { forEach(elements, function(element) { var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); if(elementData) { (elementData.closeAnimationFn || noop)(); } }); } function getElementAnimationDetails(element, cacheKey) { var data = cacheKey ? lookupCache[cacheKey] : null; if(!data) { var transitionDuration = 0; var transitionDelay = 0; var animationDuration = 0; var animationDelay = 0; var transitionDelayStyle; var animationDelayStyle; var transitionDurationStyle; var transitionPropertyStyle; //we want all the styles defined before and after forEach(element, function(element) { if (element.nodeType == ELEMENT_NODE) { var elementStyles = $window.getComputedStyle(element) || {}; transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY]; transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay); var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); if(aDuration > 0) { aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; } animationDuration = Math.max(aDuration, animationDuration); } }); data = { total : 0, transitionPropertyStyle: transitionPropertyStyle, transitionDurationStyle: transitionDurationStyle, transitionDelayStyle: transitionDelayStyle, transitionDelay: transitionDelay, transitionDuration: transitionDuration, animationDelayStyle: animationDelayStyle, animationDelay: animationDelay, animationDuration: animationDuration }; if(cacheKey) { lookupCache[cacheKey] = data; } } return data; } function parseMaxTime(str) { var maxValue = 0; var values = angular.isString(str) ? str.split(/\s*,\s*/) : []; forEach(values, function(value) { maxValue = Math.max(parseFloat(value) || 0, maxValue); }); return maxValue; } function getCacheKey(element) { var parentElement = element.parent(); var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); if(!parentID) { parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); parentID = parentCounter; } return parentID + '-' + extractElementNode(element).className; } function animateSetup(animationEvent, element, className, calculationDecorator) { var cacheKey = getCacheKey(element); var eventCacheKey = cacheKey + ' ' + className; var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; var stagger = {}; if(itemIndex > 0) { var staggerClassName = className + '-stagger'; var staggerCacheKey = cacheKey + ' ' + staggerClassName; var applyClasses = !lookupCache[staggerCacheKey]; applyClasses && element.addClass(staggerClassName); stagger = getElementAnimationDetails(element, staggerCacheKey); applyClasses && element.removeClass(staggerClassName); } /* the animation itself may need to add/remove special CSS classes * before calculating the anmation styles */ calculationDecorator = calculationDecorator || function(fn) { return fn(); }; element.addClass(className); var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {}; var timings = calculationDecorator(function() { return getElementAnimationDetails(element, eventCacheKey); }); var transitionDuration = timings.transitionDuration; var animationDuration = timings.animationDuration; if(transitionDuration === 0 && animationDuration === 0) { element.removeClass(className); return false; } element.data(NG_ANIMATE_CSS_DATA_KEY, { running : formerData.running || 0, itemIndex : itemIndex, stagger : stagger, timings : timings, closeAnimationFn : noop }); //temporarily disable the transition so that the enter styles //don't animate twice (this is here to avoid a bug in Chrome/FF). var isCurrentlyAnimating = formerData.running > 0 || animationEvent == 'setClass'; if(transitionDuration > 0) { blockTransitions(element, className, isCurrentlyAnimating); } //staggering keyframe animations work by adjusting the `animation-delay` CSS property //on the given element, however, the delay value can only calculated after the reflow //since by that time $animate knows how many elements are being animated. Therefore, //until the reflow occurs the element needs to be blocked (where the keyframe animation //is set to `none 0s`). This blocking mechanism should only be set for when a stagger //animation is detected and when the element item index is greater than 0. if(animationDuration > 0 && stagger.animationDelay > 0 && stagger.animationDuration === 0) { blockKeyframeAnimations(element); } return true; } function isStructuralAnimation(className) { return className == 'ng-enter' || className == 'ng-move' || className == 'ng-leave'; } function blockTransitions(element, className, isAnimating) { if(isStructuralAnimation(className) || !isAnimating) { extractElementNode(element).style[TRANSITION_PROP + PROPERTY_KEY] = 'none'; } else { element.addClass(NG_ANIMATE_BLOCK_CLASS_NAME); } } function blockKeyframeAnimations(element) { extractElementNode(element).style[ANIMATION_PROP] = 'none 0s'; } function unblockTransitions(element, className) { var prop = TRANSITION_PROP + PROPERTY_KEY; var node = extractElementNode(element); if(node.style[prop] && node.style[prop].length > 0) { node.style[prop] = ''; } element.removeClass(NG_ANIMATE_BLOCK_CLASS_NAME); } function unblockKeyframeAnimations(element) { var prop = ANIMATION_PROP; var node = extractElementNode(element); if(node.style[prop] && node.style[prop].length > 0) { node.style[prop] = ''; } } function animateRun(animationEvent, element, className, activeAnimationComplete) { var node = extractElementNode(element); var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY); if(node.className.indexOf(className) == -1 || !elementData) { activeAnimationComplete(); return; } var activeClassName = ''; forEach(className.split(' '), function(klass, i) { activeClassName += (i > 0 ? ' ' : '') + klass + '-active'; }); var stagger = elementData.stagger; var timings = elementData.timings; var itemIndex = elementData.itemIndex; var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay); var maxDelayTime = maxDelay * ONE_SECOND; var startTime = Date.now(); var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; var style = '', appliedStyles = []; if(timings.transitionDuration > 0) { var propertyStyle = timings.transitionPropertyStyle; if(propertyStyle.indexOf('all') == -1) { style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';'; style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ';'; appliedStyles.push(CSS_PREFIX + 'transition-property'); appliedStyles.push(CSS_PREFIX + 'transition-duration'); } } if(itemIndex > 0) { if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { var delayStyle = timings.transitionDelayStyle; style += CSS_PREFIX + 'transition-delay: ' + prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; '; appliedStyles.push(CSS_PREFIX + 'transition-delay'); } if(stagger.animationDelay > 0 && stagger.animationDuration === 0) { style += CSS_PREFIX + 'animation-delay: ' + prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; '; appliedStyles.push(CSS_PREFIX + 'animation-delay'); } } if(appliedStyles.length > 0) { //the element being animated may sometimes contain comment nodes in //the jqLite object, so we're safe to use a single variable to house //the styles since there is always only one element being animated var oldStyle = node.getAttribute('style') || ''; node.setAttribute('style', oldStyle + ' ' + style); } element.on(css3AnimationEvents, onAnimationProgress); element.addClass(activeClassName); elementData.closeAnimationFn = function() { onEnd(); activeAnimationComplete(); }; var staggerTime = itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0); var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER; var totalTime = (staggerTime + animationTime) * ONE_SECOND; elementData.running++; animationCloseHandler(element, totalTime); return onEnd; // This will automatically be called by $animate so // there is no need to attach this internally to the // timeout done method. function onEnd(cancelled) { element.off(css3AnimationEvents, onAnimationProgress); element.removeClass(activeClassName); animateClose(element, className); var node = extractElementNode(element); for (var i in appliedStyles) { node.style.removeProperty(appliedStyles[i]); } } function onAnimationProgress(event) { event.stopPropagation(); var ev = event.originalEvent || event; var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now(); /* Firefox (or possibly just Gecko) likes to not round values up * when a ms measurement is used for the animation */ var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)); /* $manualTimeStamp is a mocked timeStamp value which is set * within browserTrigger(). This is only here so that tests can * mock animations properly. Real events fallback to event.timeStamp, * or, if they don't, then a timeStamp is automatically created for them. * We're checking to see if the timeStamp surpasses the expected delay, * but we're using elapsedTime instead of the timeStamp on the 2nd * pre-condition since animations sometimes close off early */ if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) { activeAnimationComplete(); } } } function prepareStaggerDelay(delayStyle, staggerDelay, index) { var style = ''; forEach(delayStyle.split(','), function(val, i) { style += (i > 0 ? ',' : '') + (index * staggerDelay + parseInt(val, 10)) + 's'; }); return style; } function animateBefore(animationEvent, element, className, calculationDecorator) { if(animateSetup(animationEvent, element, className, calculationDecorator)) { return function(cancelled) { cancelled && animateClose(element, className); }; } } function animateAfter(animationEvent, element, className, afterAnimationComplete) { if(element.data(NG_ANIMATE_CSS_DATA_KEY)) { return animateRun(animationEvent, element, className, afterAnimationComplete); } else { animateClose(element, className); afterAnimationComplete(); } } function animate(animationEvent, element, className, animationComplete) { //If the animateSetup function doesn't bother returning a //cancellation function then it means that there is no animation //to perform at all var preReflowCancellation = animateBefore(animationEvent, element, className); if(!preReflowCancellation) { animationComplete(); return; } //There are two cancellation functions: one is before the first //reflow animation and the second is during the active state //animation. The first function will take care of removing the //data from the element which will not make the 2nd animation //happen in the first place var cancel = preReflowCancellation; afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); //once the reflow is complete then we point cancel to //the new cancellation function which will remove all of the //animation properties from the active animation cancel = animateAfter(animationEvent, element, className, animationComplete); }); return function(cancelled) { (cancel || noop)(cancelled); }; } function animateClose(element, className) { element.removeClass(className); var data = element.data(NG_ANIMATE_CSS_DATA_KEY); if(data) { if(data.running) { data.running--; } if(!data.running || data.running === 0) { element.removeData(NG_ANIMATE_CSS_DATA_KEY); } } } return { enter : function(element, animationCompleted) { return animate('enter', element, 'ng-enter', animationCompleted); }, leave : function(element, animationCompleted) { return animate('leave', element, 'ng-leave', animationCompleted); }, move : function(element, animationCompleted) { return animate('move', element, 'ng-move', animationCompleted); }, beforeSetClass : function(element, add, remove, animationCompleted) { var className = suffixClasses(remove, '-remove') + ' ' + suffixClasses(add, '-add'); var cancellationMethod = animateBefore('setClass', element, className, function(fn) { /* when classes are removed from an element then the transition style * that is applied is the transition defined on the element without the * CSS class being there. This is how CSS3 functions outside of ngAnimate. * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */ var klass = element.attr('class'); element.removeClass(remove); element.addClass(add); var timings = fn(); element.attr('class', klass); return timings; }); if(cancellationMethod) { afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, beforeAddClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), function(fn) { /* when a CSS class is added to an element then the transition style that * is applied is the transition defined on the element when the CSS class * is added at the time of the animation. This is how CSS3 functions * outside of ngAnimate. */ element.addClass(className); var timings = fn(); element.removeClass(className); return timings; }); if(cancellationMethod) { afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, setClass : function(element, add, remove, animationCompleted) { remove = suffixClasses(remove, '-remove'); add = suffixClasses(add, '-add'); var className = remove + ' ' + add; return animateAfter('setClass', element, className, animationCompleted); }, addClass : function(element, className, animationCompleted) { return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted); }, beforeRemoveClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), function(fn) { /* when classes are removed from an element then the transition style * that is applied is the transition defined on the element without the * CSS class being there. This is how CSS3 functions outside of ngAnimate. * http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */ var klass = element.attr('class'); element.removeClass(className); var timings = fn(); element.attr('class', klass); return timings; }); if(cancellationMethod) { afterReflow(element, function() { unblockTransitions(element, className); unblockKeyframeAnimations(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, removeClass : function(element, className, animationCompleted) { return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted); } }; function suffixClasses(classes, suffix) { var className = ''; classes = angular.isArray(classes) ? classes : classes.split(/\s+/); forEach(classes, function(klass, i) { if(klass && klass.length > 0) { className += (i > 0 ? ' ' : '') + klass + suffix; } }); return className; } }]); }]); })(window, window.angular);
sabhiram/nodejs-scaffolding
app/public/js/angular-animate.js
JavaScript
bsd-2-clause
74,308
// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.from es6id: 22.1.2.1 description: Value returned by mapping function (traversed via iterator) info: | [...] 2. If mapfn is undefined, let mapping be false. 3. else a. If IsCallable(mapfn) is false, throw a TypeError exception. b. If thisArg was supplied, let T be thisArg; else let T be undefined. c. Let mapping be true [...] 6. If usingIterator is not undefined, then [...] g. Repeat [...] vii. If mapping is true, then 1. Let mappedValue be Call(mapfn, T, «nextValue, k»). 2. If mappedValue is an abrupt completion, return IteratorClose(iterator, mappedValue). 3. Let mappedValue be mappedValue.[[value]]. features: [Symbol.iterator] ---*/ var thisVals = []; var nextResult = { done: false, value: {} }; var nextNextResult = { done: false, value: {} }; var firstReturnVal = {}; var secondReturnVal = {}; var mapFn = function(value, idx) { var returnVal = nextReturnVal; nextReturnVal = nextNextReturnVal; nextNextReturnVal = null; return returnVal; }; var nextReturnVal = firstReturnVal; var nextNextReturnVal = secondReturnVal; var items = {}; var result; items[Symbol.iterator] = function() { return { next: function() { var result = nextResult; nextResult = nextNextResult; nextNextResult = { done: true }; return result; } }; }; result = Array.from(items, mapFn); assert.sameValue(result.length, 2); assert.sameValue(result[0], firstReturnVal); assert.sameValue(result[1], secondReturnVal);
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/from/iter-map-fn-return.js
JavaScript
bsd-2-clause
1,769
log.enableAll(); (function(){ function animate() { requestAnimationFrame(animate); TWEEN.update(); } animate(); })(); var transform = getStyleProperty('transform'); var getStyle = ( function() { var getStyleFn = getComputedStyle ? function( elem ) { return getComputedStyle( elem, null ); } : function( elem ) { return elem.currentStyle; }; return function getStyle( elem ) { var style = getStyleFn( elem ); if ( !style ) { log.error( 'Style returned ' + style + '. Are you running this code in a hidden iframe on Firefox? ' + 'See http://bit.ly/getsizebug1' ); } return style; }; })(); var cache = { imgW: 5100, imgH: 852, panOffsetX: 0, ring: 0, deg: 0, runDeg: 0, minOffsetDeg: 8, rotationOffsetDeg: 0, onceRotationOffsetDeg: 0, nowOffset: 0, len: 0, touchLock: false, timer: null }; var tween1, tween2; var util = { setTranslateX: function setTranslateX(el, num) { el.style[transform] = "translate3d(" + num + "px,0,0)"; } }; var initPanoramaBox = function initPanoramaBox($el, opts) { var elH = $el.height(); var elW = $el.width(); var $panoramaBox = $('<div class="panorama-box">' + '<div class="panorama-item"></div>' + '<div class="panorama-item"></div>' + '</div>'); var $panoramaItem = $('.panorama-item', $panoramaBox); var scal = elH / opts.height; $panoramaItem.css({ width: opts.width, height: opts.height }); $panoramaBox.css({ width: elW / scal, height: opts.height, transform: 'scale3d(' + scal + ',' + scal + ',' + scal + ')', 'transform-origin': '0 0' }); util.setTranslateX($panoramaItem.get(0), 0); util.setTranslateX($panoramaItem.get(1), -opts.width); $el.append($panoramaBox); var offset = function offset(num) { var width = opts.width; var num1 = num % opts.width; var num2; if (num1 < -width / 2) { num2 = width + num1 - 2; } else { num2 = -width + num1 + 2; } util.setTranslateX($panoramaItem.get(0), num1); util.setTranslateX($panoramaItem.get(1), num2); }; var run = function (subBox1, subBox2, width) { return function offset(num) { num = parseInt(num); cache.len = num; var num1 = num % width; var num2; if (num1 < -width / 2) { num2 = width + num1 - 1; } else { num2 = -width + num1 + 2; } util.setTranslateX(subBox1, num1); util.setTranslateX(subBox2, num2); }; }; return run($panoramaItem.get(0), $panoramaItem.get(1), opts.width); }; var $el = {}; $el.main = $('.wrapper'); var offset = initPanoramaBox($el.main, { width: cache.imgW, height: cache.imgH }); var animOffset = function animOffset(length){ if(tween1){ tween1.stop(); } tween1 = new TWEEN.Tween({x: cache.len}); tween1.to({x: length}, 600); tween1.onUpdate(function(){ offset(this.x); }); tween1.start(); }; var animPanEnd = function animPanEnd(velocityX){ if(tween2){ tween2.stop(); } var oldLen = cache.len; var offsetLen ; tween2 = new TWEEN.Tween({x: cache.len}); tween2.to({x: cache.len - 200 * velocityX}, 600); tween2.easing(TWEEN.Easing.Cubic.Out); tween2.onUpdate(function(){ offset(this.x); offsetLen =oldLen - this.x; cache.nowOffset += + offsetLen; cache.panOffsetX += + offsetLen; }); tween2.start(); }; var initOrientationControl = function () { FULLTILT.getDeviceOrientation({'type': 'world'}) .then(function (orientationControl) { var orientationFunc = function orientationFunc() { var screenAdjustedEvent = orientationControl.getScreenAdjustedEuler(); cache.navDeg = 360 - screenAdjustedEvent.alpha; if (cache.navDeg > 270 && cache.navOldDeg < 90) { cache.ring -= 1; } else if (cache.navDeg < 90 && cache.navOldDeg > 270) { cache.ring += 1; } cache.navOldDeg = cache.navDeg; cache.oldDeg = cache.deg; cache.deg = cache.ring * 360 + cache.navDeg; var offsetDeg = cache.deg - cache.runDeg; if (!cache.touchLock && (Math.abs(offsetDeg) > cache.minOffsetDeg)) { var length = cache.imgW / 360 * -(cache.deg - cache.rotationOffsetDeg) + cache.panOffsetX; cache.runDeg = cache.deg; cache.nowOffset = length; animOffset(length); } }; orientationControl.listen(orientationFunc); }) .catch(function(e){ log.error(e); }); }; var initTouch = function(){ var mc = new Hammer.Manager($el.main.get(0)); var pan = new Hammer.Pan(); $el.main.on('touchstart', function (evt) { if (cache.timer) { clearTimeout(cache.timer); cache.timer = null; } cache.touchLock = true; if(tween1){ tween1.stop(); } if(tween2){ tween2.stop(); } cache.nowOffset = cache.len; }); $el.main.on('touchend', function (evt) { cache.timer = setTimeout(function () { cache.onceRotationOffsetDeg = cache.deg - cache.runDeg; cache.runDeg = cache.deg + cache.onceRotationOffsetDeg; cache.rotationOffsetDeg = cache.rotationOffsetDeg + cache.onceRotationOffsetDeg; cache.touchLock = false; }, 1000); }); mc.add(pan); mc.on('pan', function (evt) { offset(cache.nowOffset + evt.deltaX); }); mc.on('panend', function (evt) { cache.nowOffset += + evt.deltaX; cache.panOffsetX += + evt.deltaX; //animPanEnd(evt.velocityX); }); }; initTouch(); initOrientationControl();
wushuyi/panorama360
assets/js/functions_bak.js
JavaScript
bsd-2-clause
6,239
var _ = require('lodash'); var requireAll = require('require-all'); function load(router, options) { if (_.isString(options)) options = {dirname: options}; return requireAll(_.defaults(options, { filter: /(.*Controller)\.js$/, recursive: true, resolve: function (Controller) { var c = new (Controller.__esModule ? Controller.default : Controller)(); c.register && c.register(router); return c; } })); } module.exports = load;
vvv-v13/express-starter
library/load.js
JavaScript
bsd-2-clause
476
(function(){ var slides = [ {title: 'Работы для отдела Клиентского сервиса и сапорта ФС\nТикетная админка, админка массовых сбоев', works: [ {img: 'i/works/ticket-admin.png', description: '<div class="presentation_mb10"><strong>Тикетная админка</strong></div>' + '<div class="presentation_mb10">Через эту админку сотрудники сапорта работают с обращениями пользователей соц. сети. Мною была реализована вся верстка раздела и код на js.</div>' + '<div class="presentation_mb10">Особенности:</div>' + '<ul class="presentation-list">' + '<li>Интерфейс занимают всю высоту экрана монитора - резиновый по вертикали (На странице могут быть три внутреннии области со скролом );</li>' + '<li>Автоподгрузка новых тикетов;</li>' + '<li>Большое число кастомных элементов управления.</li>' + '</ul>' }, {img: 'i/works/ticket-admin2.png', description: '<div class="presentation_mb10"><strong>Админка массовых сбоев</strong></div>' + '<div class="presentation_mb10">Инструмент взаимодействия сотрудников сапорта и тестеровщиков. При наличие однотипных обращений пользователей, их тикеты групируются в массовый сбой. Который попадает к тестировщикам в виде таска в редмайн для исследования.</div>' }, {img: 'i/works/ticket-admin3.png', description: 'Диалог просмотра массового сбоя.'}, {img: 'i/works/ticket-admin4.png', description: 'Пример реализации кастомного выпадающего списка.'}, ] },{title: 'Отдел модерации \nПопапы жалоб, страница заблокированного пользователя', works: [ {img: 'i/works/complaint_popup.png', description: '<div class="presentation_mb10"><strong>Попап подачи жалоб на пользователя</strong></div>' + '<div class="">Мною была реализована вся frontend часть - верстка и код на js.</div>' },{img: 'i/works/abusePopups.jpg', description: '<div class="">Реализовано несколько кейсов с последовательной навигацией.</div>' },{img: 'i/works/complaint_popup1.png', description: '<div class="">Содержимое попапа - вопросник с готовыми ответами и возможностью отправить расширенное описание.</div>' }, {img: 'i/works/abuse_form.jpg', description: 'Различные варианты попапов жалоб на нарушения со стороны пользователей. Попапы показываются на странице пользователя.'}, {img: 'i/works/abuse_page.jpg', description: 'Страница заблокированного пользователя. Реализована в нескольких вариантах для удаленного пользователя и расширенной для сотрудников Фотостраны. Мною была реализована верстка (html/php).'}, ] },{title: 'Раздел помощи (FAQ)', works: [ {img: 'i/works/faq1.png', description: '<div class="presentation_mb10">В разделе помощи я занимался поддержкой старого кода, правил баги. Поэтому там моя верстка присутствует только фрагментами. К примеру этот опросник сверстан мной. Весь hover эффект при выборе количества звезд реализован только на css.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/support/feedback/ask/" target="_blank">http://fotostrana.ru/support/feedback/ask/</a></div>'}, ] },{title: 'Раздел "Мои финансы"', works: [ {img: 'i/works/finroom.png', description: '<div class="presentation_mb10"><strong>Раздел "Мои финансы" страницы пользователя</strong></div>' + '<div class="presentation_mb10">Мною была реализована верстка и необходимый код на js.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/finance/index/" target="_blank">http://fotostrana.ru/finance/index/</a></div>' }, {img: 'i/works/finroom2.png', description: '<div class="presentation_mb10">Для страницы было реализовано много различных блоков показываемые разным сегментам пользовательской аудитории.</div>'}, {img: 'i/works/finroom3.png', description: 'Так же мною были сверстаны различные попапы сопутсвующих премиальных услуг, доступные из этого раздела.'}, {img: 'i/works/autopay1.png', description: 'Попап услуги &laquo;Автоплатеж&raquo;'}, {img: 'i/works/fotocheck.png', description: 'СМС информирование'}, {img: 'i/works/finroom4.png', description: ''}, ] },{title: 'Финансовый попап \nПопап пополнения счета пользователя', works: [ {img: 'i/works/finpopup1.png', description: '<div class="presentation_mb10">Попап с большим количеством переходов и кастомными элементами управления.</div>' + '<div class="presentation_mb10">Мною была сделана необходимая верстка и js код.</div>' }, {img: 'i/works/finpopup2.png', description: '<div class="presentation_mb10">Из сложных деталей интерфейса:</div>' + '<ul class="presentation-list">' + '<li>"резиновые" кнопки ввода необходимой суммы Фотомани, с возможностью указать произвольную сумму;</li>' + '<li>контроль за вводом и валидация пользовательских данных.</li>' + '</ul>' }, {img: 'i/works/finpopup3.png', description: ''}, ] },{title: 'Сервис "Я модератор"', works: [ {img: 'i/works/imoderator1.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Я модератор"</strong> - пользователям за вознаграждение передается часть модерируемого контента.</div>' + '<div class="">Мною была выполнена вся верстка и весь js код. Из сложных деталей интерфеса - флип часы, реализованные с использованием css3 animation.</div>' }, {img: 'i/works/imoderator2.jpg', description: '<div class="presentation_mb10">В приложении реализовано несколько режимов модерации, в том числе и полно экранный режим (резиновый, скрывающий стандартный лэйаут страниц соц. сети).</div>' + '<div class="">Так же в приложении реализованы инструменты для мотивации "качественной" оценки фотографий пользователями. Используются тестовые проверочные изображения, принудительная отправка в режим обучения и поиск дубликатов изображений в Google/Yandex.</div>' }, ] },{title: 'Сервис "Голосование"', works: [ {img: 'i/works/contest.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Голосование"</strong> - один из основных по доходности сервисов Фотостраны с большой аудиторией</div>' + '<div class="presentation_mb10">В этом сервисе, я занимался поддержкой старого кода и версткой скидочных акций и сезонных мероприятий по активизации пользовательской активности приуроченные к праздникам, мероприятиям (Новый год, Олимпийские игры, 8-е марта, день всех влюбленных, 23 февраля, 12 апреля и др.)</div>' + '<div class="presentation_mb10">Так же мною был переделан механизм рендеринга фотостены.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/" target="_blank">www.fotostrana.ru/contest/</a></div>' }, {img: 'i/works/contest1.jpg', description: ''}, ] },{title: 'Игровой сервис "Битва кланов"', works: [ {img: 'i/works/clan1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Битва Кланов"</strong> - игровой под сервис голосования. Игра в форме квеста.</div>' + '<div>В этом сервисе я делал верстку и js код. Много кейсов, много попапов, много backbon-а. Используется sass, require.js, backbone.</div>' }, {img: 'i/works/clan2.jpg', description: '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/clan2/" target="_blank">www.fotostrana.ru/contest/clan2/</a></div>'}, {img: 'i/works/clan4.jpg', description: 'В сервисе много сложных интерфейсных решений, как на пример поле ввода сообщения в чат. Реализовано ограничение на длину вводимого сообщения и авторесайз высоты textarea.'}, {img: 'i/works/clan3.jpg', description: ''}, ] },{title: 'Сервис "Элитное голосование"', works: [ {img: 'i/works/elite1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Элитное голосование"</strong> - игровой под сервис голосования, доступный несколько дней в месяце для активных участников основного голосования.</div>' + '<div>В этом сервисе я делал верстку и js код. Внешнее оформление переделывалось мною к каждому запуску сервиса.</div>'}, {img: 'i/works/elite2.jpg', description: ''}, ] },{title: 'Сервис "Люди"\nДейтинговый сервис Фотостраны', works: [ {img: 'i/works/people1.jpg', description: '<div class="presentation_mb10"><strong>Дейтинговый сервис "Люди"</strong> - на протяжении полу года поддерживал фронтенд сервиса - исправлял баги, верстал рекламные банеры и попапы.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/people/" target="_blank">fotostrana.ru/people/</a></div>'}, {img: 'i/works/people2.jpg', description: ''}, ] },{title: 'Сообщества и пиновый интерфейс', works: [ {img: 'i/works/community1.jpg', description: '<div class="presentation_mb10">Некоторое время работал над версткой сообществ и пиновым интерфейсом. Концепция пинов была позаимствована у другого сервиса Pinterest. Занимался проектом начиная с первого прототипа и до предрелизной подготовкой.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/public/" target="_blank">fotostrana.ru/public/</a></div>'}, ] },{title: 'Сайт http://www.blik-cleaning.ru/', works: [ {img: 'i/works/cleaning.jpg', description: '<div class="presentation_mb10"><strong>Разработка сайта клининговой компании</strong></div>' + '<div>Сайт сделан на CMS WordPress с оригинальной темой. </div>'}, {img: 'i/works/cleaning1.jpg', description: ''}, ] },{title: 'Сайт http://www.promalp.name/', works: [ {img: 'i/works/promalp1.jpg', description: '<div class="presentation_mb10"><strong>Сайт компании занимающейся промышленным альпинизмом.</strong></div>' + '<div>Сайт сделан на node.js (express). Полностью реализован мною.</div>'}, {img: 'i/works/promalp2.jpg', description: 'Страница с портфолио.'}, {img: 'i/works/promalp3.jpg', description: 'Форма заявки.'}, ] },{title: 'Расширение для браузера chrome Netmarks', works: [ {img: 'i/works/netmarks.jpg', description: '<div class="presentation_mb10"><strong>Chrome extension "NetMarks"</strong></div>' + '<div class="presentation_mb10">Расширение для удобной работы с браузерными закладками в виде выпадающего меню.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/netmarks/boepmphdpbdnficfifejnkejlljcefjb" target="_blank">Chrome store</a></div>' }, ] },{title: 'Приложение для браузера chrome Deposit.calc', works: [ {img: 'i/works/depcalc1.jpg', description: '<div class="presentation_mb10"><strong>Deposit.calc</strong></div>' + '<div class="presentation_mb10">Приложение позволяющее расчитать доход по вкладу с пополнениями. Используется собственный оригинальный алгоритм расчета.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/депозитный-калькулятор/cibblnjekngmoeiehohbkmcbfijpcjdj" target="_blank">Chrome store</a></div>'}, {img: 'i/works/depcalc2.jpg', description: 'Для вывода графиков был использован highcharts.'}, ] }, ]; var View = m3toolkit.View, CollectionView = m3toolkit.CollectionView, BlockView = m3toolkit.BlockView, _base = { // @param {Int} Index // @return {Model} model from collection by index getAnother: function(index){ return this.slideCollection.at(index); } }; var SlideModel = Backbone.Model.extend({ defaults: { title: '', works: [], index: undefined, next: undefined, prev: undefined } }); var SlidesCollection = Backbone.Collection.extend({ model: SlideModel, initialize: function(list){ var i = 0, len = list.length indexedList = list.map(function(item){ item.index = i; if(i > 0){ item.prev = i - 1; } if(i < len - 1){ item.next = i + 1; } if(Array.isArray(item.works)){ item.frontImage = item.works[0].img; } i++; return item; }); Backbone.Collection.prototype.initialize.call(this, indexedList); } }); var WorkItemModel = Backbone.Model.extend({ defaults: { img: '', description: '' } }); var WorkItemsCollections = Backbone.Collection.extend({ model: WorkItemModel }); var WorkItemPreview = View.extend({ className: 'presentation_work-item clearfix', template: _.template( '<img src="<%=img%>" class="Stretch m3-vertical "/>' + '<% if(obj.description){ %>' + '<div class="presentation_work-item_description"><%=obj.description%></div>' + '<% }%>' ) }); var SlideView = View.extend({ className: 'presentation_slide-wrap', template: _.template( '<div style="background-image: url(<%=obj.frontImage%>)" class="presentation_front-image"></div>' + '<div class="presentation_front-image_hover"></div>' ), events: { click: function(e){ _base.openFullScreenPresentation(this.model); } }, }); var FullscreenSlideView = BlockView.extend({ className: 'presentation_fullscreen-slide', template: '<div class="presentation_fullscreen-slide_back"></div>' + '<div class="presentation_fullscreen-slide_close" data-bind="close"></div>' + '<div class="presentation_fullscreen-slide_wrap">' + '<div class="presentation_fullscreen-slide_next" data-co="next">' + '<div class="presentation_fullscreen-slide_nav-btn presentation_fullscreen-slide_nav-btn_next "></div>' + '</div>' + '<div class="presentation_fullscreen-slide_prev" data-co="prev">' + '<div class="presentation_fullscreen-slide_nav-btn"></div>'+ '</div>' + '<pre class="presentation_fullscreen-slide_title" data-co="title"></pre>' + '<div class="" data-co="works" style=""></div>' + '</div>', events: { 'click [data-bind=close]': function(){ _base.hideFullScreenPresentation(); }, 'click [data-co=next]': function(){ var nextIndex = this.model.get('next'); nextIndex != undefined && this._navigateTo(nextIndex); }, 'click [data-co=prev]': function(){ var prevIndex = this.model.get('prev'); prevIndex != undefined && this._navigateTo(prevIndex); }, }, _navigateTo: function(index){ var prevModel =_base.getAnother(index); if(prevModel){ var data = prevModel.toJSON(); this.model.set(prevModel.toJSON()); } }, initialize: function(){ BlockView.prototype.initialize.call(this); this.controls.prev[this.model.get('prev') != undefined ? 'show': 'hide'](); this.controls.next[this.model.get('next') ? 'show': 'hide'](); var workItemsCollection = new WorkItemsCollections(this.model.get('works')); this.children.workCollection = new CollectionView({ collection: workItemsCollection, el: this.controls.works }, WorkItemPreview); this.listenTo(this.model, 'change:works', function(model){ console.log('Works Changed'); workItemsCollection.reset(model.get('works')); }); }, defineBindings: function(){ this._addComputed('works', 'works', function(control, model){ console.log('Refresh works'); var worksList = model.get('works'); console.dir(worksList); }); this._addTransform('title', function(control, model, value){ console.log('Set new Title: `%s`', value); control.text(value); }); this._addTransform('next', function(control, model, value){ control[value ? 'show': 'hide'](); }); this._addTransform('prev', function(control, model, value){ control[value != undefined ? 'show': 'hide'](); }); } }); var PresentationApp = View.extend({ className: 'presentation-wrap', template: '<div class="presentation-wrap_header">' + '<div class="presentation-wrap_header-container">' + '<div class="presentation-wrap_header-title clearfix">' + /*'<div class="presentation-wrap_header-contacts">' + '<div class="">Контакты для связи:</div>' + '<div class="">8 (960) 243 14 03</div>' + '<div class="">[email protected]</div>' + '</div>' +*/ '<h2 class="presentation_header1">Портфолио презентация</h2>' + '<div class="presentation_liter1">Фронтенд разработчика Николая Мальцева</div>' + '<div class="presentation_liter1">8 (960) 243 14 03, [email protected]</div>' + '<div class="presentation_liter1"><a href="http://matraska231.herokuapp.com/?portfolio=1#cv" target="_blank">Резюме</a></div>' + '</div>' + '</div>' + '</div>' + '<div class="presentation-wrap_body" data-bind="body">' + '<div class="presentation-wrap_slide clearfix" data-bind="slides">' + '</div>' + '</div>' + '<div data-bind="fullscreen" class="presentation_fullscreen-slide" style="display: none;"></div>', initialize: function(){ View.prototype.initialize.call(this); var $slides = this.$('[data-bind=slides]'), $body = this.$('[data-bind=body]'), slideCollection = new SlidesCollection(slides); _base.app = this; _base.slideCollection = slideCollection; this.children['slides'] = new CollectionView({ collection: slideCollection, el: $slides }, SlideView); this.children['fullscreen'] = new FullscreenSlideView({ el: this.$('[data-bind=fullscreen]'), model: new SlideModel() }); _base.openFullScreenPresentation = function(model){ $body.addClass('presentation-fix-body'); this.children['fullscreen'].$el.show(); this.children['fullscreen'].model.set(model.toJSON()); // TODO store vertical position }.bind(this); _base.hideFullScreenPresentation = function(){ this.children['fullscreen'].$el.hide(); $body.removeClass('presentation-fix-body'); }.bind(this); } }); var app = new PresentationApp({ el: '#app' }); }());
matraska23/m3-backbone-toolkit
demo_presentation/js/presentation.js
JavaScript
bsd-2-clause
22,354
var searchData= [ ['lettersonly',['lettersOnly',['../class_able_polecat___data___primitive___scalar___string.html#ab2a7acaf93e00fbbd75ea51e56bbf47e',1,'AblePolecat_Data_Primitive_Scalar_String']]], ['list_5fdelimiter',['LIST_DELIMITER',['../interface_able_polecat___query_language___statement_interface.html#a7a10020800f80146451f24fbd57744f1',1,'AblePolecat_QueryLanguage_StatementInterface']]], ['load',['load',['../interface_able_polecat___service___dtx_interface.html#a4dcaa8f72c8423d4de25a9e87fa6f3e4',1,'AblePolecat_Service_DtxInterface']]], ['loadclass',['loadClass',['../class_able_polecat___registry___class.html#af58c5b3a44f9688f9e90dd35abbdefa2',1,'AblePolecat_Registry_Class']]], ['loadmore',['loadMore',['../interface_able_polecat___service___dtx_interface.html#ab5a46d6d7f1795a26153dc59a28b9881',1,'AblePolecat_Service_DtxInterface']]], ['loadtemplatefragment',['loadTemplateFragment',['../class_able_polecat___dom.html#af8f857ffafb0c1e59d752b7b430a95a0',1,'AblePolecat_Dom']]], ['loadtoken',['loadToken',['../interface_able_polecat___access_control___role___user___authenticated___o_auth2_interface.html#a5126349c471fcaff1a74b9d117b979b1',1,'AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Interface\loadToken()'],['../class_able_polecat___access_control___role___user___authenticated___o_auth2_abstract.html#a5126349c471fcaff1a74b9d117b979b1',1,'AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Abstract\loadToken()']]], ['log_2ephp',['Log.php',['../_command_2_log_8php.html',1,'']]], ['log_5fname_5fbootseq',['LOG_NAME_BOOTSEQ',['../class_able_polecat___log___boot.html#a645cd359836227fd9f770339a3147e7b',1,'AblePolecat_Log_Boot']]], ['logbootmessage',['logBootMessage',['../class_able_polecat___mode___server.html#a049626e8b9364098553ee05897b55111',1,'AblePolecat_Mode_Server']]], ['logerrorinfo',['logErrorInfo',['../class_able_polecat___database___pdo.html#a3fdddf6c2c95a4b45cf1a8468f07477d',1,'AblePolecat_Database_Pdo']]], ['logerrormessage',['logErrorMessage',['../class_able_polecat___log_abstract.html#aab8bf90eb60199535dca4c1a6a7742c6',1,'AblePolecat_LogAbstract']]], ['logstatusmessage',['logStatusMessage',['../class_able_polecat___log_abstract.html#af7ba4439ae852b1deed142b4c80f4453',1,'AblePolecat_LogAbstract']]], ['logwarningmessage',['logWarningMessage',['../class_able_polecat___log_abstract.html#a56bda277fc4e215249cfb9ed967204cc',1,'AblePolecat_LogAbstract']]], ['lookupconstraint',['lookupConstraint',['../class_able_polecat___resource___restricted_abstract.html#a46d5b25cc8f9b1ad658b5c6617536824',1,'AblePolecat_Resource_RestrictedAbstract']]], ['lvalue',['lvalue',['../interface_able_polecat___query_language___expression___binary_interface.html#a3441a080c58bdf934f6f24e8c0aea673',1,'AblePolecat_QueryLanguage_Expression_BinaryInterface\lvalue()'],['../class_able_polecat___query_language___expression___binary_abstract.html#a3441a080c58bdf934f6f24e8c0aea673',1,'AblePolecat_QueryLanguage_Expression_BinaryAbstract\lvalue()']]] ];
kkuhrman/AblePolecat
usr/share/documentation/html/search/all_c.js
JavaScript
bsd-2-clause
3,016
/** * Layout Select UI * * @package zork * @subpackage form * @author Kristof Matos <[email protected]> */ ( function ( global, $, js ) { "use strict"; if ( typeof js.layoutSelect !== "undefined" ) { return; } js.require( "jQuery.fn.vslider"); /** * Generates layout select user interface from radio inputs * * @memberOf Zork.Form.Element */ global.Zork.prototype.layoutSelect = function ( element ) { js.style('/styles/scripts/layoutselect.css'); element = $( element ); var defaultKey = element.data( "jsLayoutselectDefaultkey") || "paragraph.form.content.layout.default", descriptionKeyPattern = element.data( "jsLayoutselectDescriptionkey") || "paragraph.form.content.layout.default-description", imageSrcPattern = element.data( "jsLayoutselectImagesrc") || "", selectType = element.data( "jsLayoutselectType") || "locale", itemsPerRow = parseInt(element.data("jsLayoutselectItemsperrow"))>0 ? parseInt(element.data("jsLayoutselectItemsperrow")) : ( selectType == "local" ? 6 : 3 ); element.addClass( "layout-select "+selectType); element.find( "label" ).each( function(idx,eleRadioItem) { var input = $(eleRadioItem).find( ":radio" ), inner = $('<div class="inner"/>').append(input), title = $('<div class="title"/>').html( $(eleRadioItem).html() || js.core.translate(defaultKey) ), overlay = $('<div class="overlay"/>'), innerButtons = $('<div class="buttons"/>').appendTo(inner), innerDescription = $('<p class="description"/>').appendTo(inner), innerButtonsSelect = $('<span class="select"/>') .html( js.core.translate("default.select" ,js.core.userLocale) ) .appendTo(innerButtons), dateCreated = input.data("created") || '-', dateModified = input.data("lastModified") || '-'; $(eleRadioItem).html('') .append(inner) .append(title) .append(overlay); if( selectType == 'import' ) { innerDescription.html( js.core.translate( descriptionKeyPattern.replace("[value]", input.attr( "value")) ,js.core.userLocale)); var imageSrc = imageSrcPattern .replace("[value]",input.attr( "value")); inner.prepend( $( "<img alt='icon' />" ).attr( "src", imageSrc )); } else//selectType == 'locale' { if( input.attr( "value") ) { innerDescription .append( $('<div/>') .append( $('<span/>').html( js.core.translate("default.lastmodified", js.core.userLocale) +': ') ) .append( $('<span/>').html(dateModified) ) ) .append( $('<div/>') .append( $('<span/>').html( js.core.translate("default.created", js.core.userLocale) +': ') ) .append( $('<span/>').html(dateCreated) ) ); js.core.translate("default.created",js.core.userLocale) innerButtons.prepend( $('<a class="preview"/>') .html( js.core.translate("default.preview" ,js.core.userLocale) ) .attr('href','/app/'+js.core.userLocale +'/paragraph/render/'+input.attr( "value")) .attr('target','_blank') ); } } innerButtonsSelect.on( "click", function(evt) { element.find( "label" ).removeClass("selected"); $(evt.target.parentNode.parentNode.parentNode).addClass("selected"); } ); } ); var eleRow, eleRowsContainer = $('<div/>').appendTo(element); element.find( "label" ).each( function(idxItem,eleItem) { if( idxItem%itemsPerRow==0 ) { eleRow = $('<div />').appendTo(eleRowsContainer); } eleRow.append(eleItem); } ); $(eleRowsContainer).vslider({"items":"div", "itemheight":( selectType == 'local' ? 300 : 255 )}); { setTimeout( function(){ $('.ui-vslider').vslider('refresh') },100 ); } }; global.Zork.prototype.layoutSelect.isElementConstructor = true; } ( window, jQuery, zork ) );
webriq/core
module/Paragraph/public/scripts/zork/layoutselect.js
JavaScript
bsd-3-clause
5,515
/** * Dialog to add a new visualization from any of your * existing tables. * */ cdb.admin.NewVisualizationDialogTableItem = cdb.core.View.extend({ events: { "click .remove" : "_onRemove" }, tagName: "li", className: "table", initialize: function() { _.bindAll(this, "_onRemove"); this.template = this.getTemplate('dashboard/views/new_visualization_dialog_table_item'); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this.$el; }, show: function() { this.$el.show(); }, _onRemove: function(e) { this.killEvent(e); this.clear(); this.trigger("remove", this); }, clear: function() { this.$el.hide(); } }); cdb.admin.NewVisualizationDialog = cdb.admin.BaseDialog.extend({ _MAX_LAYERS: 3, _TEXTS: { title: _t('Create visualization'), loading_data: _t('Loading data…'), description: _t('Select the layers you will use on this visualization (you will be able to add more later)'), new_vis_title: _t("Give a name to your visualization"), no_tables: _t("Looks like you don’t have any imported data in your account. To create your first \ visualization you will need to import at least a dataset.") }, events: cdb.core.View.extendEvents({ // do not remove "click .add" : "_onAddTableItem", }), initialize: function() { if (!this.options.user) { new Throw("No user specified when it is needed") } this.user = this.options.user; // Dialog options _.extend(this.options, { title: this._TEXTS.title, template_name: 'common/views/dialog_base', clean_on_hide: true, ok_button_classes: "button green hidden", ok_title: this._TEXTS.title, modal_type: "creation", modal_class: 'new_visualization_dialog', width: this.user.isInsideOrg() ? 502 : 464 }); // Set max layers if user has this parameter var max_user_layers = this.options.user.get('max_layers'); if (!isNaN(max_user_layers) && this._MAX_LAYERS != max_user_layers) { this._MAX_LAYERS = max_user_layers; } this.ok = this.options.ok; this.model = new cdb.core.Model(); this.model.bind("change:disabled", this._onToggleDisabled, this); // Collection to manage the tables this.table_items = new Backbone.Collection(); this.table_items.bind("add", this._addTableItem, this); this.table_items.bind("remove", this._onRemove, this); this.constructor.__super__.initialize.apply(this); this.setWizard(this.options.wizard_option); this.visualizations = new cdb.admin.Visualizations({ type: "derived" }); }, render_content: function() { this.$content = $("<div>"); var temp_content = this.getTemplate('dashboard/views/new_visualization_dialog'); this.$content.append(temp_content({ description: this._TEXTS.loading })); // Tables combo this.tableCombo = new cdb.ui.common.VisualizationsSelector({ model: this.visualizations, user: this.options.user }); this.$content.find('.tableListCombo').append(this.tableCombo.render().el); this.addView(this.tableCombo); this.disableOkButton(); this._loadTables(); return this.$content; }, _onToggleDisabled: function() { this.tableCombo[ this.model.get("disabled") ? "disable" : "enable" ]() this.$(".combo_wrapper")[( this.model.get("disabled") ? "addClass" : "removeClass" )]('disabled'); }, _loadTables: function() { this.visualizations.bind('reset', this._onReset, this); this.visualizations.options.set({ type: "table", per_page: 100000 }); var order = { data: { o: { updated_at: "desc" }, exclude_raster: true }}; this.visualizations.fetch(order); }, _onReset: function() { this.visualizations.unbind(null, null, this); // do this one time and one time only if (this.visualizations.size() == 0) { this.emptyState = true; this._showEmpyState(); } else { this.emptyState = false; this._showControls(); } }, _showEmpyState: function() { var self = this; this.$el.find(".loader").fadeOut(250, function() { $(this).addClass("hidden"); self.$el.find("p").html(self._TEXTS.no_tables); self.$el.find(".ok.button").removeClass("green").addClass("grey"); self.$el.find(".ok.button").html("Ok, let's import some data"); self.$el.find(".ok.button").fadeIn(250, function() { self.enableOkButton(); }); }); }, _showControls: function() { var self = this; this.$el.find(".loader").fadeOut(250, function() { $(this).addClass("hidden"); self.$el.find("p").html(self._TEXTS.description); self.$el.find(".combo_wrapper").addClass('active'); self.$el.find(".ok.button").fadeIn(250, function() { $(this).removeClass("hidden"); }); self.$el.find(".cancel").fadeIn(250); }); this._setupScroll(); }, _setupScroll: function() { this.$scrollPane = this.$el.find(".scrollpane"); this.$scrollPane.jScrollPane({ showArrows: true, animateScroll: true, animateDuration: 150 }); this.api = this.$scrollPane.data('jsp'); }, _cleanString: function(s, n) { if (s) { s = s.replace(/<(?:.|\n)*?>/gm, ''); // strip HTML tags s = s.substr(0, n-1) + (s.length > n ? '&hellip;' : ''); // truncate string } return s; }, _onAddTableItem: function(e) { this.killEvent(e); if (this.model.get("disabled")) return; var table = this.tableCombo.getSelected(); if (table) { var model = new cdb.core.Model(table); this.table_items.add(model); } }, _afterAddItem: function() { if (this.table_items.length >= this._MAX_LAYERS) { this.model.set("disabled", true); } }, _afterRemoveItem: function() { if (this.table_items.length < this._MAX_LAYERS) { this.model.set("disabled", false); } }, _addTableItem: function(model) { this.enableOkButton(); this._afterAddItem(); var view = new cdb.admin.NewVisualizationDialogTableItem({ model: model }); this.$(".tables").append(view.render()); view.bind("remove", this._onRemoveItem, this); view.show(); this._refreshScrollPane(); }, _onRemoveItem: function(item) { this.table_items.remove(item.model); this._refreshScrollPane(); this._afterRemoveItem(); }, _onRemove: function() { if (this.table_items.length == 0) this.disableOkButton(); }, _refreshScrollPane: function() { var self = this; this.$(".scrollpane").animate({ height: this.$(".tables").height() + 5 }, { duration: 150, complete: function() { self.api && self.api.reinitialise(); }}); }, _ok: function(ev) { this.killEvent(ev); if (this.emptyState) { this.hide(); this.trigger("navigate_tables", this); } else { if (this.table_items.length === 0) return; this.hide(); this._openNameVisualizationDialog(); } }, _openNameVisualizationDialog: function() { var selected_tables = this.table_items.pluck("vis_id"); var tables = _.compact( this.visualizations.map(function(m) { if (_.contains(selected_tables, m.get('id'))) { return m.get('table').name } return false; }) ); var dlg = new cdb.admin.NameVisualization({ msg: this._TEXTS.new_vis_title, onResponse: function(name) { var vis = new cdb.admin.Visualization(); vis.save({ name: name, tables: tables }).success(function() { window.location.href = vis.viewUrl(); }); } }); dlg.bind("will_open", function() { $("body").css({ overflow: "hidden" }); }, this); dlg.bind("was_removed", function() { $("body").css({ overflow: "auto" }); }, this); dlg.appendToBody().open(); }, clean: function() { $(".select2-drop.select2-drop-active").hide(); cdb.admin.BaseDialog.prototype.clean.call(this); } });
comilla/map
lib/assets/javascripts/cartodb/dashboard/visualizations/new_visualization_dialog.js
JavaScript
bsd-3-clause
8,143
/** * @author */ imports("Controls.Composite.Carousel"); using("System.Fx.Marquee"); var Carousel = Control.extend({ onChange: function (e) { var ul = this.find('.x-carousel-header'), t; if (t = ul.first(e.from)) t.removeClass('x-carousel-header-selected'); if(t = ul.first(e.to)) t.addClass('x-carousel-header-selected'); }, init: function (options) { var me = this; me.marquee = new Marquee(me, options.direction, options.loop, options.deferUpdate); if (options.duration != null) me.marquee.duration = options.duration; if (options.delay != null) me.marquee.delay = options.delay; me.marquee.on('changing', me.onChange, me); me.query('.x-carousel-header > li').setWidth(me.getWidth() / me.marquee.length).on(options.event || 'mouseover', function (e) { me.marquee.moveTo(this.index()); }); me.onChange({to: 0}); me.marquee.start(); } }).defineMethods("marquee", "moveTo moveBy start stop");
jplusui/jplusui-en
src/Controls/Composite/assets/scripts/Carousel.js
JavaScript
bsd-3-clause
994
import React from "react"; import { expect } from "chai"; import { mount } from "enzyme"; import { Provider } from "react-redux"; import Editor from "../../../src/notebook/providers/editor"; import { dummyStore } from "../../utils"; import { UPDATE_CELL_SOURCE, FOCUS_CELL_EDITOR } from "../../../src/notebook/constants"; describe("EditorProvider", () => { const store = dummyStore(); const setup = (id, cellFocused = true) => mount( <Provider store={store}> <Editor id={id} cellFocused={cellFocused} /> </Provider> ); it("can be constructed", () => { const component = setup("test"); expect(component).to.not.be.null; }); it("onChange updates cell source", () => new Promise(resolve => { const dispatch = action => { expect(action.id).to.equal("test"); expect(action.source).to.equal("i love nteract"); expect(action.type).to.equal(UPDATE_CELL_SOURCE); resolve(); }; store.dispatch = dispatch; const wrapper = setup("test"); const onChange = wrapper .findWhere(n => n.prop("onChange") !== undefined) .first() .prop("onChange"); onChange("i love nteract"); })); it("onFocusChange can update editor focus", () => new Promise(resolve => { const dispatch = action => { expect(action.id).to.equal("test"); expect(action.type).to.equal(FOCUS_CELL_EDITOR); resolve(); }; store.dispatch = dispatch; const wrapper = setup("test"); const onFocusChange = wrapper .findWhere(n => n.prop("onFocusChange") !== undefined) .first() .prop("onFocusChange"); onFocusChange(true); })); });
temogen/nteract
test/renderer/providers/editor-spec.js
JavaScript
bsd-3-clause
1,719
/* Scala.js runtime support * Copyright 2013 LAMP/EPFL * Author: Sébastien Doeraene */ /* ---------------------------------- * * The top-level Scala.js environment * * ---------------------------------- */ //!if outputMode == ECMAScript51Global var ScalaJS = {}; //!endif // Get the environment info ScalaJS.env = (typeof __ScalaJSEnv === "object" && __ScalaJSEnv) ? __ScalaJSEnv : {}; // Global scope ScalaJS.g = (typeof ScalaJS.env["global"] === "object" && ScalaJS.env["global"]) ? ScalaJS.env["global"] : ((typeof global === "object" && global && global["Object"] === Object) ? global : this); ScalaJS.env["global"] = ScalaJS.g; // Where to send exports //!if moduleKind == CommonJSModule ScalaJS.e = exports; //!else ScalaJS.e = (typeof ScalaJS.env["exportsNamespace"] === "object" && ScalaJS.env["exportsNamespace"]) ? ScalaJS.env["exportsNamespace"] : ScalaJS.g; //!endif ScalaJS.env["exportsNamespace"] = ScalaJS.e; // Freeze the environment info ScalaJS.g["Object"]["freeze"](ScalaJS.env); // Linking info - must be in sync with scala.scalajs.runtime.LinkingInfo ScalaJS.linkingInfo = { "envInfo": ScalaJS.env, "semantics": { //!if asInstanceOfs == Compliant "asInstanceOfs": 0, //!else //!if asInstanceOfs == Fatal "asInstanceOfs": 1, //!else "asInstanceOfs": 2, //!endif //!endif //!if arrayIndexOutOfBounds == Compliant "arrayIndexOutOfBounds": 0, //!else //!if arrayIndexOutOfBounds == Fatal "arrayIndexOutOfBounds": 1, //!else "arrayIndexOutOfBounds": 2, //!endif //!endif //!if moduleInit == Compliant "moduleInit": 0, //!else //!if moduleInit == Fatal "moduleInit": 1, //!else "moduleInit": 2, //!endif //!endif //!if floats == Strict "strictFloats": true, //!else "strictFloats": false, //!endif //!if productionMode == true "productionMode": true //!else "productionMode": false //!endif }, //!if outputMode == ECMAScript6 "assumingES6": true, //!else "assumingES6": false, //!endif "linkerVersion": "{{LINKER_VERSION}}" }; ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo); ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo["semantics"]); // Snapshots of builtins and polyfills //!if outputMode == ECMAScript6 ScalaJS.imul = ScalaJS.g["Math"]["imul"]; ScalaJS.fround = ScalaJS.g["Math"]["fround"]; ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"]; //!else ScalaJS.imul = ScalaJS.g["Math"]["imul"] || (function(a, b) { // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul const ah = (a >>> 16) & 0xffff; const al = a & 0xffff; const bh = (b >>> 16) & 0xffff; const bl = b & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0); }); ScalaJS.fround = ScalaJS.g["Math"]["fround"] || //!if floats == Strict (ScalaJS.g["Float32Array"] ? (function(v) { const array = new ScalaJS.g["Float32Array"](1); array[0] = v; return array[0]; }) : (function(v) { return ScalaJS.m.sjsr_package$().froundPolyfill__D__D(+v); })); //!else (function(v) { return +v; }); //!endif ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"] || (function(i) { // See Hacker's Delight, Section 5-3 if (i === 0) return 32; let r = 1; if ((i & 0xffff0000) === 0) { i <<= 16; r += 16; }; if ((i & 0xff000000) === 0) { i <<= 8; r += 8; }; if ((i & 0xf0000000) === 0) { i <<= 4; r += 4; }; if ((i & 0xc0000000) === 0) { i <<= 2; r += 2; }; return r + (i >> 31); }); //!endif // Other fields //!if outputMode == ECMAScript51Global ScalaJS.d = {}; // Data for types ScalaJS.a = {}; // Scala.js-defined JS class value accessors ScalaJS.b = {}; // Scala.js-defined JS class value fields ScalaJS.c = {}; // Scala.js constructors ScalaJS.h = {}; // Inheritable constructors (without initialization code) ScalaJS.s = {}; // Static methods ScalaJS.t = {}; // Static fields ScalaJS.f = {}; // Default methods ScalaJS.n = {}; // Module instances ScalaJS.m = {}; // Module accessors ScalaJS.is = {}; // isInstanceOf methods ScalaJS.isArrayOf = {}; // isInstanceOfArrayOf methods //!if asInstanceOfs != Unchecked ScalaJS.as = {}; // asInstanceOf methods ScalaJS.asArrayOf = {}; // asInstanceOfArrayOf methods //!endif ScalaJS.lastIDHash = 0; // last value attributed to an id hash code ScalaJS.idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null; //!else let $lastIDHash = 0; // last value attributed to an id hash code //!if outputMode == ECMAScript6 const $idHashCodeMap = new ScalaJS.g["WeakMap"](); //!else const $idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null; //!endif //!endif // Core mechanism ScalaJS.makeIsArrayOfPrimitive = function(primitiveData) { return function(obj, depth) { return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth) && (obj.$classData.arrayBase === primitiveData)); } }; //!if asInstanceOfs != Unchecked ScalaJS.makeAsArrayOfPrimitive = function(isInstanceOfFunction, arrayEncodedName) { return function(obj, depth) { if (isInstanceOfFunction(obj, depth) || (obj === null)) return obj; else ScalaJS.throwArrayCastException(obj, arrayEncodedName, depth); } }; //!endif /** Encode a property name for runtime manipulation * Usage: * env.propertyName({someProp:0}) * Returns: * "someProp" * Useful when the property is renamed by a global optimizer (like Closure) * but we must still get hold of a string of that name for runtime * reflection. */ ScalaJS.propertyName = function(obj) { for (const prop in obj) return prop; }; // Runtime functions ScalaJS.isScalaJSObject = function(obj) { return !!(obj && obj.$classData); }; //!if asInstanceOfs != Unchecked ScalaJS.throwClassCastException = function(instance, classFullName) { //!if asInstanceOfs == Compliant throw new ScalaJS.c.jl_ClassCastException().init___T( instance + " is not an instance of " + classFullName); //!else throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable( new ScalaJS.c.jl_ClassCastException().init___T( instance + " is not an instance of " + classFullName)); //!endif }; ScalaJS.throwArrayCastException = function(instance, classArrayEncodedName, depth) { for (; depth; --depth) classArrayEncodedName = "[" + classArrayEncodedName; ScalaJS.throwClassCastException(instance, classArrayEncodedName); }; //!endif //!if arrayIndexOutOfBounds != Unchecked ScalaJS.throwArrayIndexOutOfBoundsException = function(i) { const msg = (i === null) ? null : ("" + i); //!if arrayIndexOutOfBounds == Compliant throw new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg); //!else throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable( new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg)); //!endif }; //!endif ScalaJS.noIsInstance = function(instance) { throw new ScalaJS.g["TypeError"]( "Cannot call isInstance() on a Class representing a raw JS trait/object"); }; ScalaJS.makeNativeArrayWrapper = function(arrayClassData, nativeArray) { return new arrayClassData.constr(nativeArray); }; ScalaJS.newArrayObject = function(arrayClassData, lengths) { return ScalaJS.newArrayObjectInternal(arrayClassData, lengths, 0); }; ScalaJS.newArrayObjectInternal = function(arrayClassData, lengths, lengthIndex) { const result = new arrayClassData.constr(lengths[lengthIndex]); if (lengthIndex < lengths.length-1) { const subArrayClassData = arrayClassData.componentData; const subLengthIndex = lengthIndex+1; const underlying = result.u; for (let i = 0; i < underlying.length; i++) { underlying[i] = ScalaJS.newArrayObjectInternal( subArrayClassData, lengths, subLengthIndex); } } return result; }; ScalaJS.objectToString = function(instance) { if (instance === void 0) return "undefined"; else return instance.toString(); }; ScalaJS.objectGetClass = function(instance) { switch (typeof instance) { case "string": return ScalaJS.d.T.getClassOf(); case "number": { const v = instance | 0; if (v === instance) { // is the value integral? if (ScalaJS.isByte(v)) return ScalaJS.d.jl_Byte.getClassOf(); else if (ScalaJS.isShort(v)) return ScalaJS.d.jl_Short.getClassOf(); else return ScalaJS.d.jl_Integer.getClassOf(); } else { if (ScalaJS.isFloat(instance)) return ScalaJS.d.jl_Float.getClassOf(); else return ScalaJS.d.jl_Double.getClassOf(); } } case "boolean": return ScalaJS.d.jl_Boolean.getClassOf(); case "undefined": return ScalaJS.d.sr_BoxedUnit.getClassOf(); default: if (instance === null) return instance.getClass__jl_Class(); else if (ScalaJS.is.sjsr_RuntimeLong(instance)) return ScalaJS.d.jl_Long.getClassOf(); else if (ScalaJS.isScalaJSObject(instance)) return instance.$classData.getClassOf(); else return null; // Exception? } }; ScalaJS.objectClone = function(instance) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) return instance.clone__O(); else throw new ScalaJS.c.jl_CloneNotSupportedException().init___(); }; ScalaJS.objectNotify = function(instance) { // final and no-op in java.lang.Object if (instance === null) instance.notify__V(); }; ScalaJS.objectNotifyAll = function(instance) { // final and no-op in java.lang.Object if (instance === null) instance.notifyAll__V(); }; ScalaJS.objectFinalize = function(instance) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) instance.finalize__V(); // else no-op }; ScalaJS.objectEquals = function(instance, rhs) { if (ScalaJS.isScalaJSObject(instance) || (instance === null)) return instance.equals__O__Z(rhs); else if (typeof instance === "number") return typeof rhs === "number" && ScalaJS.numberEquals(instance, rhs); else return instance === rhs; }; ScalaJS.numberEquals = function(lhs, rhs) { return (lhs === rhs) ? ( // 0.0.equals(-0.0) must be false lhs !== 0 || 1/lhs === 1/rhs ) : ( // are they both NaN? (lhs !== lhs) && (rhs !== rhs) ); }; ScalaJS.objectHashCode = function(instance) { switch (typeof instance) { case "string": return ScalaJS.m.sjsr_RuntimeString$().hashCode__T__I(instance); case "number": return ScalaJS.m.sjsr_Bits$().numberHashCode__D__I(instance); case "boolean": return instance ? 1231 : 1237; case "undefined": return 0; default: if (ScalaJS.isScalaJSObject(instance) || instance === null) return instance.hashCode__I(); //!if outputMode != ECMAScript6 else if (ScalaJS.idHashCodeMap === null) return 42; //!endif else return ScalaJS.systemIdentityHashCode(instance); } }; ScalaJS.comparableCompareTo = function(instance, rhs) { switch (typeof instance) { case "string": //!if asInstanceOfs != Unchecked ScalaJS.as.T(rhs); //!endif return instance === rhs ? 0 : (instance < rhs ? -1 : 1); case "number": //!if asInstanceOfs != Unchecked ScalaJS.as.jl_Number(rhs); //!endif return ScalaJS.m.jl_Double$().compare__D__D__I(instance, rhs); case "boolean": //!if asInstanceOfs != Unchecked ScalaJS.asBoolean(rhs); //!endif return instance - rhs; // yes, this gives the right result default: return instance.compareTo__O__I(rhs); } }; ScalaJS.charSequenceLength = function(instance) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.uI(instance["length"]); //!else return instance["length"] | 0; //!endif else return instance.length__I(); }; ScalaJS.charSequenceCharAt = function(instance, index) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.uI(instance["charCodeAt"](index)) & 0xffff; //!else return instance["charCodeAt"](index) & 0xffff; //!endif else return instance.charAt__I__C(index); }; ScalaJS.charSequenceSubSequence = function(instance, start, end) { if (typeof(instance) === "string") //!if asInstanceOfs != Unchecked return ScalaJS.as.T(instance["substring"](start, end)); //!else return instance["substring"](start, end); //!endif else return instance.subSequence__I__I__jl_CharSequence(start, end); }; ScalaJS.booleanBooleanValue = function(instance) { if (typeof instance === "boolean") return instance; else return instance.booleanValue__Z(); }; ScalaJS.numberByteValue = function(instance) { if (typeof instance === "number") return (instance << 24) >> 24; else return instance.byteValue__B(); }; ScalaJS.numberShortValue = function(instance) { if (typeof instance === "number") return (instance << 16) >> 16; else return instance.shortValue__S(); }; ScalaJS.numberIntValue = function(instance) { if (typeof instance === "number") return instance | 0; else return instance.intValue__I(); }; ScalaJS.numberLongValue = function(instance) { if (typeof instance === "number") return ScalaJS.m.sjsr_RuntimeLong$().fromDouble__D__sjsr_RuntimeLong(instance); else return instance.longValue__J(); }; ScalaJS.numberFloatValue = function(instance) { if (typeof instance === "number") return ScalaJS.fround(instance); else return instance.floatValue__F(); }; ScalaJS.numberDoubleValue = function(instance) { if (typeof instance === "number") return instance; else return instance.doubleValue__D(); }; ScalaJS.isNaN = function(instance) { return instance !== instance; }; ScalaJS.isInfinite = function(instance) { return !ScalaJS.g["isFinite"](instance) && !ScalaJS.isNaN(instance); }; ScalaJS.doubleToInt = function(x) { return (x > 2147483647) ? (2147483647) : ((x < -2147483648) ? -2147483648 : (x | 0)); }; /** Instantiates a JS object with variadic arguments to the constructor. */ ScalaJS.newJSObjectWithVarargs = function(ctor, args) { // This basically emulates the ECMAScript specification for 'new'. const instance = ScalaJS.g["Object"]["create"](ctor.prototype); const result = ctor["apply"](instance, args); switch (typeof result) { case "string": case "number": case "boolean": case "undefined": case "symbol": return instance; default: return result === null ? instance : result; } }; ScalaJS.resolveSuperRef = function(initialProto, propName) { const getPrototypeOf = ScalaJS.g["Object"]["getPrototypeOf"]; const getOwnPropertyDescriptor = ScalaJS.g["Object"]["getOwnPropertyDescriptor"]; let superProto = getPrototypeOf(initialProto); while (superProto !== null) { const desc = getOwnPropertyDescriptor(superProto, propName); if (desc !== void 0) return desc; superProto = getPrototypeOf(superProto); } return void 0; }; ScalaJS.superGet = function(initialProto, self, propName) { const desc = ScalaJS.resolveSuperRef(initialProto, propName); if (desc !== void 0) { const getter = desc["get"]; if (getter !== void 0) return getter["call"](self); else return desc["value"]; } return void 0; }; ScalaJS.superSet = function(initialProto, self, propName, value) { const desc = ScalaJS.resolveSuperRef(initialProto, propName); if (desc !== void 0) { const setter = desc["set"]; if (setter !== void 0) { setter["call"](self, value); return void 0; } } throw new ScalaJS.g["TypeError"]("super has no setter '" + propName + "'."); }; //!if moduleKind == CommonJSModule ScalaJS.moduleDefault = function(m) { return (m && (typeof m === "object") && "default" in m) ? m["default"] : m; }; //!endif ScalaJS.propertiesOf = function(obj) { const result = []; for (const prop in obj) result["push"](prop); return result; }; ScalaJS.systemArraycopy = function(src, srcPos, dest, destPos, length) { const srcu = src.u; const destu = dest.u; //!if arrayIndexOutOfBounds != Unchecked if (srcPos < 0 || destPos < 0 || length < 0 || (srcPos > ((srcu.length - length) | 0)) || (destPos > ((destu.length - length) | 0))) { ScalaJS.throwArrayIndexOutOfBoundsException(null); } //!endif if (srcu !== destu || destPos < srcPos || (((srcPos + length) | 0) < destPos)) { for (let i = 0; i < length; i = (i + 1) | 0) destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0]; } else { for (let i = (length - 1) | 0; i >= 0; i = (i - 1) | 0) destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0]; } }; ScalaJS.systemIdentityHashCode = //!if outputMode != ECMAScript6 (ScalaJS.idHashCodeMap !== null) ? //!endif (function(obj) { switch (typeof obj) { case "string": case "number": case "boolean": case "undefined": return ScalaJS.objectHashCode(obj); default: if (obj === null) { return 0; } else { let hash = ScalaJS.idHashCodeMap["get"](obj); if (hash === void 0) { hash = (ScalaJS.lastIDHash + 1) | 0; ScalaJS.lastIDHash = hash; ScalaJS.idHashCodeMap["set"](obj, hash); } return hash; } } //!if outputMode != ECMAScript6 }) : (function(obj) { if (ScalaJS.isScalaJSObject(obj)) { let hash = obj["$idHashCode$0"]; if (hash !== void 0) { return hash; } else if (!ScalaJS.g["Object"]["isSealed"](obj)) { hash = (ScalaJS.lastIDHash + 1) | 0; ScalaJS.lastIDHash = hash; obj["$idHashCode$0"] = hash; return hash; } else { return 42; } } else if (obj === null) { return 0; } else { return ScalaJS.objectHashCode(obj); } //!endif }); // is/as for hijacked boxed classes (the non-trivial ones) ScalaJS.isByte = function(v) { return (v << 24 >> 24) === v && 1/v !== 1/-0; }; ScalaJS.isShort = function(v) { return (v << 16 >> 16) === v && 1/v !== 1/-0; }; ScalaJS.isInt = function(v) { return (v | 0) === v && 1/v !== 1/-0; }; ScalaJS.isFloat = function(v) { //!if floats == Strict return v !== v || ScalaJS.fround(v) === v; //!else return typeof v === "number"; //!endif }; //!if asInstanceOfs != Unchecked ScalaJS.asUnit = function(v) { if (v === void 0 || v === null) return v; else ScalaJS.throwClassCastException(v, "scala.runtime.BoxedUnit"); }; ScalaJS.asBoolean = function(v) { if (typeof v === "boolean" || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Boolean"); }; ScalaJS.asByte = function(v) { if (ScalaJS.isByte(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Byte"); }; ScalaJS.asShort = function(v) { if (ScalaJS.isShort(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Short"); }; ScalaJS.asInt = function(v) { if (ScalaJS.isInt(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Integer"); }; ScalaJS.asFloat = function(v) { if (ScalaJS.isFloat(v) || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Float"); }; ScalaJS.asDouble = function(v) { if (typeof v === "number" || v === null) return v; else ScalaJS.throwClassCastException(v, "java.lang.Double"); }; //!endif // Unboxes //!if asInstanceOfs != Unchecked ScalaJS.uZ = function(value) { return !!ScalaJS.asBoolean(value); }; ScalaJS.uB = function(value) { return ScalaJS.asByte(value) | 0; }; ScalaJS.uS = function(value) { return ScalaJS.asShort(value) | 0; }; ScalaJS.uI = function(value) { return ScalaJS.asInt(value) | 0; }; ScalaJS.uJ = function(value) { return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : ScalaJS.as.sjsr_RuntimeLong(value); }; ScalaJS.uF = function(value) { /* Here, it is fine to use + instead of fround, because asFloat already * ensures that the result is either null or a float. */ return +ScalaJS.asFloat(value); }; ScalaJS.uD = function(value) { return +ScalaJS.asDouble(value); }; //!else ScalaJS.uJ = function(value) { return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : value; }; //!endif // TypeArray conversions ScalaJS.byteArray2TypedArray = function(value) { return new ScalaJS.g["Int8Array"](value.u); }; ScalaJS.shortArray2TypedArray = function(value) { return new ScalaJS.g["Int16Array"](value.u); }; ScalaJS.charArray2TypedArray = function(value) { return new ScalaJS.g["Uint16Array"](value.u); }; ScalaJS.intArray2TypedArray = function(value) { return new ScalaJS.g["Int32Array"](value.u); }; ScalaJS.floatArray2TypedArray = function(value) { return new ScalaJS.g["Float32Array"](value.u); }; ScalaJS.doubleArray2TypedArray = function(value) { return new ScalaJS.g["Float64Array"](value.u); }; ScalaJS.typedArray2ByteArray = function(value) { const arrayClassData = ScalaJS.d.B.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int8Array"](value)); }; ScalaJS.typedArray2ShortArray = function(value) { const arrayClassData = ScalaJS.d.S.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int16Array"](value)); }; ScalaJS.typedArray2CharArray = function(value) { const arrayClassData = ScalaJS.d.C.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Uint16Array"](value)); }; ScalaJS.typedArray2IntArray = function(value) { const arrayClassData = ScalaJS.d.I.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Int32Array"](value)); }; ScalaJS.typedArray2FloatArray = function(value) { const arrayClassData = ScalaJS.d.F.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Float32Array"](value)); }; ScalaJS.typedArray2DoubleArray = function(value) { const arrayClassData = ScalaJS.d.D.getArrayOf(); return new arrayClassData.constr(new ScalaJS.g["Float64Array"](value)); }; // TypeData class //!if outputMode != ECMAScript6 /** @constructor */ ScalaJS.TypeData = function() { //!else class $TypeData { constructor() { //!endif // Runtime support this.constr = void 0; this.parentData = void 0; this.ancestors = null; this.componentData = null; this.arrayBase = null; this.arrayDepth = 0; this.zero = null; this.arrayEncodedName = ""; this._classOf = void 0; this._arrayOf = void 0; this.isArrayOf = void 0; // java.lang.Class support this["name"] = ""; this["isPrimitive"] = false; this["isInterface"] = false; this["isArrayClass"] = false; this["isRawJSType"] = false; this["isInstance"] = void 0; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initPrim = function( //!else initPrim( //!endif zero, arrayEncodedName, displayName) { // Runtime support this.ancestors = {}; this.componentData = null; this.zero = zero; this.arrayEncodedName = arrayEncodedName; this.isArrayOf = function(obj, depth) { return false; }; // java.lang.Class support this["name"] = displayName; this["isPrimitive"] = true; this["isInstance"] = function(obj) { return false; }; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initClass = function( //!else initClass( //!endif internalNameObj, isInterface, fullName, ancestors, isRawJSType, parentData, isInstance, isArrayOf) { const internalName = ScalaJS.propertyName(internalNameObj); isInstance = isInstance || function(obj) { return !!(obj && obj.$classData && obj.$classData.ancestors[internalName]); }; isArrayOf = isArrayOf || function(obj, depth) { return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth) && obj.$classData.arrayBase.ancestors[internalName]) }; // Runtime support this.parentData = parentData; this.ancestors = ancestors; this.arrayEncodedName = "L"+fullName+";"; this.isArrayOf = isArrayOf; // java.lang.Class support this["name"] = fullName; this["isInterface"] = isInterface; this["isRawJSType"] = !!isRawJSType; this["isInstance"] = isInstance; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.initArray = function( //!else initArray( //!endif componentData) { // The constructor const componentZero0 = componentData.zero; // The zero for the Long runtime representation // is a special case here, since the class has not // been defined yet, when this file is read const componentZero = (componentZero0 == "longZero") ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : componentZero0; //!if outputMode != ECMAScript6 /** @constructor */ const ArrayClass = function(arg) { if (typeof(arg) === "number") { // arg is the length of the array this.u = new Array(arg); for (let i = 0; i < arg; i++) this.u[i] = componentZero; } else { // arg is a native array that we wrap this.u = arg; } } ArrayClass.prototype = new ScalaJS.h.O; ArrayClass.prototype.constructor = ArrayClass; //!if arrayIndexOutOfBounds != Unchecked ArrayClass.prototype.get = function(i) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); return this.u[i]; }; ArrayClass.prototype.set = function(i, v) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); this.u[i] = v; }; //!endif ArrayClass.prototype.clone__O = function() { if (this.u instanceof Array) return new ArrayClass(this.u["slice"](0)); else // The underlying Array is a TypedArray return new ArrayClass(new this.u.constructor(this.u)); }; //!else class ArrayClass extends ScalaJS.c.O { constructor(arg) { super(); if (typeof(arg) === "number") { // arg is the length of the array this.u = new Array(arg); for (let i = 0; i < arg; i++) this.u[i] = componentZero; } else { // arg is a native array that we wrap this.u = arg; } }; //!if arrayIndexOutOfBounds != Unchecked get(i) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); return this.u[i]; }; set(i, v) { if (i < 0 || i >= this.u.length) ScalaJS.throwArrayIndexOutOfBoundsException(i); this.u[i] = v; }; //!endif clone__O() { if (this.u instanceof Array) return new ArrayClass(this.u["slice"](0)); else // The underlying Array is a TypedArray return new ArrayClass(new this.u.constructor(this.u)); }; }; //!endif ArrayClass.prototype.$classData = this; // Don't generate reflective call proxies. The compiler special cases // reflective calls to methods on scala.Array // The data const encodedName = "[" + componentData.arrayEncodedName; const componentBase = componentData.arrayBase || componentData; const arrayDepth = componentData.arrayDepth + 1; const isInstance = function(obj) { return componentBase.isArrayOf(obj, arrayDepth); } // Runtime support this.constr = ArrayClass; this.parentData = ScalaJS.d.O; this.ancestors = {O: 1, jl_Cloneable: 1, Ljava_io_Serializable: 1}; this.componentData = componentData; this.arrayBase = componentBase; this.arrayDepth = arrayDepth; this.zero = null; this.arrayEncodedName = encodedName; this._classOf = undefined; this._arrayOf = undefined; this.isArrayOf = undefined; // java.lang.Class support this["name"] = encodedName; this["isPrimitive"] = false; this["isInterface"] = false; this["isArrayClass"] = true; this["isInstance"] = isInstance; return this; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.getClassOf = function() { //!else getClassOf() { //!endif if (!this._classOf) this._classOf = new ScalaJS.c.jl_Class().init___jl_ScalaJSClassData(this); return this._classOf; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype.getArrayOf = function() { //!else getArrayOf() { //!endif if (!this._arrayOf) this._arrayOf = new ScalaJS.TypeData().initArray(this); return this._arrayOf; }; // java.lang.Class support //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getFakeInstance"] = function() { //!else "getFakeInstance"() { //!endif if (this === ScalaJS.d.T) return "some string"; else if (this === ScalaJS.d.jl_Boolean) return false; else if (this === ScalaJS.d.jl_Byte || this === ScalaJS.d.jl_Short || this === ScalaJS.d.jl_Integer || this === ScalaJS.d.jl_Float || this === ScalaJS.d.jl_Double) return 0; else if (this === ScalaJS.d.jl_Long) return ScalaJS.m.sjsr_RuntimeLong$().Zero$1; else if (this === ScalaJS.d.sr_BoxedUnit) return void 0; else return {$classData: this}; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getSuperclass"] = function() { //!else "getSuperclass"() { //!endif return this.parentData ? this.parentData.getClassOf() : null; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["getComponentType"] = function() { //!else "getComponentType"() { //!endif return this.componentData ? this.componentData.getClassOf() : null; }; //!if outputMode != ECMAScript6 ScalaJS.TypeData.prototype["newArrayOfThisClass"] = function(lengths) { //!else "newArrayOfThisClass"(lengths) { //!endif let arrayClassData = this; for (let i = 0; i < lengths.length; i++) arrayClassData = arrayClassData.getArrayOf(); return ScalaJS.newArrayObject(arrayClassData, lengths); }; //!if outputMode == ECMAScript6 }; //!endif // Create primitive types ScalaJS.d.V = new ScalaJS.TypeData().initPrim(undefined, "V", "void"); ScalaJS.d.Z = new ScalaJS.TypeData().initPrim(false, "Z", "boolean"); ScalaJS.d.C = new ScalaJS.TypeData().initPrim(0, "C", "char"); ScalaJS.d.B = new ScalaJS.TypeData().initPrim(0, "B", "byte"); ScalaJS.d.S = new ScalaJS.TypeData().initPrim(0, "S", "short"); ScalaJS.d.I = new ScalaJS.TypeData().initPrim(0, "I", "int"); ScalaJS.d.J = new ScalaJS.TypeData().initPrim("longZero", "J", "long"); ScalaJS.d.F = new ScalaJS.TypeData().initPrim(0.0, "F", "float"); ScalaJS.d.D = new ScalaJS.TypeData().initPrim(0.0, "D", "double"); // Instance tests for array of primitives ScalaJS.isArrayOf.Z = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.Z); ScalaJS.d.Z.isArrayOf = ScalaJS.isArrayOf.Z; ScalaJS.isArrayOf.C = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.C); ScalaJS.d.C.isArrayOf = ScalaJS.isArrayOf.C; ScalaJS.isArrayOf.B = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.B); ScalaJS.d.B.isArrayOf = ScalaJS.isArrayOf.B; ScalaJS.isArrayOf.S = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.S); ScalaJS.d.S.isArrayOf = ScalaJS.isArrayOf.S; ScalaJS.isArrayOf.I = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.I); ScalaJS.d.I.isArrayOf = ScalaJS.isArrayOf.I; ScalaJS.isArrayOf.J = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.J); ScalaJS.d.J.isArrayOf = ScalaJS.isArrayOf.J; ScalaJS.isArrayOf.F = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.F); ScalaJS.d.F.isArrayOf = ScalaJS.isArrayOf.F; ScalaJS.isArrayOf.D = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.D); ScalaJS.d.D.isArrayOf = ScalaJS.isArrayOf.D; //!if asInstanceOfs != Unchecked // asInstanceOfs for array of primitives ScalaJS.asArrayOf.Z = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.Z, "Z"); ScalaJS.asArrayOf.C = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.C, "C"); ScalaJS.asArrayOf.B = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.B, "B"); ScalaJS.asArrayOf.S = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.S, "S"); ScalaJS.asArrayOf.I = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.I, "I"); ScalaJS.asArrayOf.J = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.J, "J"); ScalaJS.asArrayOf.F = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.F, "F"); ScalaJS.asArrayOf.D = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.D, "D"); //!endif
xuwei-k/scala-js
tools/scalajsenv.js
JavaScript
bsd-3-clause
32,145
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com'; var NETKI_API_HOST = 'https://api.netki.com'; var SHORTCODES = { 'btc': 'Bitcoin', 'tbtc': 'Bitcoin Testnet', 'ltc': 'Litecoin', 'dgc': 'Dogecoin', 'nmc': 'Namecoin', 'tusd': 'tetherUSD', 'teur': 'tetherEUR', 'tjpy': 'tetherJPY', 'oap': 'Open Asset', 'fct': 'Factom Factoid', 'fec': 'Factom Entry Credit', 'eth': 'Ethereum Ether' }; function isWalletName(walletName) { var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i; return pattern.test(walletName); }
netkicorp/walletname-chrome-extension
app/scripts.babel/netkiUtils.js
JavaScript
bsd-3-clause
573
/* eslint-disable no-underscore-dangle */ export default function ({ client, filterQuery, mustContain, busy, encodeQueryAsString, }) { return { listUsers(query) { const params = filterQuery( query, 'text', 'limit', 'offset', 'sort', 'sortdir' ); return busy( client._.get('/user', { params, }) ); }, createUser(user) { const expected = [ 'login', 'email', 'firstName', 'lastName', 'password', 'admin', ]; const params = filterQuery(user, ...expected); const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.post(`/user${encodeQueryAsString(params)}`)); }, changePassword(old, newPassword) { const params = { old, new: newPassword, }; return busy(client._.put(`/user/password${encodeQueryAsString(params)}`)); }, resetPassword(email) { const params = { email, }; return busy( client._.delete('/user/password', { params, }) ); }, deleteUser(id) { return busy(client._.delete(`/user/${id}`)); }, getUser(id) { return busy(client._.get(`/user/${id}`)); }, updateUser(user) { const expected = ['email', 'firstName', 'lastName', '_id']; const params = filterQuery(user, ...expected.slice(0, 3)); // Remove '_id' const { missingKeys, promise } = mustContain(user, ...expected); return missingKeys ? promise : busy(client._.put(`/user/${user._id}${encodeQueryAsString(params)}`)); }, }; }
Kitware/paraviewweb
src/IO/Girder/CoreEndpoints/user.js
JavaScript
bsd-3-clause
1,750
module.exports = (function () { var TypeChecker = Cactus.Util.TypeChecker; var JSON = Cactus.Util.JSON; var stringify = JSON.stringify; var object = Cactus.Addon.Object; var collection = Cactus.Data.Collection; var gettype = TypeChecker.gettype.bind(TypeChecker); return { "null and undefined" : function () { var o = new TypeChecker({ type : "number" }); exception(/Expected "number", but got undefined \(type "undefined"\)/, o.parse.bind(o, undefined)); exception(/Expected "number", but got null \(type "null"\)/, o.parse.bind(o, null)); }, "required values" : function () { var o = new TypeChecker({ required : false, type : "boolean" }); equal(true, o.parse(true)); o.parse(null); }, "default value" : function () { var o = new TypeChecker({ type : "number", defaultValue : 3 }); assert.eql(3, o.parse(null)); assert.eql(4, o.parse(4)); o = new TypeChecker({ type : { a : { type : "number", defaultValue : 1 } } }); var h = o.parse({ a : 2 }); assert.eql(2, o.parse({ a : 2}).a); assert.eql(1, o.parse({ a : null }).a); assert.eql(1, o.parse({}).a); o = new TypeChecker({ type : { x : { type : "boolean", defaultValue : false } } }); eql({ x : true }, o.parse({ x : true })); eql({ x : false }, o.parse({ x : false })); eql({ x : false }, o.parse({})); // When not passing bool properties. o = new TypeChecker({ type : { b : { type : "boolean", defaultValue : false } } }); eql({ b : false }, o.parse({})); // Default values with incorrect types should have special error message (always throw error) exception(/Expected "boolean", but got 1/, function () { return new TypeChecker({ type : "boolean", defaultValue : 1 }); }); }, defaultValueFunc : function () { var o = new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "number" }); assert.strictEqual(1, o.parse(null)); o = new TypeChecker({ type : { a : { defaultValueFunc : function () { return 2; }, type : "number" } } }); assert.strictEqual(2, o.parse({ a : null }).a); assert.strictEqual(2, o.parse({}).a); // defaultValueFunc return value must match type. exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ defaultValueFunc : function () { return 1; }, type : "boolean" }).parse(undefined); }); exception(/expected "boolean", but got 1/i, function () { return new TypeChecker({ type : { a : { defaultValueFunc : function () { return 1; }, type : "boolean" } } }).parse({}); }); }, validators : function () { var o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; } }] }); o.parse(1); o.parse(0, false); eql({ "" : ["Validation failed: got 0."] }, o.getErrors()); // Validation error message. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected positive number." }] }); o.parse(1); exception(/TypeChecker: Error: Expected positive number./, o.parse.bind(o, 0)); eql({ "" : ["Expected positive number."] }, o.getErrors()); // Multiple ordered validators. o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > -1; }, message : "Expected number bigger than -1." }, { func : function (v) { return v < 1; }, message : "Expected number smaller than 1." }] }); o.parse(0); exception(/Expected number bigger than -1/i, o.parse.bind(o, -1)); exception(/Expected number smaller than 1/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : "number", validators : [{ func : function (v) { return v > 0; }, message : "Expected number bigger than 0." }, { func : function (v) { return v > 1; }, message : "Expected number bigger than 1." }] }); o.parse(2); exception(/bigger than 0.+ bigger than 1./i, o.parse.bind(o, 0)); }, "simple interface" : function () { var o = TypeChecker.simple("number"); o.parse(1); o = TypeChecker.simple(["number"]); o.parse([1]); o = TypeChecker.simple({ a : "number", b : "boolean" }); o.parse({ a : 1, b : true }); o = TypeChecker.simple({ a : ["number"] }); o.parse({ a : [1] }); o = TypeChecker.simple({ a : { b : "boolean" } }); o.parse({ a : { b : true } }); // Classes. Class("X"); o = TypeChecker.simple({ _type : X }); o.parse(new X()); o = TypeChecker.simple({ a : { _type : X } }); o.parse({ a : new X() }); }, errorHash : function () { var o = TypeChecker.simple("string"); exception(/Nothing parsed/i, o.hasErrors.bind(o)); exception(/Nothing parsed/i, o.getErrors.bind(o)); o.parse("x", false); exception(/No errors exist/, o.getErrors.bind(o)); o.parse(1, false); ok(o.hasErrors()); var errors = o.getErrors(); ok(o.hasErrorsFor("")); not(o.hasErrorsFor("foo")); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, o.getErrors()); o = TypeChecker.simple({ a : "number", b : "number" }); o.parse({ a : "x", b : true }, false); ok(o.hasErrors()); eql({ a : ['Expected "number", but got "x" (type "string")'], b : ['Expected "number", but got true (type "boolean")'] }, o.getErrors()); ok(o.hasErrorsFor("a")); ok(o.hasErrorsFor("b")); eql(['Expected "number", but got "x" (type "string")'], o.getErrorsFor("a")); eql(['Expected "number", but got true (type "boolean")'], o.getErrorsFor("b")); o = new TypeChecker({ type : "number", validators : [{ func : Function.returning(false), message : "false" }] }); o.parse(1, false); eql({ "" : ["false"] }, o.getErrors()); // Errors for array validators. o = new TypeChecker({ type : { p : { type : "string", validators : [{ func : Function.returning(false), message : "Error #1." }, { func : Function.returning(false), message : "Error #2." }] } } }); o.parse({ p : "" }, false); eql({ p : ["Error #1.", "Error #2."] }, o.getErrors()); // When Error is thrown, there should be a hash property with the error // messages as well. o = new TypeChecker({ type : "string" }); o.parse(1, false); assert.throws(o.parse.bind(o, 1), function (e) { assert.ok(/expected "string".+got 1 \(type "number"\)/i.test(e.message)); assert.ok("hash" in e, "Missing hash property"); eql({ "" : ['Expected "string", but got 1 (type "number")'] }, e.hash); return true; }); }, validators2 : function () { // Validators should run only if all other validations pass. var ran = false; var o = new TypeChecker({ type : "number", defaultValue : 0, validators : [{ func : function (v) { ran = true; return v === 0; }, message : "Only way to validate is to send null or 0." }] }); o.parse(0); o.parse("x", false); eql({ "" : [ 'Expected "number", but got "x" (type "string")', 'Only way to validate is to send null or 0.' ] }, o.getErrors()); // Do not run validators if constraints fail. o.parse("x", false); assert.strictEqual(1, object.count(o.getErrors())); o.parse(-1, false); eql({ "" : ["Only way to validate is to send null or 0."] }, o.getErrors()); // Default value should be applied before validation as well. ran = false; assert.strictEqual(0, o.parse(null)); assert.ok(ran, "Validation did not run."); }, "predefined validations" : function () { var o = new TypeChecker({ type : "number", validators : ["natural"] }); o.parse(1); o.parse(0); o.parse(-1, false); eql({ "" : ["Expected natural number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["positive"] }); o.parse(1); o.parse(0, false); eql({ "" : ["Expected positive number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["negative"] }); o.parse(-1); o.parse(0, false); eql({ "" : ["Expected negative number."] }, o.getErrors()); o = new TypeChecker({ type : "number", validators : ["x"] }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, 1)); o = new TypeChecker({ type : { a : { type : "number", validators : ["x"] } } }); exception(/Undefined built in validator "x"/i, o.parse.bind(o, { a : 1 })); o = new TypeChecker({ type : "string", validators : ["non empty string"] }); o.parse("x"); o.parse("", false); eql({ "" : ["Expected non-empty string."] }, o.getErrors()); }, T_Array : function () { eql([{ type : "string" }], gettype(new TypeChecker.types.T_Array({ type : "string" }))); var o = new TypeChecker({ type : [{ type : "number" }] }); eql([1, 2], o.parse([1, 2])); eql([], o.parse([])); exception(/Expected \[\{"type":"number"\}\], but got "a" \(type "string"\)/i, o.parse.bind(o, "a")); exception(/error in property "0": expected "number", but got "a" \(type "string"\)/i, o.parse.bind(o, ["a"])); exception(/error in property "1": expected "number", but got true \(type "boolean"\)/i, o.parse.bind(o, [1, true])); exception(/error in property "0": expected "number", but got "a"[\s\S]+error in property "1": expected "number", but got true/i, o.parse.bind(o, ["a", true])); // Nesting of arrays. var o = new TypeChecker({ type : [{ type : [{ type : "number" }] }] }); eql([[1, 2]], o.parse([[1, 2]])); exception(/^TypeChecker: Error in property "0": expected \[\{"type":"number"\}\], but got 1/i, o.parse.bind(o, [1, [2, 3]])); exception(/^TypeChecker: Error in property "1.1": expected "number", but got true/i, o.parse.bind(o, [[1], [2, true]])); eql([[]], o.parse([[]])); eql([], o.parse([])); // Optional arrays. o = new TypeChecker({ type : [{ type : "mixed" }], defaultValue : [] }); o.parse(null); // Optional array in hash. o = new TypeChecker({ type : { a : { type : [{ type : "number" }], defaultValue : [] } } }); o.parse({}); }, T_Primitive : function () { var o = new TypeChecker({ type : "string" }); assert.eql("aoeu", o.parse("aoeu")); exception(/expected "string", but got 1 \(type "number"\)/i, o.parse.bind(o, 1)); exception(/expected "string", but got true \(type "boolean"\)/i, o.parse.bind(o, true)); o = new TypeChecker({ type : "number" }); assert.eql(100, o.parse(100)); exception(/^TypeChecker: Error: Expected "number", but got "1" \(type "string"\)$/, o.parse.bind(o, "1")); // Default values o = new TypeChecker({ type : "boolean", defaultValue : false }); o.parse(true); o.parse(false); not(o.parse(null)); }, T_Enumerable : function () { var o = new TypeChecker({ enumerable : [1,2,3] }); eql(1, o.parse(1)); o.parse(2); o.parse(3); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 0$/, o.parse.bind(o, 0)); exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 4$/, o.parse.bind(o, 4)); eql({ enumerable : [1,2,3] }, gettype(new TypeChecker.types.T_Enumerable([1, 2, 3]))); }, "T_Union" : function () { var o = new TypeChecker({ union : ["string", "number"] }); eql(1, o.parse(1)); eql("x", o.parse("x")); exception(/Expected a Union/, o.parse.bind(o, true)); eql({ union : [ { type : "string"}, { type : "number" } ]}, gettype(new TypeChecker.types.T_Union([ { type : "string" }, { type : "number" } ]))); }, "T_Instance" : function () { var Foo2 = Class("Foo2", {}); Class("Bar", { isa : Foo2 }); var o = new TypeChecker({ type : Foo2 }); var foo2 = new Foo2(); equal(foo2, o.parse(foo2)); o.parse(new Bar()); exception(/Expected an instance of "Foo2", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); Class("Baz"); exception(/Expected an instance of "Foo2", but got value <a Baz> \(type "Baz"\)$/, o.parse.bind(o, new Baz())); // Non-Joose classes. function Bax() { } function Qux() { } Qux.extend(Bax); o = new TypeChecker({ type : Bax }); o.parse(new Bax()); o.parse(new Qux()); function Qax() { } Qax.prototype.toString = function () { return "my Qax"; }; exception(/Expected an instance of "Bax", but got value <1> \(type "number"\)/, o.parse.bind(o, 1)); exception(/Expected an instance of "Bax", but got value <my Qax> \(type "Qax"\)$/, o.parse.bind(o, new Qax())); // Anonymous classes. var F = function () {}; var G = function () {}; o = new TypeChecker({ type : F }); G.extend(F); o.parse(new F()); o.parse(new G()); var H = function () {}; H.prototype.toString = Function.returning("my H"); exception(/Expected an instance of "anonymous type", but got value <1>/, o.parse.bind(o, 1)); exception(/Expected an instance of "anonymous type", but got value <my H> \(type "anonymous type"\)/i, o.parse.bind(o, new H())); function I() {} equal(I, gettype(new TypeChecker.types.T_Instance(I)).type); }, T_Hash : function () { var o = new TypeChecker({ x : { type : "boolean" } }); eql({ x : { type : "boolean" } }, gettype(new TypeChecker.types.T_Hash({ x : { type : "boolean" } }))); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); eql({ a : 1, b : true }, o.parse({ a : 1, b : true })); o = new TypeChecker({ type : { a : { type : "number" }, b : { type : "boolean" } } }); exception(/Expected \{"a":\{"type":"number"\},"b":\{"type":"boolean"\}\}, but got 1/i, o.parse.bind(o, 1)); exception(/Error in property "a": expected "number", but got "2"/i, o.parse.bind(o, { a : "2", b : true })); exception(/Error in property "a": expected "number", but got "2"[\s\S]+Error in property "b": expected "boolean", but got "2"/i, o.parse.bind(o, { a : "2", b : "2" })); exception(/Error in property "b": Missing property/, o.parse.bind(o, { a : 1 })); exception(/Error in property "c": Property lacks definition/i, o.parse.bind(o, { a : 1, b : true, c : "1" })); // With required specified. o = new TypeChecker({ type : { name : { type : "string", required : true } } }); assert.throws(o.parse.bind(o, {}), function (e) { assert.ok(/"name": Missing property/.test(e.message)); return true; }); // Non-required properties. o = new TypeChecker({ type : { a : { type : "number", required : false }, b : { type : "boolean", required : false } } }); eql({ a : 1, b : false }, o.parse({ a : 1, b : false })); var h = o.parse({ a : 1, b : undefined }); ok(!("b" in h)); h = o.parse({ a : 1, b : null }); equal(null, h.b); h = o.parse({ a : undefined, b : undefined }); ok(object.isEmpty(h)); h = o.parse({}); ok(object.isEmpty(h)); // Skip properties not in definition. o = new TypeChecker({ allowUndefined : true, type : { a : { type : "number" } } }); o.parse({}, false); eql({ a : ["Missing property"] }, o.getErrors()); o.parse({ a : 1 }); o.parse({ a : 1, b : 2 }); o.parse({ b : 2 }, false); eql({ a : ["Missing property"] }, o.getErrors()); // Remove skipped props that are undefined. eql({ a : 1 }, o.parse({ a : 1 })); }, T_Map : function () { var o = new TypeChecker({ map : true, type : "number" }); eql({ a : 1, b : 1 }, o.parse({ a : 1, b : 1 })); o.parse({ a : 1, b : false }, false); eql({ b : ['Expected "number", but got false (type "boolean")'] }, o.getErrors()); }, "T_Mixed" : function () { var o = new TypeChecker({ type : "mixed" }); equal(true, o.parse(true)); o.parse(""); o.parse({}); eql([], o.parse([])); ok(null === o.parse(null)); ok(undefined === o.parse(undefined)); equal("mixed", gettype(new TypeChecker.types.T_Mixed())); }, "typeof" : function () { var t = TypeChecker.typeof.bind(TypeChecker); equal("number", t(1)); equal("boolean", t(true)); equal("undefined", t(undefined)); equal("null", t(null)); equal("Function", t(function () {})); equal("Object", t({})); equal("Array", t([])); Class("JooseClass"); equal("JooseClass", t(new JooseClass())); function MyClass() {} equal("MyClass", t(new MyClass())); var AnonymousClass = function () {}; equal("anonymous type", t(new AnonymousClass)); }, "BUILD errors" : function () { exception(/Must be a hash/i, function () { return new TypeChecker(); }); exception(/May only specify one of required, defaultValue and defaultValueFunc/i, function () { return new TypeChecker({ required : true, defaultValue : 1 }); }); // required or defaultValue or defaultValueFunc }, helpers : function () { //var tc = new TypeChecker({ // type : "number", // validators : [{ // func : function (o, helpers) { // return !!helpers; // }, // message : "helpers == false" // }] //}); //tc.parse(1, true, true); //tc.parse(1, false, true); //eql({ // "" : ["helpers == false"] //}, tc.getErrors()); }, "recursive definition" : function () { var o = new TypeChecker({ type : { // type type : { required : false, type : "mixed", validators : [{ func : function (v) { if (typeof v === "string") { return collection.hasValue(["string", "number", "object", "function", "boolean", "mixed"], v); } else if (v instanceof Array) { // Flat check only. return v.length === 1; } else if (v instanceof Object) { // Flat check only. return true; } return false; } }] }, required : { type : "boolean", defaultValue : true }, defaultValue : { required : false, type : "mixed" }, defaultValueFunc : { required : false, type : Function }, validators : { type : [{ type : { func : { type : Function }, message : { type : "string" } } }], defaultValue : [] }, enumerable : { required : false, type : Array }, allowUndefined : { defaultValue : false, type : "boolean" } } }); o.parse({ type : "string" }); o.parse({ type : "number" }); o.parse({ required : false, type : "number" }); o.parse({ defaultValue : 3, type : "number" }); o.parse({ defaultValue : true, type : "boolean" }); o.parse({ defaultValue : 4, type : "mixed" }); o.parse({ defaultValue : {}, type : "mixed" }); o.parse({ defaultValueFunc : function () { return 1; }, type : "number" }); o.parse({ type : [{ type : "string" }] }); o.parse({ type : "mixed", validators : [{ func : Function.empty, message : "msg" }] }); o.parse({ type : "number", enumerable : [1,2,3] }); o.parse({ type : {} }); o.parse({ allowUndefined : true, type : {} }); } }; })();
bergmark/Cactus
module/Core/lib/Util/Util.TypeChecker.test.js
JavaScript
bsd-3-clause
22,955
/** * Swedish translation for bootstrap-wysihtml5 */ (function($){ $.fn.wysihtml5.locale["sv-SE"] = { font_styles: { normal: "Normal Text", h1: "Rubrik 1", h2: "Rubrik 2", h3: "Rubrik 3" }, emphasis: { bold: "Fet", italic: "Kursiv", underline: "Understruken" }, lists: { unordered: "Osorterad lista", ordered: "Sorterad lista", outdent: "Minska indrag", indent: "Öka indrag" }, link: { insert: "Lägg till länk", cancel: "Avbryt" }, image: { insert: "Lägg till Bild", cancel: "Avbryt" }, html: { edit: "Redigera HTML" }, colours: { black: "Svart", silver: "Silver", gray: "Grå", maroon: "Kastaniebrun", red: "Röd", purple: "Lila", green: "Grön", olive: "Olivgrön", navy: "Marinblå", blue: "Blå", orange: "Orange" } }; }(jQuery));
landasystems/tamanharapan
backend/extensions/bootstrap/assets/js/locales/bootstrap-wysihtml5.sv-SE.js
JavaScript
bsd-3-clause
1,185
// Benchpress: A collection of micro-benchmarks. var allResults = [ ]; // ----------------------------------------------------------------------------- // F r a m e w o r k // ----------------------------------------------------------------------------- function Benchmark(string, run) { this.string = string; this.run = run; } // Run each benchmark for two seconds and count number of iterations. function time(benchmark) { var elapsed = 0; var start = new Date(); for (var n = 0; elapsed < 2000; n++) { benchmark.run(); elapsed = new Date() - start; } var usec = (elapsed * 1000) / n; allResults.push(usec); print('Time (' + benchmark.string + '): ' + Math.floor(usec) + ' us.'); } function error(string) { print(string); } // ----------------------------------------------------------------------------- // L o o p // ----------------------------------------------------------------------------- function loop() { var sum = 0; for (var i = 0; i < 200; i++) { for (var j = 0; j < 100; j++) { sum++; } } if (sum != 20000) error("Wrong result: " + sum + " should be: 20000"); } var Loop = new Benchmark("Loop", loop); // ----------------------------------------------------------------------------- // M a i n // ----------------------------------------------------------------------------- time(Loop); var logMean = 0; for (var i = 0; i < allResults.length; i++) logMean += Math.log(allResults[i]); logMean /= allResults.length; print("Geometric mean: " + Math.round(Math.pow(Math.E, logMean)) + " us.");
daejunpark/jsaf
benchmarks/v8_v1/units/loop.js
JavaScript
bsd-3-clause
1,571
'use strict'; myApp.controller('editProfileController', ['$scope', '$state', 'loadingMaskService', 'CONSTANTS', '$uibModal', '$log', '$rootScope', '$http', function ($scope, $state, loadingMaskService, CONSTANTS, $uibModal, $log, $rootScope, $http) { var userInfo = JSON.parse(localStorage.getItem(CONSTANTS.LOCAL_STORAGE_KEY)); $scope.email = userInfo.email; $scope.date = userInfo.birthDate; $scope.firstName = userInfo.firstName; $scope.lastName = userInfo.lastName; $scope.relations = userInfo.relations; $scope.relationOptions = ['Мама', 'Отец', 'Брат']; $scope.submit = function () { if ($scope.editProfileForm.$valid && $scope.editProfileForm.$dirty) { // if form is valid var userInfo = { email: $scope.email, birthDate: $scope.date, firstName: $scope.firstName, lastName: $scope.lastName, relations: $scope.relations }; $http({ method: 'POST', url: '/editRelation', data: { email: userInfo.email, relations: $scope.relations } }).then(function successCallback(response) { localStorage.setItem(CONSTANTS.LOCAL_STORAGE_KEY, JSON.stringify(userInfo)); loadingMaskService.sendRequest(); $state.go('mainPageState.userProfile'); }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } }; $rootScope.$on('relationsUpdated', function(event, relations){ $scope.relations = relations; }); $rootScope.$on('relationRemoved', function(event, relations){ $scope.relations = relations; }); $scope.removeRelation = function(index) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/removeRelationConfirm.tpl.html', controller: 'removeRelationController', resolve: { index: function () { return index } } }); } $scope.open = function (size) { var modalInstance = $uibModal.open({ templateUrl: 'app/pages/src/editProfilePage/src/tpl/addARelation.tpl.html', controller: 'addRelationController' }); }; }]);
yslepianok/analysis_site
views/tests/app/pages/src/editProfilePage/src/editProfileController.js
JavaScript
bsd-3-clause
2,590
/* * Copyright (c) 2011 Yahoo! Inc. All rights reserved. */ YUI.add('master', function(Y, NAME) { /** * The master module. * * @module master */ var DIMENSIONS = { device: 'smartphone', region: 'CA', skin : 'grey' }; /** * Constructor for the Controller class. * * @class Controller * @constructor */ Y.mojito.controllers[NAME] = { init: function(config) { this.config = config; }, /** * Method corresponding to the 'index' action. * * @param ac {Object} The ActionContext that provides access * to the Mojito API. */ index: function(ac) { var dims = ac.params.getFromUrl(), self = this, config = { view: 'index', children: { primary: { type: 'primary', action: 'index' }, secondary: { type: 'secondary', action: 'index' } } }; ac.composite.execute(config, function (data, meta) { data.buttons = self.createButtons(ac, dims); ac.done(data, meta); }); }, createButtons: function (ac, dims) { var buttons = [], className, label, url; Y.each(Y.Object.keys(DIMENSIONS), function (dim) { var params = Y.merge({}, dims); className = 'nav nav-' + dim + (dims[dim] ? ' active' : ''); params[dim] ? delete params[dim] : params[dim] = DIMENSIONS[dim]; url = ac.url.make('htmlframe', 'index', null, 'GET', params); label = dim.substring(0,1).toUpperCase() + dim.substring(1); buttons.push('<a href="'+url+'" class="'+className+'">'+label+'</a>'); }); return buttons.join('\n'); } }; }, '0.0.1', {requires: ['mojito', 'mojito-assets-addon']});
triptych/shaker
examples/demo/mojits/master/controller.common.js
JavaScript
bsd-3-clause
2,296
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ export default {"viewBox":"0 0 100 100","xmlns":"http://www.w3.org/2000/svg","path":{"d":"M50.6 52.9c2.6-3.7 5.3-5.6 7.1-8.4 3.2-4.8 3.9-11.6 1.8-16.8-2.1-5.3-7-8.4-12.7-8.3S36.5 23 34.7 28.3c-2.1 5.8-1.2 12.8 3.5 17.2 1.9 1.8 3.7 4.7 2.7 7.4-.9 2.6-4 3.7-6.2 4.8-5 2.2-11.1 5.3-12.1 11.2-1 4.9 2.3 10 7.6 10h23.3c1 0 1.9-1.2 1.3-1.9-3.2-3.7-6.6-8.7-6.6-13.6-.3-3.5.7-7.4 2.4-10.5zm14.2 13.5c-2.7 0-5-2.2-5-4.9s2.2-4.9 5-4.9c2.7 0 5 2.2 5 4.9.1 2.7-2.3 4.9-5 4.9zm0-16.8c-6.6 0-11.9 5.3-11.9 11.9 0 8.1 8.5 15.8 11.1 17.7.4.4 1 .4 1.6 0 2.6-2.1 11.1-9.6 11.1-17.7 0-6.6-5.3-11.9-11.9-11.9z"}};
salesforce/design-system-react
icons/standard/visits.js
JavaScript
bsd-3-clause
746
import React from 'react'; import 'isomorphic-fetch'; import {RouteHandler} from 'react-router'; import Transmit from 'react-transmit'; import {createStore, combineReducers} from 'redux'; import {Provider} from 'react-redux'; import * as reducers from '../reducers/index'; class AppContainer extends React.Component { static propTypes = { initialState: React.PropTypes.object.isRequired } render() { const reducer = combineReducers(reducers); const store = createStore(reducer, this.props.initialState); return ( <Provider store={store}> {() => <RouteHandler /> } </Provider> ); } } export default Transmit.createContainer(AppContainer, { queries: {} });
nivanson/hapi-universal-redux
src/containers/AppContainer.js
JavaScript
bsd-3-clause
725
require("../pc.v0"); require("util").puts(JSON.stringify({ "name": "pc", "version": pc.version, "description": "property creation for reusable d3.js code.", "keywords": ["d3", "visualization"], "homepage": "http://milroc.github.com/pc/", "author": {"name": "Miles McCrocklin", "url": "http://www.milesmccrocklin.com" }, "repository": {"type": "git", "url": "http://github.com/milroc/pc.git"}, "devDependencies": { "uglify-js": "1.2.6", "vows": "0.6.0" } }, null, 2));
milroc/pc.js
src/package.js
JavaScript
bsd-3-clause
485
/*! jQuery UI - v1.11.4 - 2015-12-06 * http://jqueryui.com * Includes: core.js, datepicker.js * Copyright jQuery Foundation and other contributors; Licensed MIT */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI Core 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.4", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap='#" + mapName + "']" )[ 0 ]; return !!img && visible( img ); } return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; /*! * jQuery UI Datepicker 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/datepicker/ */ $.extend($.ui, { datepicker: { version: "1.11.4" } }); var datepicker_instActive; function datepicker_getZindex( elem ) { var position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } return 0; } /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.regional.en = $.extend( true, {}, this.regional[ "" ]); this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en ); this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { datepicker_extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, "datepicker", inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, "datepicker", inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], "datepicker", inst); } datepicker_extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], "datepicker", inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, "datepicker"); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } if ( datepicker_instActive === inst ) { datepicker_instActive = null; } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, "datepicker"); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); datepicker_extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } datepicker_extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 ); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) datepicker_instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17, activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" ); if ( activeCell.length > 0 ) { datepicker_handleMouseover.apply( activeCell.get( 0 ) ); } inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, "datepicker"))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), minSize = (match === "y" ? size : 1), digits = new RegExp("^\\d{" + minSize + "," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function datepicker_bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate( selector, "mouseover", datepicker_handleMouseover ); } function datepicker_handleMouseover() { if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } } /* jQuery extend now ignores nulls! */ function datepicker_extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.11.4"; var datepicker = $.datepicker; }));
davidred/spree_delivery_time
app/assets/javascripts/spree/frontend/store/datepicker.js
JavaScript
bsd-3-clause
91,677
var sbModule = angular.module('sbServices', ['ngResource']); sbModule.factory('App', function($resource) { return $resource('/api/v1/app/:name', { q: '' }, { get: { method: 'GET' }, //isArray: false }, query: { method: 'GET'} //, params: { q: '' }//, isArray: false } }); });
beni55/shipbuilder
webroot/js/services.js
JavaScript
bsd-3-clause
302
'use strict'; describe('Directive: searchFilters', function () { // load the directive's module beforeEach(module('searchApp')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); it('should make hidden element visible', inject(function ($compile) { element = angular.element('<search-filters></search-filters>'); element = $compile(element)(scope); expect(element.text()).toBe('this is the searchFilters directive'); })); });
MLR-au/esrc-search
test/spec/directives/search-filters.js
JavaScript
bsd-3-clause
509
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ export default {"viewBox":"0 0 52 52","xmlns":"http://www.w3.org/2000/svg","path":[{"d":"M43.3 6h-1.73a.74.74 0 00-.67.8V10a6.37 6.37 0 01-6.3 6.4H17.4a6.37 6.37 0 01-6.3-6.4V6.67a.74.74 0 00-.8-.67H8.7A4.77 4.77 0 004 10.8v34.4A4.77 4.77 0 008.7 50h34.6a4.77 4.77 0 004.7-4.8V10.8A4.77 4.77 0 0043.3 6zM25.92 45a12 12 0 01.16-24 12 12 0 01-.16 24z"},{"d":"M16.91 11.6h17.86a1.59 1.59 0 001.63-1.55V6.8A4.81 4.81 0 0031.6 2H20.4a4.82 4.82 0 00-4.8 4.8V10a1.47 1.47 0 001.31 1.6zM32.23 27.2A9.09 9.09 0 0026 24.4v8.8h8.77a7.32 7.32 0 00-2.54-6z"}]};
salesforce/design-system-react
icons/utility/capacity_plan.js
JavaScript
bsd-3-clause
701
// 1000-page badge // Awarded when total read page count exceeds 1000. var sys = require('sys'); var _ = require('underscore'); var users = require('../../users'); var badge_template = require('./badge'); // badge key, must be unique. var name = "1000page"; exports.badge_info = { id: name, name: "1,000 Pages", achievement: "Reading over 1,000 pages." } // the in-work state of a badge for a user function Badge (userid) { badge_template.Badge.apply(this,arguments); this.id = name; this.page_goal = 1000; }; // inherit from the badge template sys.inherits(Badge, badge_template.Badge); // Steps to perform when a book is added or modified in the read list Badge.prototype.add_reading_transform = function(reading,callback) { var pages = parseInt(reading.book.pages); if (_.isNumber(pages)) { this.state[reading.book_id] = pages } callback(); }; // Steps to perform when a book is removed from the read list. Badge.prototype.remove_book_transform = function(book,callback) { delete(this.state[book.id]); callback(); }; // determine if the badge should be awarded, and if yes, do so Badge.prototype.should_award = function(callback) { // sum all page counts in state var pagecount = 0; for (bookid in this.state) { pagecount += this.state[bookid] } return (pagecount >= this.page_goal); } exports.Badge = Badge;
scsibug/read52
badger/badges/1000page.js
JavaScript
bsd-3-clause
1,422
/* prevent execution of jQuery if included more than once */ if(typeof window.jQuery == "undefined") { /* * jQuery 1.1.2 - New Wave Javascript * * Copyright (c) 2007 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date: 2007-04-03 22:27:21 $ * $Rev: 1465 $ */ // Global undefined variable window.undefined = window.undefined; var jQuery = function(a,c) { // If the context is global, return a new object if ( window == this ) return new jQuery(a,c); // Make sure that a selection was provided a = a || document; // HANDLE: $(function) // Shortcut for document ready if ( jQuery.isFunction(a) ) return new jQuery(document)[ jQuery.fn.ready ? "ready" : "load" ]( a ); // Handle HTML strings if ( typeof a == "string" ) { // HANDLE: $(html) -> $(array) var m = /^[^<]*(<(.|\s)+>)[^>]*$/.exec(a); if ( m ) a = jQuery.clean( [ m[1] ] ); // HANDLE: $(expr) else return new jQuery( c ).find( a ); } return this.setArray( // HANDLE: $(array) a.constructor == Array && a || // HANDLE: $(arraylike) // Watch for when an array-like object is passed as the selector (a.jquery || a.length && a != window && !a.nodeType && a[0] != undefined && a[0].nodeType) && jQuery.makeArray( a ) || // HANDLE: $(*) [ a ] ); }; // Map over the $ in case of overwrite if ( typeof $ != "undefined" ) jQuery._$ = $; // Map the jQuery namespace to the '$' one var $ = jQuery; jQuery.fn = jQuery.prototype = { jquery: "1.1.2", size: function() { return this.length; }, length: 0, get: function( num ) { return num == undefined ? // Return a 'clean' array jQuery.makeArray( this ) : // Return just the object this[num]; }, pushStack: function( a ) { var ret = jQuery(a); ret.prevObject = this; return ret; }, setArray: function( a ) { this.length = 0; [].push.apply( this, a ); return this; }, each: function( fn, args ) { return jQuery.each( this, fn, args ); }, index: function( obj ) { var pos = -1; this.each(function(i){ if ( this == obj ) pos = i; }); return pos; }, attr: function( key, value, type ) { var obj = key; // Look for the case where we're accessing a style value if ( key.constructor == String ) if ( value == undefined ) return this.length && jQuery[ type || "attr" ]( this[0], key ) || undefined; else { obj = {}; obj[ key ] = value; } // Check to see if we're setting style values return this.each(function(index){ // Set all the styles for ( var prop in obj ) jQuery.attr( type ? this.style : this, prop, jQuery.prop(this, obj[prop], type, index, prop) ); }); }, css: function( key, value ) { return this.attr( key, value, "curCSS" ); }, text: function(e) { if ( typeof e == "string" ) return this.empty().append( document.createTextNode( e ) ); var t = ""; jQuery.each( e || this, function(){ jQuery.each( this.childNodes, function(){ if ( this.nodeType != 8 ) t += this.nodeType != 1 ? this.nodeValue : jQuery.fn.text([ this ]); }); }); return t; }, wrap: function() { // The elements to wrap the target around var a = jQuery.clean(arguments); // Wrap each of the matched elements individually return this.each(function(){ // Clone the structure that we're using to wrap var b = a[0].cloneNode(true); // Insert it before the element to be wrapped this.parentNode.insertBefore( b, this ); // Find the deepest point in the wrap structure while ( b.firstChild ) b = b.firstChild; // Move the matched element to within the wrap structure b.appendChild( this ); }); }, append: function() { return this.domManip(arguments, true, 1, function(a){ this.appendChild( a ); }); }, prepend: function() { return this.domManip(arguments, true, -1, function(a){ this.insertBefore( a, this.firstChild ); }); }, before: function() { return this.domManip(arguments, false, 1, function(a){ this.parentNode.insertBefore( a, this ); }); }, after: function() { return this.domManip(arguments, false, -1, function(a){ this.parentNode.insertBefore( a, this.nextSibling ); }); }, end: function() { return this.prevObject || jQuery([]); }, find: function(t) { return this.pushStack( jQuery.map( this, function(a){ return jQuery.find(t,a); }), t ); }, clone: function(deep) { return this.pushStack( jQuery.map( this, function(a){ var a = a.cloneNode( deep != undefined ? deep : true ); a.$events = null; // drop $events expando to avoid firing incorrect events return a; }) ); }, filter: function(t) { return this.pushStack( jQuery.isFunction( t ) && jQuery.grep(this, function(el, index){ return t.apply(el, [index]) }) || jQuery.multiFilter(t,this) ); }, not: function(t) { return this.pushStack( t.constructor == String && jQuery.multiFilter(t, this, true) || jQuery.grep(this, function(a) { return ( t.constructor == Array || t.jquery ) ? jQuery.inArray( a, t ) < 0 : a != t; }) ); }, add: function(t) { return this.pushStack( jQuery.merge( this.get(), t.constructor == String ? jQuery(t).get() : t.length != undefined && (!t.nodeName || t.nodeName == "FORM") ? t : [t] ) ); }, is: function(expr) { return expr ? jQuery.filter(expr,this).r.length > 0 : false; }, val: function( val ) { return val == undefined ? ( this.length ? this[0].value : null ) : this.attr( "value", val ); }, html: function( val ) { return val == undefined ? ( this.length ? this[0].innerHTML : null ) : this.empty().append( val ); }, domManip: function(args, table, dir, fn){ var clone = this.length > 1; var a = jQuery.clean(args); if ( dir < 0 ) a.reverse(); return this.each(function(){ var obj = this; if ( table && jQuery.nodeName(this, "table") && jQuery.nodeName(a[0], "tr") ) obj = this.getElementsByTagName("tbody")[0] || this.appendChild(document.createElement("tbody")); jQuery.each( a, function(){ fn.apply( obj, [ clone ? this.cloneNode(true) : this ] ); }); }); } }; jQuery.extend = jQuery.fn.extend = function() { // copy reference to target object var target = arguments[0], a = 1; // extend jQuery itself if only one argument is passed if ( arguments.length == 1 ) { target = this; a = 0; } var prop; while (prop = arguments[a++]) // Extend the base object for ( var i in prop ) target[i] = prop[i]; // Return the modified object return target; }; jQuery.extend({ noConflict: function() { if ( jQuery._$ ) $ = jQuery._$; return jQuery; }, // This may seem like some crazy code, but trust me when I say that this // is the only cross-browser way to do this. --John isFunction: function( fn ) { return !!fn && typeof fn != "string" && !fn.nodeName && typeof fn[0] == "undefined" && /function/i.test( fn + "" ); }, // check if an element is in a XML document isXMLDoc: function(elem) { return elem.tagName && elem.ownerDocument && !elem.ownerDocument.body; }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); }, // args is for internal usage only each: function( obj, fn, args ) { if ( obj.length == undefined ) for ( var i in obj ) fn.apply( obj[i], args || [i, obj[i]] ); else for ( var i = 0, ol = obj.length; i < ol; i++ ) if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break; return obj; }, prop: function(elem, value, type, index, prop){ // Handle executable functions if ( jQuery.isFunction( value ) ) value = value.call( elem, [index] ); // exclude the following css properties to add px var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i; // Handle passing in a number to a CSS property return value && value.constructor == Number && type == "curCSS" && !exclude.test(prop) ? value + "px" : value; }, className: { // internal only, use addClass("class") add: function( elem, c ){ jQuery.each( c.split(/\s+/), function(i, cur){ if ( !jQuery.className.has( elem.className, cur ) ) elem.className += ( elem.className ? " " : "" ) + cur; }); }, // internal only, use removeClass("class") remove: function( elem, c ){ elem.className = c ? jQuery.grep( elem.className.split(/\s+/), function(cur){ return !jQuery.className.has( c, cur ); }).join(" ") : ""; }, // internal only, use is(".class") has: function( t, c ) { t = t.className || t; // escape regex characters c = c.replace(/([\.\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); return t && new RegExp("(^|\\s)" + c + "(\\s|$)").test( t ); } }, swap: function(e,o,f) { for ( var i in o ) { e.style["old"+i] = e.style[i]; e.style[i] = o[i]; } f.apply( e, [] ); for ( var i in o ) e.style[i] = e.style["old"+i]; }, css: function(e,p) { if ( p == "height" || p == "width" ) { var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"]; jQuery.each( d, function(){ old["padding" + this] = 0; old["border" + this + "Width"] = 0; }); jQuery.swap( e, old, function() { if (jQuery.css(e,"display") != "none") { oHeight = e.offsetHeight; oWidth = e.offsetWidth; } else { e = jQuery(e.cloneNode(true)) .find(":radio").removeAttr("checked").end() .css({ visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0" }).appendTo(e.parentNode)[0]; var parPos = jQuery.css(e.parentNode,"position"); if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "relative"; oHeight = e.clientHeight; oWidth = e.clientWidth; if ( parPos == "" || parPos == "static" ) e.parentNode.style.position = "static"; e.parentNode.removeChild(e); } }); return p == "height" ? oHeight : oWidth; } return jQuery.curCSS( e, p ); }, curCSS: function(elem, prop, force) { var ret; if (prop == "opacity" && jQuery.browser.msie) return jQuery.attr(elem.style, "opacity"); if (prop == "float" || prop == "cssFloat") prop = jQuery.browser.msie ? "styleFloat" : "cssFloat"; if (!force && elem.style[prop]) ret = elem.style[prop]; else if (document.defaultView && document.defaultView.getComputedStyle) { if (prop == "cssFloat" || prop == "styleFloat") prop = "float"; prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase(); var cur = document.defaultView.getComputedStyle(elem, null); if ( cur ) ret = cur.getPropertyValue(prop); else if ( prop == "display" ) ret = "none"; else jQuery.swap(elem, { display: "block" }, function() { var c = document.defaultView.getComputedStyle(this, ""); ret = c && c.getPropertyValue(prop) || ""; }); } else if (elem.currentStyle) { var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();}); ret = elem.currentStyle[prop] || elem.currentStyle[newProp]; } return ret; }, clean: function(a) { var r = []; jQuery.each( a, function(i,arg){ if ( !arg ) return; if ( arg.constructor == Number ) arg = arg.toString(); // Convert html string into DOM nodes if ( typeof arg == "string" ) { // Trim whitespace, otherwise indexOf won't work as expected var s = jQuery.trim(arg), div = document.createElement("div"), tb = []; var wrap = // option or optgroup !s.indexOf("<opt") && [1, "<select>", "</select>"] || (!s.indexOf("<thead") || !s.indexOf("<tbody") || !s.indexOf("<tfoot")) && [1, "<table>", "</table>"] || !s.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] || // <thead> matched above (!s.indexOf("<td") || !s.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] || [0,"",""]; // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + s + wrap[2]; // Move to the right depth while ( wrap[0]-- ) div = div.firstChild; // Remove IE's autoinserted <tbody> from table fragments if ( jQuery.browser.msie ) { // String was a <table>, *may* have spurious <tbody> if ( !s.indexOf("<table") && s.indexOf("<tbody") < 0 ) tb = div.firstChild && div.firstChild.childNodes; // String was a bare <thead> or <tfoot> else if ( wrap[1] == "<table>" && s.indexOf("<tbody") < 0 ) tb = div.childNodes; for ( var n = tb.length-1; n >= 0 ; --n ) if ( jQuery.nodeName(tb[n], "tbody") && !tb[n].childNodes.length ) tb[n].parentNode.removeChild(tb[n]); } arg = []; for (var i=0, l=div.childNodes.length; i<l; i++) arg.push(div.childNodes[i]); } if ( arg.length === 0 && !jQuery.nodeName(arg, "form") ) return; if ( arg[0] == undefined || jQuery.nodeName(arg, "form") ) r.push( arg ); else r = jQuery.merge( r, arg ); }); return r; }, attr: function(elem, name, value){ var fix = jQuery.isXMLDoc(elem) ? {} : { "for": "htmlFor", "class": "className", "float": jQuery.browser.msie ? "styleFloat" : "cssFloat", cssFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat", innerHTML: "innerHTML", className: "className", value: "value", disabled: "disabled", checked: "checked", readonly: "readOnly", selected: "selected" }; // IE actually uses filters for opacity ... elem is actually elem.style if ( name == "opacity" && jQuery.browser.msie && value != undefined ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level elem.zoom = 1; // Set the alpha filter to set the opacity return elem.filter = elem.filter.replace(/alpha\([^\)]*\)/gi,"") + ( value == 1 ? "" : "alpha(opacity=" + value * 100 + ")" ); } else if ( name == "opacity" && jQuery.browser.msie ) return elem.filter ? parseFloat( elem.filter.match(/alpha\(opacity=(.*)\)/)[1] ) / 100 : 1; // Mozilla doesn't play well with opacity 1 if ( name == "opacity" && jQuery.browser.mozilla && value == 1 ) value = 0.9999; // Certain attributes only work when accessed via the old DOM 0 way if ( fix[name] ) { if ( value != undefined ) elem[fix[name]] = value; return elem[fix[name]]; } else if ( value == undefined && jQuery.browser.msie && jQuery.nodeName(elem, "form") && (name == "action" || name == "method") ) return elem.getAttributeNode(name).nodeValue; // IE elem.getAttribute passes even for style else if ( elem.tagName ) { if ( value != undefined ) elem.setAttribute( name, value ); if ( jQuery.browser.msie && /href|src/.test(name) && !jQuery.isXMLDoc(elem) ) return elem.getAttribute( name, 2 ); return elem.getAttribute( name ); // elem is actually elem.style ... set the style } else { name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();}); if ( value != undefined ) elem[name] = value; return elem[name]; } }, trim: function(t){ return t.replace(/^\s+|\s+$/g, ""); }, makeArray: function( a ) { var r = []; if ( a.constructor != Array ) for ( var i = 0, al = a.length; i < al; i++ ) r.push( a[i] ); else r = a.slice( 0 ); return r; }, inArray: function( b, a ) { for ( var i = 0, al = a.length; i < al; i++ ) if ( a[i] == b ) return i; return -1; }, merge: function(first, second) { var r = [].slice.call( first, 0 ); // Now check for duplicates between the two arrays // and only add the unique items for ( var i = 0, sl = second.length; i < sl; i++ ) // Check for duplicates if ( jQuery.inArray( second[i], r ) == -1 ) // The item is unique, add it first.push( second[i] ); return first; }, grep: function(elems, fn, inv) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( typeof fn == "string" ) fn = new Function("a","i","return " + fn); var result = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, el = elems.length; i < el; i++ ) if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) ) result.push( elems[i] ); return result; }, map: function(elems, fn) { // If a string is passed in for the function, make a function // for it (a handy shortcut) if ( typeof fn == "string" ) fn = new Function("a","return " + fn); var result = [], r = []; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, el = elems.length; i < el; i++ ) { var val = fn(elems[i],i); if ( val !== null && val != undefined ) { if ( val.constructor != Array ) val = [val]; result = result.concat( val ); } } var r = result.length ? [ result[0] ] : []; check: for ( var i = 1, rl = result.length; i < rl; i++ ) { for ( var j = 0; j < i; j++ ) if ( result[i] == r[j] ) continue check; r.push( result[i] ); } return r; } }); /* * Whether the W3C compliant box model is being used. * * @property * @name $.boxModel * @type Boolean * @cat JavaScript */ new function() { var b = navigator.userAgent.toLowerCase(); // Figure out what browser is being used jQuery.browser = { safari: /webkit/.test(b), opera: /opera/.test(b), msie: /msie/.test(b) && !/opera/.test(b), mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b) }; // Check to see if the W3C box model is being used jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat"; }; jQuery.each({ parent: "a.parentNode", parents: "jQuery.parents(a)", next: "jQuery.nth(a,2,'nextSibling')", prev: "jQuery.nth(a,2,'previousSibling')", siblings: "jQuery.sibling(a.parentNode.firstChild,a)", children: "jQuery.sibling(a.firstChild)" }, function(i,n){ jQuery.fn[ i ] = function(a) { var ret = jQuery.map(this,n); if ( a && typeof a == "string" ) ret = jQuery.multiFilter(a,ret); return this.pushStack( ret ); }; }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after" }, function(i,n){ jQuery.fn[ i ] = function(){ var a = arguments; return this.each(function(){ for ( var j = 0, al = a.length; j < al; j++ ) jQuery(a[j])[n]( this ); }); }; }); jQuery.each( { removeAttr: function( key ) { jQuery.attr( this, key, "" ); this.removeAttribute( key ); }, addClass: function(c){ jQuery.className.add(this,c); }, removeClass: function(c){ jQuery.className.remove(this,c); }, toggleClass: function( c ){ jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this, c); }, remove: function(a){ if ( !a || jQuery.filter( a, [this] ).r.length ) this.parentNode.removeChild( this ); }, empty: function() { while ( this.firstChild ) this.removeChild( this.firstChild ); } }, function(i,n){ jQuery.fn[ i ] = function() { return this.each( n, arguments ); }; }); jQuery.each( [ "eq", "lt", "gt", "contains" ], function(i,n){ jQuery.fn[ n ] = function(num,fn) { return this.filter( ":" + n + "(" + num + ")", fn ); }; }); jQuery.each( [ "height", "width" ], function(i,n){ jQuery.fn[ n ] = function(h) { return h == undefined ? ( this.length ? jQuery.css( this[0], n ) : null ) : this.css( n, h.constructor == String ? h : h + "px" ); }; }); jQuery.extend({ expr: { "": "m[2]=='*'||jQuery.nodeName(a,m[2])", "#": "a.getAttribute('id')==m[2]", ":": { // Position Checks lt: "i<m[3]-0", gt: "i>m[3]-0", nth: "m[3]-0==i", eq: "m[3]-0==i", first: "i==0", last: "i==r.length-1", even: "i%2==0", odd: "i%2", // Child Checks "nth-child": "jQuery.nth(a.parentNode.firstChild,m[3],'nextSibling',a)==a", "first-child": "jQuery.nth(a.parentNode.firstChild,1,'nextSibling')==a", "last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a", "only-child": "jQuery.sibling(a.parentNode.firstChild).length==1", // Parent Checks parent: "a.firstChild", empty: "!a.firstChild", // Text Check contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0", // Visibility visible: 'a.type!="hidden"&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"', hidden: 'a.type=="hidden"||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"', // Form attributes enabled: "!a.disabled", disabled: "a.disabled", checked: "a.checked", selected: "a.selected||jQuery.attr(a,'selected')", // Form elements text: "a.type=='text'", radio: "a.type=='radio'", checkbox: "a.type=='checkbox'", file: "a.type=='file'", password: "a.type=='password'", submit: "a.type=='submit'", image: "a.type=='image'", reset: "a.type=='reset'", button: 'a.type=="button"||jQuery.nodeName(a,"button")', input: "/input|select|textarea|button/i.test(a.nodeName)" }, ".": "jQuery.className.has(a,m[2])", "@": { "=": "z==m[4]", "!=": "z!=m[4]", "^=": "z&&!z.indexOf(m[4])", "$=": "z&&z.substr(z.length - m[4].length,m[4].length)==m[4]", "*=": "z&&z.indexOf(m[4])>=0", "": "z", _resort: function(m){ return ["", m[1], m[3], m[2], m[5]]; }, _prefix: "z=a[m[3]];if(!z||/href|src/.test(m[3]))z=jQuery.attr(a,m[3]);" }, "[": "jQuery.find(m[2],a).length" }, // The regular expressions that power the parsing engine parse: [ // Match: [@value='test'], [@foo] /^\[ *(@)([a-z0-9_-]*) *([!*$^=]*) *('?"?)(.*?)\4 *\]/i, // Match: [div], [div p] /^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/, // Match: :contains('foo') /^(:)([a-z0-9_-]*)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/i, // Match: :even, :last-chlid /^([:.#]*)([a-z0-9_*-]*)/i ], token: [ /^(\/?\.\.)/, "a.parentNode", /^(>|\/)/, "jQuery.sibling(a.firstChild)", /^(\+)/, "jQuery.nth(a,2,'nextSibling')", /^(~)/, function(a){ var s = jQuery.sibling(a.parentNode.firstChild); return s.slice(jQuery.inArray(a,s) + 1); } ], multiFilter: function( expr, elems, not ) { var old, cur = []; while ( expr && expr != old ) { old = expr; var f = jQuery.filter( expr, elems, not ); expr = f.t.replace(/^\s*,\s*/, "" ); cur = not ? elems = f.r : jQuery.merge( cur, f.r ); } return cur; }, find: function( t, context ) { // Quickly handle non-string expressions if ( typeof t != "string" ) return [ t ]; // Make sure that the context is a DOM Element if ( context && !context.nodeType ) context = null; // Set the correct context (if none is provided) context = context || document; // Handle the common XPath // expression if ( !t.indexOf("//") ) { context = context.documentElement; t = t.substr(2,t.length); // And the / root expression } else if ( !t.indexOf("/") ) { context = context.documentElement; t = t.substr(1,t.length); if ( t.indexOf("/") >= 1 ) t = t.substr(t.indexOf("/"),t.length); } // Initialize the search var ret = [context], done = [], last = null; // Continue while a selector expression exists, and while // we're no longer looping upon ourselves while ( t && last != t ) { var r = []; last = t; t = jQuery.trim(t).replace( /^\/\//i, "" ); var foundToken = false; // An attempt at speeding up child selectors that // point to a specific element tag var re = /^[\/>]\s*([a-z0-9*-]+)/i; var m = re.exec(t); if ( m ) { // Perform our own iteration and filter jQuery.each( ret, function(){ for ( var c = this.firstChild; c; c = c.nextSibling ) if ( c.nodeType == 1 && ( jQuery.nodeName(c, m[1]) || m[1] == "*" ) ) r.push( c ); }); ret = r; t = t.replace( re, "" ); if ( t.indexOf(" ") == 0 ) continue; foundToken = true; } else { // Look for pre-defined expression tokens for ( var i = 0; i < jQuery.token.length; i += 2 ) { // Attempt to match each, individual, token in // the specified order var re = jQuery.token[i]; var m = re.exec(t); // If the token match was found if ( m ) { // Map it against the token's handler r = ret = jQuery.map( ret, jQuery.isFunction( jQuery.token[i+1] ) ? jQuery.token[i+1] : function(a){ return eval(jQuery.token[i+1]); }); // And remove the token t = jQuery.trim( t.replace( re, "" ) ); foundToken = true; break; } } } // See if there's still an expression, and that we haven't already // matched a token if ( t && !foundToken ) { // Handle multiple expressions if ( !t.indexOf(",") ) { // Clean the result set if ( ret[0] == context ) ret.shift(); // Merge the result sets jQuery.merge( done, ret ); // Reset the context r = ret = [context]; // Touch up the selector string t = " " + t.substr(1,t.length); } else { // Optomize for the case nodeName#idName var re2 = /^([a-z0-9_-]+)(#)([a-z0-9\\*_-]*)/i; var m = re2.exec(t); // Re-organize the results, so that they're consistent if ( m ) { m = [ 0, m[2], m[3], m[1] ]; } else { // Otherwise, do a traditional filter check for // ID, class, and element selectors re2 = /^([#.]?)([a-z0-9\\*_-]*)/i; m = re2.exec(t); } // Try to do a global search by ID, where we can if ( m[1] == "#" && ret[ret.length-1].getElementById ) { // Optimization for HTML document case var oid = ret[ret.length-1].getElementById(m[2]); // Do a quick check for the existence of the actual ID attribute // to avoid selecting by the name attribute in IE if ( jQuery.browser.msie && oid && oid.id != m[2] ) oid = jQuery('[@id="'+m[2]+'"]', ret[ret.length-1])[0]; // Do a quick check for node name (where applicable) so // that div#foo searches will be really fast ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : []; } else { // Pre-compile a regular expression to handle class searches if ( m[1] == "." ) var rec = new RegExp("(^|\\s)" + m[2] + "(\\s|$)"); // We need to find all descendant elements, it is more // efficient to use getAll() when we are already further down // the tree - we try to recognize that here jQuery.each( ret, function(){ // Grab the tag name being searched for var tag = m[1] != "" || m[0] == "" ? "*" : m[2]; // Handle IE7 being really dumb about <object>s if ( jQuery.nodeName(this, "object") && tag == "*" ) tag = "param"; jQuery.merge( r, m[1] != "" && ret.length != 1 ? jQuery.getAll( this, [], m[1], m[2], rec ) : this.getElementsByTagName( tag ) ); }); // It's faster to filter by class and be done with it if ( m[1] == "." && ret.length == 1 ) r = jQuery.grep( r, function(e) { return rec.test(e.className); }); // Same with ID filtering if ( m[1] == "#" && ret.length == 1 ) { // Remember, then wipe out, the result set var tmp = r; r = []; // Then try to find the element with the ID jQuery.each( tmp, function(){ if ( this.getAttribute("id") == m[2] ) { r = [ this ]; return false; } }); } ret = r; } t = t.replace( re2, "" ); } } // If a selector string still exists if ( t ) { // Attempt to filter it var val = jQuery.filter(t,r); ret = r = val.r; t = jQuery.trim(val.t); } } // Remove the root context if ( ret && ret[0] == context ) ret.shift(); // And combine the results jQuery.merge( done, ret ); return done; }, filter: function(t,r,not) { // Look for common filter expressions while ( t && /^[a-z[({<*:.#]/i.test(t) ) { var p = jQuery.parse, m; jQuery.each( p, function(i,re){ // Look for, and replace, string-like sequences // and finally build a regexp out of it m = re.exec( t ); if ( m ) { // Remove what we just matched t = t.substring( m[0].length ); // Re-organize the first match if ( jQuery.expr[ m[1] ]._resort ) m = jQuery.expr[ m[1] ]._resort( m ); return false; } }); // :not() is a special case that can be optimized by // keeping it out of the expression list if ( m[1] == ":" && m[2] == "not" ) r = jQuery.filter(m[3], r, true).r; // Handle classes as a special case (this will help to // improve the speed, as the regexp will only be compiled once) else if ( m[1] == "." ) { var re = new RegExp("(^|\\s)" + m[2] + "(\\s|$)"); r = jQuery.grep( r, function(e){ return re.test(e.className || ""); }, not); // Otherwise, find the expression to execute } else { var f = jQuery.expr[m[1]]; if ( typeof f != "string" ) f = jQuery.expr[m[1]][m[2]]; // Build a custom macro to enclose it eval("f = function(a,i){" + ( jQuery.expr[ m[1] ]._prefix || "" ) + "return " + f + "}"); // Execute it against the current filter r = jQuery.grep( r, f, not ); } } // Return an array of filtered elements (r) // and the modified expression string (t) return { r: r, t: t }; }, getAll: function( o, r, token, name, re ) { for ( var s = o.firstChild; s; s = s.nextSibling ) if ( s.nodeType == 1 ) { var add = true; if ( token == "." ) add = s.className && re.test(s.className); else if ( token == "#" ) add = s.getAttribute("id") == name; if ( add ) r.push( s ); if ( token == "#" && r.length ) break; if ( s.firstChild ) jQuery.getAll( s, r, token, name, re ); } return r; }, parents: function( elem ){ var matched = []; var cur = elem.parentNode; while ( cur && cur != document ) { matched.push( cur ); cur = cur.parentNode; } return matched; }, nth: function(cur,result,dir,elem){ result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType == 1 ) num++; if ( num == result || result == "even" && num % 2 == 0 && num > 1 && cur == elem || result == "odd" && num % 2 == 1 && cur == elem ) return cur; } }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType == 1 && (!elem || n != elem) ) r.push( n ); } return r; } }); /* * A number of helper functions used for managing events. * Many of the ideas behind this code orignated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function(element, type, handler, data) { // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.browser.msie && element.setInterval != undefined ) element = window; // if data is passed, bind to handler if( data ) handler.data = data; // Make sure that the function being executed has a unique ID if ( !handler.guid ) handler.guid = this.guid++; // Init the element's event structure if (!element.$events) element.$events = {}; // Get the current list of functions bound to this event var handlers = element.$events[type]; // If it hasn't been initialized yet if (!handlers) { // Init the event handler queue handlers = element.$events[type] = {}; // Remember an existing handler, if it's already there if (element["on" + type]) handlers[0] = element["on" + type]; } // Add the function to the element's handler list handlers[handler.guid] = handler; // And bind the global event handler to the element element["on" + type] = this.handle; // Remember the function in a global list (for triggering) if (!this.global[type]) this.global[type] = []; this.global[type].push( element ); }, guid: 1, global: {}, // Detach an event or set of events from an element remove: function(element, type, handler) { if (element.$events) { var i,j,k; if ( type && type.type ) { // type is actually an event object here handler = type.handler; type = type.type; } if (type && element.$events[type]) // remove the given handler for the given type if ( handler ) delete element.$events[type][handler.guid]; // remove all handlers for the given type else for ( i in element.$events[type] ) delete element.$events[type][i]; // remove all handlers else for ( j in element.$events ) this.remove( element, j ); // remove event handler if no more handlers exist for ( k in element.$events[type] ) if (k) { k = true; break; } if (!k) element["on" + type] = null; } }, trigger: function(type, data, element) { // Clone the incoming data, if any data = jQuery.makeArray(data || []); // Handle a global trigger if ( !element ) jQuery.each( this.global[type] || [], function(){ jQuery.event.trigger( type, data, this ); }); // Handle triggering a single element else { var handler = element["on" + type ], val, fn = jQuery.isFunction( element[ type ] ); if ( handler ) { // Pass along a fake event data.unshift( this.fix({ type: type, target: element }) ); // Trigger the event if ( (val = handler.apply( element, data )) !== false ) this.triggered = true; } if ( fn && val !== false ) element[ type ](); this.triggered = false; } }, handle: function(event) { // Handle the second event of a trigger and when // an event is called after a page has unloaded if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return; // Empty object is for triggered events with no data event = jQuery.event.fix( event || window.event || {} ); // returned undefined or false var returnValue; var c = this.$events[event.type]; var args = [].slice.call( arguments, 1 ); args.unshift( event ); for ( var j in c ) { // Pass in a reference to the handler function itself // So that we can later remove it args[0].handler = c[j]; args[0].data = c[j].data; if ( c[j].apply( this, args ) === false ) { event.preventDefault(); event.stopPropagation(); returnValue = false; } } // Clean up added properties in IE to prevent memory leak if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null; return returnValue; }, fix: function(event) { // Fix target property, if necessary if ( !event.target && event.srcElement ) event.target = event.srcElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == undefined && event.clientX != undefined ) { var e = document.documentElement, b = document.body; event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft); event.pageY = event.clientY + (e.scrollTop || b.scrollTop); } // check if target is a textnode (safari) if (jQuery.browser.safari && event.target.nodeType == 3) { // store a copy of the original event object // and clone because target is read only var originalEvent = event; event = jQuery.extend({}, originalEvent); // get parentnode from textnode event.target = originalEvent.target.parentNode; // add preventDefault and stopPropagation since // they will not work on the clone event.preventDefault = function() { return originalEvent.preventDefault(); }; event.stopPropagation = function() { return originalEvent.stopPropagation(); }; } // fix preventDefault and stopPropagation if (!event.preventDefault) event.preventDefault = function() { this.returnValue = false; }; if (!event.stopPropagation) event.stopPropagation = function() { this.cancelBubble = true; }; return event; } }; jQuery.fn.extend({ bind: function( type, data, fn ) { return this.each(function(){ jQuery.event.add( this, type, fn || data, data ); }); }, one: function( type, data, fn ) { return this.each(function(){ jQuery.event.add( this, type, function(event) { jQuery(this).unbind(event); return (fn || data).apply( this, arguments); }, data); }); }, unbind: function( type, fn ) { return this.each(function(){ jQuery.event.remove( this, type, fn ); }); }, trigger: function( type, data ) { return this.each(function(){ jQuery.event.trigger( type, data, this ); }); }, toggle: function() { // Save reference to arguments for access in closure var a = arguments; return this.click(function(e) { // Figure out which function to execute this.lastToggle = this.lastToggle == 0 ? 1 : 0; // Make sure that clicks stop e.preventDefault(); // and execute the function return a[this.lastToggle].apply( this, [e] ) || false; }); }, hover: function(f,g) { // A private function for handling mouse 'hovering' function handleHover(e) { // Check if mouse(over|out) are still within the same parent element var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; // Traverse up the tree while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; }; // If we actually just moused on to a sub-element, ignore it if ( p == this ) return false; // Execute the right function return (e.type == "mouseover" ? f : g).apply(this, [e]); } // Bind the function to the two event listeners return this.mouseover(handleHover).mouseout(handleHover); }, ready: function(f) { // If the DOM is already ready if ( jQuery.isReady ) // Execute the function immediately f.apply( document, [jQuery] ); // Otherwise, remember the function for later else { // Add the function to the wait list jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } ); } return this; } }); jQuery.extend({ /* * All the code that makes DOM Ready work nicely. */ isReady: false, readyList: [], // Handle when the DOM is ready ready: function() { // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( jQuery.readyList ) { // Execute all of them jQuery.each( jQuery.readyList, function(){ this.apply( document ); }); // Reset the list of functions jQuery.readyList = null; } // Remove event lisenter to avoid memory leak if ( jQuery.browser.mozilla || jQuery.browser.opera ) document.removeEventListener( "DOMContentLoaded", jQuery.ready, false ); } } }); new function(){ jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," + "mousedown,mouseup,mousemove,mouseover,mouseout,change,select," + "submit,keydown,keypress,keyup,error").split(","), function(i,o){ // Handle event binding jQuery.fn[o] = function(f){ return f ? this.bind(o, f) : this.trigger(o); }; }); // If Mozilla is used if ( jQuery.browser.mozilla || jQuery.browser.opera ) // Use the handy event callback document.addEventListener( "DOMContentLoaded", jQuery.ready, false ); // If IE is used, use the excellent hack by Matthias Miller // http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited else if ( jQuery.browser.msie ) { // Only works if you document.write() it document.write("<scr" + "ipt id=__ie_init defer=true " + "src=//:><\/script>"); // Use the defer script hack var script = document.getElementById("__ie_init"); // script does not exist if jQuery is loaded dynamically if ( script ) script.onreadystatechange = function() { if ( this.readyState != "complete" ) return; this.parentNode.removeChild( this ); jQuery.ready(); }; // Clear from memory script = null; // If Safari is used } else if ( jQuery.browser.safari ) // Continually check to see if the document.readyState is valid jQuery.safariTimer = setInterval(function(){ // loaded and complete are both valid states if ( document.readyState == "loaded" || document.readyState == "complete" ) { // If either one are found, remove the timer clearInterval( jQuery.safariTimer ); jQuery.safariTimer = null; // and execute any waiting functions jQuery.ready(); } }, 10); // A fallback to window.onload, that will always work jQuery.event.add( window, "load", jQuery.ready ); }; // Clean up after IE to avoid memory leaks if (jQuery.browser.msie) jQuery(window).one("unload", function() { var global = jQuery.event.global; for ( var type in global ) { var els = global[type], i = els.length; if ( i && type != 'unload' ) do jQuery.event.remove(els[i-1], type); while (--i); } }); jQuery.fn.extend({ loadIfModified: function( url, params, callback ) { this.load( url, params, callback, 1 ); }, load: function( url, params, callback, ifModified ) { if ( jQuery.isFunction( url ) ) return this.bind("load", url); callback = callback || function(){}; // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else { params = jQuery.param( params ); type = "POST"; } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, data: params, ifModified: ifModified, complete: function(res, status){ if ( status == "success" || !ifModified && status == "notmodified" ) // Inject the HTML into all the matched elements self.attr("innerHTML", res.responseText) // Execute all the scripts inside of the newly-injected HTML .evalScripts() // Execute callback .each( callback, [res.responseText, status, res] ); else callback.apply( self, [res.responseText, status, res] ); } }); return this; }, serialize: function() { return jQuery.param( this ); }, evalScripts: function() { return this.find("script").each(function(){ if ( this.src ) jQuery.getScript( this.src ); else jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" ); }).end(); } }); // If IE is used, create a wrapper for the XMLHttpRequest object if ( !window.XMLHttpRequest ) XMLHttpRequest = function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){ jQuery.fn[o] = function(f){ return this.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type, ifModified ) { // shift arguments if data argument was ommited if ( jQuery.isFunction( data ) ) { callback = data; data = null; } return jQuery.ajax({ url: url, data: data, success: callback, dataType: type, ifModified: ifModified }); }, getIfModified: function( url, data, callback, type ) { return jQuery.get(url, data, callback, type, 1); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { if ( jQuery.isFunction( data ) ) { callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, // timeout (ms) //timeout: 0, ajaxTimeout: function( timeout ) { jQuery.ajaxSettings.timeout = timeout; }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { global: true, type: "GET", timeout: 0, contentType: "application/x-www-form-urlencoded", processData: true, async: true, data: null }, // Last-Modified header cache for next request lastModified: {}, ajax: function( s ) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); // if data available if ( s.data ) { // convert data if not already a string if (s.processData && typeof s.data != "string") s.data = jQuery.param(s.data); // append data to url for get requests if( s.type.toLowerCase() == "get" ) { // "?" + data or "&" + data (in case there are already params) s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data; // IE likes to send both get and post data, prevent this s.data = null; } } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) jQuery.event.trigger( "ajaxStart" ); var requestDone = false; // Create the request object var xml = new XMLHttpRequest(); // Open the socket xml.open(s.type, s.url, s.async); // Set the correct header, if data is being sent if ( s.data ) xml.setRequestHeader("Content-Type", s.contentType); // Set the If-Modified-Since header, if ifModified mode. if ( s.ifModified ) xml.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" ); // Set header so the called script knows that it's an XMLHttpRequest xml.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // Make sure the browser sends the right content length if ( xml.overrideMimeType ) xml.setRequestHeader("Connection", "close"); // Allow custom headers/mimetypes if( s.beforeSend ) s.beforeSend(xml); if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var onreadystatechange = function(isTimeout){ // The transfer is complete and the data is available, or the request timed out if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) { requestDone = true; // clear poll interval if (ival) { clearInterval(ival); ival = null; } var status; try { status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ? s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // Cache Last-Modified header, if ifModified mode. var modRes; try { modRes = xml.getResponseHeader("Last-Modified"); } catch(e) {} // swallow exception thrown by FF if header is not available if ( s.ifModified && modRes ) jQuery.lastModified[s.url] = modRes; // process the data (runs the xml through httpData regardless of callback) var data = jQuery.httpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); // Stop memory leaks if(s.async) xml = null; } }; // don't attach the handler to the request, just poll it instead var ival = setInterval(onreadystatechange, 13); // Timeout checker if ( s.timeout > 0 ) setTimeout(function(){ // Check to see if the request is still happening if ( xml ) { // Cancel the request xml.abort(); if( !requestDone ) onreadystatechange( "timeout" ); } }, s.timeout); // Send the data try { xml.send(s.data); } catch(e) { jQuery.handleError(s, xml, null, e); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) onreadystatechange(); // return XMLHttpRequest to allow aborting the request etc. return xml; }, handleError: function( s, xml, status, e ) { // If a local callback was specified, fire it if ( s.error ) s.error( xml, status, e ); // Fire the global callback if ( s.global ) jQuery.event.trigger( "ajaxError", [xml, s, e] ); }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( r ) { try { return !r.status && location.protocol == "file:" || ( r.status >= 200 && r.status < 300 ) || r.status == 304 || jQuery.browser.safari && r.status == undefined; } catch(e){} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xml, url ) { try { var xmlRes = xml.getResponseHeader("Last-Modified"); // Firefox always returns 200. check Last-Modified date return xml.status == 304 || xmlRes == jQuery.lastModified[url] || jQuery.browser.safari && xml.status == undefined; } catch(e){} return false; }, /* Get the data out of an XMLHttpRequest. * Return parsed XML if content-type header is "xml" and type is "xml" or omitted, * otherwise return plain text. * (String) data - The type of data that you're expecting back, * (e.g. "xml", "html", "script") */ httpData: function( r, type ) { var ct = r.getResponseHeader("content-type"); var data = !type && ct && ct.indexOf("xml") >= 0; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) eval( "data = " + data ); // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a ) { var s = []; // If an array was passed in, assume that it is an array // of form elements if ( a.constructor == Array || a.jquery ) // Serialize the form elements jQuery.each( a, function(){ s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) ); }); // Otherwise, assume that it's an object of key/value pairs else // Serialize the key/values for ( var j in a ) // If the value is an array then the key names need to be repeated if ( a[j] && a[j].constructor == Array ) jQuery.each( a[j], function(){ s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) ); }); else s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) ); // Return the resulting serialization return s.join("&"); }, // evalulates a script in global context // not reliable for safari globalEval: function( data ) { if ( window.execScript ) window.execScript( data ); else if ( jQuery.browser.safari ) // safari doesn't provide a synchronous global eval window.setTimeout( data, 0 ); else eval.call( window, data ); } }); jQuery.fn.extend({ show: function(speed,callback){ var hidden = this.filter(":hidden"); speed ? hidden.animate({ height: "show", width: "show", opacity: "show" }, speed, callback) : hidden.each(function(){ this.style.display = this.oldblock ? this.oldblock : ""; if ( jQuery.css(this,"display") == "none" ) this.style.display = "block"; }); return this; }, hide: function(speed,callback){ var visible = this.filter(":visible"); speed ? visible.animate({ height: "hide", width: "hide", opacity: "hide" }, speed, callback) : visible.each(function(){ this.oldblock = this.oldblock || jQuery.css(this,"display"); if ( this.oldblock == "none" ) this.oldblock = "block"; this.style.display = "none"; }); return this; }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ){ var args = arguments; return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ? this._toggle( fn, fn2 ) : this.each(function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ] .apply( jQuery(this), args ); }); }, slideDown: function(speed,callback){ return this.animate({height: "show"}, speed, callback); }, slideUp: function(speed,callback){ return this.animate({height: "hide"}, speed, callback); }, slideToggle: function(speed, callback){ return this.each(function(){ var state = jQuery(this).is(":hidden") ? "show" : "hide"; jQuery(this).animate({height: state}, speed, callback); }); }, fadeIn: function(speed, callback){ return this.animate({opacity: "show"}, speed, callback); }, fadeOut: function(speed, callback){ return this.animate({opacity: "hide"}, speed, callback); }, fadeTo: function(speed,to,callback){ return this.animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { return this.queue(function(){ this.curAnim = jQuery.extend({}, prop); var opt = jQuery.speed(speed, easing, callback); for ( var p in prop ) { var e = new jQuery.fx( this, opt, p ); if ( prop[p].constructor == Number ) e.custom( e.cur(), prop[p] ); else e[ prop[p] ]( prop ); } }); }, queue: function(type,fn){ if ( !fn ) { fn = type; type = "fx"; } return this.each(function(){ if ( !this.queue ) this.queue = {}; if ( !this.queue[type] ) this.queue[type] = []; this.queue[type].push( fn ); if ( this.queue[type].length == 1 ) fn.apply(this); }); } }); jQuery.extend({ speed: function(speed, easing, fn) { var opt = speed && speed.constructor == Object ? speed : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && easing.constructor != Function && easing }; opt.duration = (opt.duration && opt.duration.constructor == Number ? opt.duration : { slow: 600, fast: 200 }[opt.duration]) || 400; // Queueing opt.old = opt.complete; opt.complete = function(){ jQuery.dequeue(this, "fx"); if ( jQuery.isFunction( opt.old ) ) opt.old.apply( this ); }; return opt; }, easing: {}, queue: {}, dequeue: function(elem,type){ type = type || "fx"; if ( elem.queue && elem.queue[type] ) { // Remove self elem.queue[type].shift(); // Get next function var f = elem.queue[type][0]; if ( f ) f.apply( elem ); } }, /* * I originally wrote fx() as a clone of moo.fx and in the process * of making it small in size the code became illegible to sane * people. You've been warned. */ fx: function( elem, options, prop ){ var z = this; // The styles var y = elem.style; // Store display property var oldDisplay = jQuery.css(elem, "display"); // Make sure that nothing sneaks out y.overflow = "hidden"; // Simple function for setting a style value z.a = function(){ if ( options.step ) options.step.apply( elem, [ z.now ] ); if ( prop == "opacity" ) jQuery.attr(y, "opacity", z.now); // Let attr handle opacity else if ( parseInt(z.now) ) // My hate for IE will never die y[prop] = parseInt(z.now) + "px"; y.display = "block"; // Set display property to block for animation }; // Figure out the maximum number to run to z.max = function(){ return parseFloat( jQuery.css(elem,prop) ); }; // Get the current size z.cur = function(){ var r = parseFloat( jQuery.curCSS(elem, prop) ); return r && r > -10000 ? r : z.max(); }; // Start an animation from one number to another z.custom = function(from,to){ z.startTime = (new Date()).getTime(); z.now = from; z.a(); z.timer = setInterval(function(){ z.step(from, to); }, 13); }; // Simple 'show' function z.show = function(){ if ( !elem.orig ) elem.orig = {}; // Remember where we started, so that we can go back to it later elem.orig[prop] = this.cur(); options.show = true; // Begin the animation z.custom(0, elem.orig[prop]); // Stupid IE, look what you made me do if ( prop != "opacity" ) y[prop] = "1px"; }; // Simple 'hide' function z.hide = function(){ if ( !elem.orig ) elem.orig = {}; // Remember where we started, so that we can go back to it later elem.orig[prop] = this.cur(); options.hide = true; // Begin the animation z.custom(elem.orig[prop], 0); }; //Simple 'toggle' function z.toggle = function() { if ( !elem.orig ) elem.orig = {}; // Remember where we started, so that we can go back to it later elem.orig[prop] = this.cur(); if(oldDisplay == "none") { options.show = true; // Stupid IE, look what you made me do if ( prop != "opacity" ) y[prop] = "1px"; // Begin the animation z.custom(0, elem.orig[prop]); } else { options.hide = true; // Begin the animation z.custom(elem.orig[prop], 0); } }; // Each step of an animation z.step = function(firstNum, lastNum){ var t = (new Date()).getTime(); if (t > options.duration + z.startTime) { // Stop the timer clearInterval(z.timer); z.timer = null; z.now = lastNum; z.a(); if (elem.curAnim) elem.curAnim[ prop ] = true; var done = true; for ( var i in elem.curAnim ) if ( elem.curAnim[i] !== true ) done = false; if ( done ) { // Reset the overflow y.overflow = ""; // Reset the display y.display = oldDisplay; if (jQuery.css(elem, "display") == "none") y.display = "block"; // Hide the element if the "hide" operation was done if ( options.hide ) y.display = "none"; // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) for ( var p in elem.curAnim ) if (p == "opacity") jQuery.attr(y, p, elem.orig[p]); else y[p] = ""; } // If a callback was provided, execute it if ( done && jQuery.isFunction( options.complete ) ) // Execute the complete function options.complete.apply( elem ); } else { var n = t - this.startTime; // Figure out where in the animation we are and set the number var p = n / options.duration; // If the easing function exists, then use it z.now = options.easing && jQuery.easing[options.easing] ? jQuery.easing[options.easing](p, n, firstNum, (lastNum-firstNum), options.duration) : // else use default linear easing ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum; // Perform the next step of the animation z.a(); } }; } }); }
NCIP/eagle
WebRoot/js/lib/jquery.js
JavaScript
bsd-3-clause
59,266
/************************************************************************************** * Copyright (c) 2013-2015, Finnish Social Science Data Archive/University of Tampere * * * * 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. Neither the name of the copyright holder 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. * **************************************************************************************/ define(function (require) { 'use strict'; /** * Add localizations for general UI elements such as buttons * as well as all error messages even though most of these will not be needed at one time */ require('./addTranslation')('', { "page": { "&title": { "default": "Yhteiskuntatieteellinen tietoarkisto - Metka" } }, "topmenu": { "&desktop": { "default": "Työpöytä" }, "&expert": { "default": "Eksperttihaku" }, "&study": { "default": "Aineistot" }, "&variables": { "default": "Muuttujat" }, "&publication": { "default": "Julkaisut" }, "&series": { "default": "Sarjat" }, "&binder": { "default": "Mapit" }, "&report": { "default": "Raportit" }, "&settings": { "default": "Asetukset" }, "&help": { "default": "Ohjeet" }, "&logout": { "default": "Kirjaudu ulos" } }, "state": { "&DRAFT": { "default": "LUONNOS" }, "&APPROVED": { "default": "HYVÄKSYTTY" }, "&REMOVED": { "default": "POISTETTU" } }, "type": { "SERIES": { "&title": { "default": "Sarja" }, "&search": { "default": "Sarjahaku" } }, "STUDY": { "&title": { "default": "Aineisto" }, "&search": { "default": "Aineistohaku" }, "erroneous": { "&title": { "default": "Virheelliset" }, "table": { "&id": { "default": "Aineistonumero" }, "&name": { "default": "Aineiston nimi" }, "&errorPointCount": { "default": "Virhepisteet" } } } }, "STUDY_VARIABLES": { "&title": { "default": "Muuttujat" }, "&search": { "default": "Muuttujahaku" } }, "STUDY_VARIABLE": { "&title": { "default": "Muuttuja" }, "&search": { "default": "Muuttujahaku" } }, "STUDY_ATTACHMENT": { "&title": { "default": "Liite" }, "&search": { "default": "Liitehaku" } }, "PUBLICATION": { "&title": { "default": "Julkaisu" }, "&search": { "default": "Julkaisuhaku" } }, "BINDERS": { "&title": { "default": "Mapit" } }, "SETTINGS": { "&title": { "default": "Hallinta" } }, "BINDER_PAGE": { "&title": { "default": "Mapitus" } }, "STUDY_ERROR": { "&title": { "default": "Aineistovirhe" } } }, "general": { "result": { "&amount": { "default": "Rivejä: {length}" } }, "downloadInfo": { "&currentlyDownloading": { "default": "Lataus on jo käynnissä. Odota latauksen valmistumista ladataksesi uudelleen." } }, "buttons": { "&add": { "default": "Lisää" }, "&addSeries": { "default": "Lisää sarja" }, "&cancel": { "default": "Peruuta" }, "&close": { "default": "Sulje" }, "&download": { "default": "Lataa" }, "&upload": { "default": "Lataa" }, "&ok": { "default": "OK" }, "&save": { "default": "Tallenna" }, "&search": { "default": "Hae" }, "&remove": { "default": "Poista" }, "&no": { "default": "Ei" }, "&yes": { "default": "Kyllä" }, "&addGroup": { "default": "Lisää ryhmä" } }, "revision": { "compare": { "&begin": { "default": "Alku" }, "&changed": { "default": "Muutos" }, "&end": { "default": "Loppu" }, "&modifier": { "default": "Muuttaja" }, "&modifyDate": { "default": "Muutospvm" }, "&property": { "default": "Ominaisuus" }, "&original": { "default": "Alkuperäinen" }, "&title": { "default": "Revisioiden vertailu (revisio {0} -> revisio {1})" } }, "&compare": { "default": "Vertaa" }, "&publishDate": { "default": "Julkaisupvm" }, "&replace": { "default": "Korvaa" }, "&revisions": { "default": "Revisiot" } }, "&referenceValue": { "default": "Referenssiarvo" }, "&referenceType": { "default": "Tyyppi" }, "saveInfo": { "&savedAt": { "default": "Päivämäärä" }, "&savedBy": { "default": "Tallentaja" } }, "refSaveInfo": { "&savedAt": { "default": "Päivämäärä (viittaus)" }, "&savedBy": { "default": "Tallentaja (viittaus)" } }, "&refState": { "default": "Tila" }, "refApproveInfo": { "&approvedAt": { "default": "Hyväksytty (viittaus)" }, "&approvedBy": { "default": "Hyväksyjä (viittaus)" }, "&approvedRevision": { "default": "Revisio (viittaus)" } }, "selection": { "&empty": { "default": "-- Valitse --" } }, "table": { "&add": { "default": "Lisää" }, "countries": { "&addFinland": { "default": "Lisää Suomi" } } }, "&id": { "default": "ID" }, "&revision": { "default": "Revisio" }, "&handler": { "default": "Käsittelijä" }, "&noHandler": { "default": "Ei käsittelijää" } }, "search": { "state": { "&title": { "default": "Hae:" }, "&APPROVED": { "default": "Hyväksyttyjä" }, "&DRAFT": { "default": "Luonnoksia" }, "&REMOVED": { "default": "Poistettuja" } }, "result": { "&title": { "default": "Hakutulos" }, "&amount": { "default": "Hakutuloksia: {length}" }, "state": { "&title": { "default": "Tila" }, "&APPROVED": { "default": "Hyväksytty" }, "&DRAFT": { "default": "Luonnos" }, "&REMOVED": { "default": "Poistettu" } } } }, "settings": { "&title": { "default": "Asetukset" }, "upload": { "dataConfiguration": { "&title": { "default": "Datan konfiguraatio" }, "&upload": { "default": "Lataa datan konfiguraatio" } }, "guiConfiguration": { "&title": { "default": "GUI konfiguraatio" }, "&upload": { "default": "Lataa GUI konfiguraatio" } }, "miscJson": { "&title": { "default": "Json tiedosto" }, "&upload": { "default": "Lataa Json tiedosto" } } } }, "dialog": { "waitDialog": { "title": "Toimintoa suoritetaan..." } }, "alert": { "notice": { "&title": { "default": "Huomio" }, "approve": { "success": "Luonnos hyväksytty onnistuneesti." }, "save": { "success": "Luonnos tallennettu onnistuneesti." } }, "error": { "&title": { "default": "Virhe" }, "approve": { "fail": { "save": "Luonnoksen hyväksymisessä tapahtui virhe tallennuksen aikana.", "validate": "Luonnoksen hyväksymisessä tapahtui virhe datan validoinnin aikana." } }, "save": { "fail": "Luonnoksen tallentamisessa tapahtui virhe." } }, "gui": { "missingButtonHandler": { "&text": { "default": 'Ei käsittelijää painikkeelle [{0}] otsikolla "{1}"' } } } }, "confirmation": { "&title": { "default": "Varmistus" }, "remove": { "revision": { "&title": { "default": "Revision poiston varmistus" }, "draft": { "&text": { "default": "Haluatko varmasti poistaa {target} id:llä {id} luonnoksen {no}?" }, "data": { "&SERIES": { "default": "sarjalta" }, "&STUDY": { "default": "aineistolta" }, "&STUDY_VARIABLES": { "default": "aineistomuuttujilta" }, "&STUDY_VARIABLE": { "default": "muuttujalta" }, "&STUDY_ATTACHMENT": { "default": "aineistoliitteistä" }, "&PUBLICATION": { "default": "julkaisulta" }, "&BINDER_PAGE": { "default": "mapitukselta" } } }, "logical": { "&text": { "default": "Haluatko varmasti poistaa {target} id:llä {id}?" }, "data": { "&SERIES": { "default": "sarjan" }, "&STUDY": { "default": "aineiston" }, "&STUDY_ATTACHMENT": { "default": "aineistoliitteen" }, "&PUBLICATION": { "default": "julkaisun" }, "&BINDER_PAGE": { "default": "mapituksen" } } } } } } }); });
henrisu/metka
metka/src/main/webapp/resources/js/modules/uiLocalization.js
JavaScript
bsd-3-clause
17,066
var $ = require('jquery'); var CoreView = require('backbone/core-view'); var checkAndBuildOpts = require('builder/helpers/required-opts'); var REQUIRED_OPTS = [ 'el' ]; module.exports = CoreView.extend({ events: { 'click .js-foo': '_fooHandler' }, initialize: function (opts) { checkAndBuildOpts(opts, REQUIRED_OPTS, this); this._onWindowScroll = this._onWindowScroll.bind(this); this._topBoundary = this.$el.offset().top; this._initBinds(); }, _initBinds: function () { this._bindScroll(); }, _onWindowScroll: function () { this.$el.toggleClass('is-fixed', $(window).scrollTop() > this._topBoundary); }, _unbindScroll: function () { $(window).unbind('scroll', this._onWindowScroll); }, _bindScroll: function () { this._unbindScroll(); $(window).bind('scroll', this._onWindowScroll); }, clean: function () { this._unbindScroll(); } });
CartoDB/cartodb
lib/assets/javascripts/dashboard/helpers/scroll-tofixed-view.js
JavaScript
bsd-3-clause
920
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. (function() { "use strict"; var runFunc; var count = 0; function getId() { return "code" + (count++); } function text(node) { var s = ""; for (var i = 0; i < node.childNodes.length; i++) { var n = node.childNodes[i]; if (n.nodeType === 1 && n.tagName === "SPAN" && n.className != "number") { var innerText = n.innerText === undefined ? "textContent" : "innerText"; s += n[innerText] + "\n"; continue; } if (n.nodeType === 1 && n.tagName !== "BUTTON") { s += text(n); } } return s; } function init(code) { var id = getId(); var output = document.createElement('div'); var outpre = document.createElement('pre'); var stopFunc; function onKill() { if (stopFunc) { stopFunc(); } } function onRun(e) { onKill(); outpre.innerHTML = ""; output.style.display = "block"; run.style.display = "none"; var options = {Race: e.shiftKey}; stopFunc = runFunc(text(code), outpre, options); } function onClose() { onKill(); output.style.display = "none"; run.style.display = "inline-block"; } var run = document.createElement('button'); run.innerHTML = 'Run'; run.className = 'run'; run.addEventListener("click", onRun, false); var run2 = document.createElement('button'); run2.className = 'run'; run2.innerHTML = 'Run'; run2.addEventListener("click", onRun, false); var kill = document.createElement('button'); kill.className = 'kill'; kill.innerHTML = 'Kill'; kill.addEventListener("click", onKill, false); var close = document.createElement('button'); close.className = 'close'; close.innerHTML = 'Close'; close.addEventListener("click", onClose, false); var button = document.createElement('div'); button.classList.add('buttons'); button.appendChild(run); // Hack to simulate insertAfter code.parentNode.insertBefore(button, code.nextSibling); var buttons = document.createElement('div'); buttons.classList.add('buttons'); buttons.appendChild(run2); buttons.appendChild(kill); buttons.appendChild(close); output.classList.add('output'); output.appendChild(buttons); output.appendChild(outpre); output.style.display = "none"; code.parentNode.insertBefore(output, button.nextSibling); } var play = document.querySelectorAll('div.playground'); for (var i = 0; i < play.length; i++) { init(play[i]); } if (play.length > 0) { if (window.connectPlayground) { runFunc = window.connectPlayground("ws://" + window.location.host + "/socket"); } else { // If this message is logged, // we have neglected to include socket.js or playground.js. console.log("No playground transport available."); } } })();
bketelsen/gablog
static/play/play.js
JavaScript
bsd-3-clause
3,040
var PgQuery = require('bindings')('pg-query'); module.exports = { parse: function(query) { var result = PgQuery.parse(query); if (result.query) { result.query = JSON.parse(result.query); } if (result.error) { var err = new Error(result.error.message); err.fileName = result.error.fileName; err.lineNumber = result.error.lineNumber; err.cursorPosition = result.error.cursorPosition; err.functionName = result.error.functionName; err.context = result.error.context; result.error = err; } return result; } };
zhm/node-pg-query-native
index.js
JavaScript
bsd-3-clause
588
// Replacement for jquery.ui.accordion to avoid dealing with // jquery.ui theming. // // Usage: $('#container').squeezebox(options); // where the direct child elements of '#container' are // sequential pairs of header/panel elements, and options // is an optional object with any of the following properties: // // activeHeaderClass: Class name to apply to the active header // headerSelector: Selector for the header elements // nextPanelSelector: Selector for the next panel from a header // speed: Animation speed (function($) { $.fn.squeezebox = function(options) { // Default options. options = $.extend({ activeHeaderClass: 'squeezebox-header-on', headerSelector: '> *:even', nextPanelSelector: ':first', speed: 500 }, options); var headers = this.find(options.headerSelector); // When a header is clicked, iterate through each of the // headers, getting their corresponding panels, and opening // the panel for the header that was clicked (slideDown), // closing the others (slideUp). headers.click(function() { var clicked = this; $.each(headers, function(i, header) { var panel = $(header).next(options.nextPanelSelector); if (clicked == header) { panel.slideDown(options.speed); $(header).addClass(options.activeHeaderClass); } else { panel.slideUp(options.speed); $(header).removeClass(options.activeHeaderClass); } }); }); }; })(jQuery);
stephenmcd/jquery-squeezebox
jquery.squeezebox.js
JavaScript
bsd-3-clause
1,697
define(function () { return [ { "default": { name: 'form1', label: 'Form 1', "_elements": [ { "default": { "name": "id", "type": "hidden" } }, { "default": { "name": "test1", "type": "text", "label": "Test1", "defaultValue": "test1", "page": 0 } }, { "default": { "name": "test2", "type": "text", "label": "Test2", "defaultValue": "test2", "page": 0 } }, { "default": { "name": "calc_button", "type": "button", "label": "Calculate", "persist": false, "page": 0 } }, { "default": { "name": "calc", "type": "message", "label": "Calc", "labelPlacement": "default", "labelStyle": "Plain", "showTextbox": "show", "calculationType": "manual", "buttonText": "Calculate", "persist": true, "page": 0 } } ], "_checks": [ ], "_actions": [ { "default": { "javascript": "\"[test1]\"+\"[test2]\"", "outputTarget": "calc", "name": "CALC_calc" } } ], "_behaviours": [ { "default": { "name": "auto_calculations", "trigger": { "formElements": ["calc_button"] }, "actions": [ "CALC_calc" ] } } ] } } ]; });
blinkmobile/forms
test/18_calculation/definitions.js
JavaScript
bsd-3-clause
1,923
////functionen hämtar alla artiklar med hjälp av getJSON //och får tillbaka en array med alla artiklar //efter den är klar kallar den på functionen ShoArtTab. //som skriver ut alla artiklar i en tabell. function getAllAdminProducts() { $.getJSON("index2.php/getAllProducts").done(showArtTab); } //functionen showArtTab får en array av getAllArticle funktionen //som den loopar igenom och anväder för att skapa upp en tabell med alla de olika //artiklarna function showArtTab(cart){ var mainTabell = document.createElement('div'); mainTabell.setAttribute('id', 'mainTabell'); var tbl = document.createElement('table'); tbl.setAttribute('border', '1'); var tr = document.createElement('tr'); var th2 = document.createElement('th'); var txt2 = document.createTextNode('Produktid'); var th3 = document.createElement('th'); var txt3 = document.createTextNode('Produktnamn'); var th4 = document.createElement('th'); var txt4 = document.createTextNode('Kategori'); var th5 = document.createElement('th'); var txt5 = document.createTextNode('Pris'); var th6 = document.createElement('th'); var txt6 = document.createTextNode('Bild'); var th7 = document.createElement('th'); var txt7 = document.createTextNode('Delete'); var th8 = document.createElement('th'); var txt8 = document.createTextNode('Update'); th2.appendChild(txt2); tr.appendChild(th2); th3.appendChild(txt3); tr.appendChild(th3); th4.appendChild(txt4); tr.appendChild(th4); th5.appendChild(txt5); tr.appendChild(th5); th6.appendChild(txt6); tr.appendChild(th6); th7.appendChild(txt7); tr.appendChild(th7); th8.appendChild(txt8); tr.appendChild(th8); tbl.appendChild(tr); var i = 0; do{ var row = tbl.insertRow(-1); row.insertCell(-1).innerHTML = cart[i].produktid; var cell2 = row.insertCell(-1); cell2.innerHTML = cart[i].namn; var cell3 = row.insertCell(-1); cell3.innerHTML = cart[i].kategori; var cell4 = row.insertCell(-1); cell4.innerHTML = cart[i].pris; var cell6 = row.insertCell(-1); cell6.innerHTML = '<img src="' + cart[i].img + '" height="70" width="70"/>'; var cell7 = row.insertCell(-1); cell7.innerHTML = "<a href='#' onclick='removeArt(\"" +cart[i].produktid+ "\",\""+ "\");'>Remove</a>"; var cell8 = row.insertCell(-1); cell8.innerHTML = "<a href='#' onclick='getUpdate(\"" +cart[i].produktid+ "\",\""+ "\");'>Update</a>"; tbl.appendChild(row); i++; }while(i< cart.length); $('#main').html(tbl); } //öppnar en dialogruta när man trycker på "Add Article" knappen //med det som finns i diven med id:addArt function showAddArt(){ $('#addArt').dialog({ show:'fade', position:'center' }); } //när man trycker på "Add Article" knappen i dialogrutan så ska den lägga till datan //från formuläret som görs med .serialize som hämtar datan från textfälten. function addArticle(){ $.post('index2.php/AdminController/addProduct',$('#addArtForm').serialize()).done(getAllAdminProducts); $("#addArt").dialog('close'); } //tar bort en artikel med att hämta in dess namn och skicka förfrågningen till modellen function deleteArt(prodid) { $.getJSON("index2.php/AdminController/deleteProduct/"+prodid); } function removeArt(prodid){ var r=confirm("Vill du ta bort den här produkten?"); if (r==true) { x="JA"; } else { x="NEJ"; } if(x === "JA"){ deleteArt(prodid); getAllAdminProducts(); } } //en function som tar in namnet //och använder det när man kallar på getArt function getUpdate(prodid){ getArt(prodid); } //får in artikelid och använder det för att hämta alla artiklar som har samma //id med hjälp av modellen. function getArt(prodid){ $.getJSON("index2.php/Controller/getProdById/"+prodid).done(showArt); } //en function som visar en dialog ruta med färdig i fylld data i textfällten //från den uppgift man vill uppdatera. function showArt(data){ $('#updateId').attr('value',data[0].produktid); $('#updateNamn').attr('value',data[0].namn); $('#updateKategori').attr('value',data[0].kategori); $('#updatePris').attr('value',data[0].pris); $('#updateImg').attr('value',data[0].img); $('#update').dialog({ show:'fade', position:'center', }); } //när man trycker på uppdatera så hämtar den datan från forumlätert med hjälp av // .serialize och skickar datan till modellen. //stänger sen dialogrutan. function updateArt(){ $.post("index2.php/AdminController/updateProduct/", $('#updateForm').serialize()).done(getAllAdminProducts); $("#update").dialog('close'); }
cider94/JsKlar
start/admin.js
JavaScript
bsd-3-clause
4,847
/** * Copyright (c) 2015, Legendum Ltd. 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 ntil 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. */ /** * ntil - create a handler to call a function until the result is good. * * This package provides a single method "ntil()" which is called thus: * * ntil(performer, success, failure, opts) * * checker - a function to check a result and return true or false * performer - a function to call to perform a task which may succeed or fail * success - an optional function to process the result of a successful call * failure - an optional function to process the result of a failed call * opts - an optional hash of options (see below) * * ntil() will return a handler that may be called with any number of arguments. * The performer function will receive these arguments, with a final "next" arg * appended to the argument list, such that it should be called on completion, * passing the result (as a single argument *or* multiple arguments) thus: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * var ntil = require('ntil'); * var handler = ntil( * function(result) { return result === 3 }, // the checker * function myFunc(a, b, next) { next(a + b) }, // the performer * function(result) { console.log('success! ' + result) }, // on success * function(result) { console.log('failure! ' + result) }, // on failure * {logger: console} // options * ); * * handler(1, 1); // this will fail after 7 attempts (taking about a minute) * handler(1, 2); // this will succeed immediately * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * ...and here's the equivalent code in a syntax more similar to promises: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * var ntil = require('./ntil'); * var handler = ntil( * function(result) { return result === 3 } * ).exec( * function myFunc(a, b, next) { next(a + b) } * ).done( * function(result) { console.log('success! ' + result) } * ).fail( * function(result) { console.log('failure! ' + result) } * }.opts( * {logger: console} * ).func(); * * handler(1, 1); // this will fail after 7 attempts (taking about a minute) * handler(1, 2); // this will succeed immediately * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * Note that the logger includes "myFunc" in log messages, because the function * is named. An alternative is to use the "name" option (see below). * * The "checker" function checks that the result is 3, causing the first handler * to fail (it has a result of 2, not 3) and the second handler to succeed. * * The output from both these examples is: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * perform: 1 failure - trying again in 1 seconds * perform: success * success! 3 * perform: 2 failures - trying again in 2 seconds * perform: 3 failures - trying again in 4 seconds * perform: 4 failures - trying again in 8 seconds * perform: 5 failures - trying again in 16 seconds * perform: 6 failures - trying again in 32 seconds * perform: too many failures (7) * failure! 2 * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * * The options may optionally include: * name: The name of the "performer" function we're calling, e.g. "getData" * logger: A logger object that responds to "info" and "warn" method calls * waitSecs: The initial duration in seconds to wait before retrying * waitMult: The factor by which to multiply the wait duration upon each retry * maxCalls: The maximum number of calls to make before failing * * Note that "waitSecs" defaults to 1, "waitMult" defaults to 2, and "maxCalls" * defaults to 7. * * Ideas for improvement? Email [email protected] */ (function() { "use strict"; var sig = "Check params: function ntil(checker, performer, success, failure, opts)"; function chain(checker, opts) { this.opts = function(options) { opts = options; return this } this.exec = function(perform) { this.perform = perform; return this }; this.done = function(success) { this.success = success; return this }; this.fail = function(failure) { this.failure = failure; return this }; this.func = function() { return ntil(checker, this.perform, this.success, this.failure, opts); }; } function ntil(checker, performer, success, failure, opts) { opts = opts || {}; if (typeof checker !== 'function') throw sig; if (typeof performer !== 'function') return new chain(checker, performer); var name = opts.name || performer.name || 'anonymous function', logger = opts.logger, waitSecs = opts.waitSecs || 1, waitMult = opts.waitMult || 2, maxCalls = opts.maxCalls || 7; // it takes about a minute for 7 attempts return function() { var args = Array.prototype.slice.call(arguments, 0), wait = waitSecs, calls = 0; function next() { var result = Array.prototype.slice.call(arguments, 0); if (checker.apply(checker, result) === true) { if (logger) logger.info(name + ': success'); if (typeof success === 'function') success.apply(success, result); } else { calls++; if (calls < maxCalls) { if (logger) logger.warn(name + ': ' + calls + ' failure' + (calls === 1 ? '' : 's') + ' - trying again in ' + wait + ' seconds'); setTimeout(function() { invoke(); }, wait * 1000); wait *= waitMult; } else { if (logger) logger.warn(name + ': too many failures (' + calls + ')'); if (typeof failure === 'function') failure.apply(failure, result); } } } function invoke() { try { performer.apply(performer, args); } catch (e) { if (logger) logger.warn(name + ': exception "' + e + '"'); next(); } } args.push(next); invoke(); } } if (typeof module !== 'undefined' && module.exports) { module.exports = ntil; } else { // browser? this.ntil = ntil; } }).call(this);
legendum/ntil
ntil.js
JavaScript
bsd-3-clause
7,810
/** * History.js Core * @author Benjamin Arthur Lupton <[email protected]> * @copyright 2010-2011 Benjamin Arthur Lupton <[email protected]> * @license New BSD License <http://creativecommons.org/licenses/BSD/> */ (function(window,undefined){ "use strict"; // ======================================================================== // Initialise // Localise Globals var console = window.console||undefined, // Prevent a JSLint complain document = window.document, // Make sure we are using the correct document navigator = window.navigator, // Make sure we are using the correct navigator sessionStorage = false, // sessionStorage setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, setInterval = window.setInterval, clearInterval = window.clearInterval, JSON = window.JSON, alert = window.alert, History = window.History = window.History||{}, // Public History Object history = window.history; // Old History Object // MooTools Compatibility JSON.stringify = JSON.stringify||JSON.encode; JSON.parse = JSON.parse||JSON.decode; try { sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome) sessionStorage.setItem('TEST', '1'); sessionStorage.removeItem('TEST'); } catch(e) { sessionStorage = false; } // Check Existence if ( typeof History.init !== 'undefined' ) { throw new Error('History.js Core has already been loaded...'); } // Initialise History History.init = function(){ // Check Load Status of Adapter if ( typeof History.Adapter === 'undefined' ) { return false; } // Check Load Status of Core if ( typeof History.initCore !== 'undefined' ) { History.initCore(); } // Check Load Status of HTML4 Support if ( typeof History.initHtml4 !== 'undefined' ) { History.initHtml4(); } // Return true return true; }; // ======================================================================== // Initialise Core // Initialise Core History.initCore = function(){ // Initialise if ( typeof History.initCore.initialized !== 'undefined' ) { // Already Loaded return false; } else { History.initCore.initialized = true; } // ==================================================================== // Options /** * History.options * Configurable options */ History.options = History.options||{}; /** * History.options.hashChangeInterval * How long should the interval be before hashchange checks */ History.options.hashChangeInterval = History.options.hashChangeInterval || 100; /** * History.options.safariPollInterval * How long should the interval be before safari poll checks */ History.options.safariPollInterval = History.options.safariPollInterval || 500; /** * History.options.doubleCheckInterval * How long should the interval be before we perform a double check */ History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500; /** * History.options.storeInterval * How long should we wait between store calls */ History.options.storeInterval = History.options.storeInterval || 5000; /** * History.options.busyDelay * How long should we wait between busy events */ History.options.busyDelay = History.options.busyDelay || 250; /** * History.options.debug * If true will enable debug messages to be logged */ History.options.debug = History.options.debug || false; /** * History.options.initialTitle * What is the title of the initial state */ History.options.initialTitle = History.options.initialTitle || document.title; // ==================================================================== // Interval record /** * History.intervalList * List of intervals set, to be cleared when document is unloaded. */ History.intervalList = []; /** * History.clearAllIntervals * Clears all setInterval instances. */ History.clearAllIntervals = function(){ var i, il = History.intervalList; if (typeof il !== "undefined" && il !== null) { for (i = 0; i < il.length; i++) { clearInterval(il[i]); } History.intervalList = null; } }; // ==================================================================== // Debug /** * History.debug(message,...) * Logs the passed arguments if debug enabled */ History.debug = function(){ if ( (History.options.debug||false) ) { History.log.apply(History,arguments); } }; /** * History.log(message,...) * Logs the passed arguments */ History.log = function(){ // Prepare var consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'), textarea = document.getElementById('log'), message, i,n, args,arg ; // Write to Console if ( consoleExists ) { args = Array.prototype.slice.call(arguments); message = args.shift(); if ( typeof console.debug !== 'undefined' ) { console.debug.apply(console,[message,args]); } else { console.log.apply(console,[message,args]); } } else { message = ("\n"+arguments[0]+"\n"); } // Write to log for ( i=1,n=arguments.length; i<n; ++i ) { arg = arguments[i]; if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) { try { arg = JSON.stringify(arg); } catch ( Exception ) { // Recursive Object } } message += "\n"+arg+"\n"; } // Textarea if ( textarea ) { textarea.value += message+"\n-----\n"; textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight; } // No Textarea, No Console else if ( !consoleExists ) { alert(message); } // Return true return true; }; // ==================================================================== // Emulated Status /** * History.getInternetExplorerMajorVersion() * Get's the major version of Internet Explorer * @return {integer} * @license Public Domain * @author Benjamin Arthur Lupton <[email protected]> * @author James Padolsey <https://gist.github.com/527683> */ History.getInternetExplorerMajorVersion = function(){ var result = History.getInternetExplorerMajorVersion.cached = (typeof History.getInternetExplorerMajorVersion.cached !== 'undefined') ? History.getInternetExplorerMajorVersion.cached : (function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {} return (v > 4) ? v : false; })() ; return result; }; /** * History.isInternetExplorer() * Are we using Internet Explorer? * @return {boolean} * @license Public Domain * @author Benjamin Arthur Lupton <[email protected]> */ History.isInternetExplorer = function(){ var result = History.isInternetExplorer.cached = (typeof History.isInternetExplorer.cached !== 'undefined') ? History.isInternetExplorer.cached : Boolean(History.getInternetExplorerMajorVersion()) ; return result; }; /** * History.emulated * Which features require emulating? */ History.emulated = { pushState: !Boolean( window.history && window.history.pushState && window.history.replaceState && !( (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */ || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */ ) ), hashChange: Boolean( !(('onhashchange' in window) || ('onhashchange' in document)) || (History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8) ) }; /** * History.enabled * Is History enabled? */ History.enabled = !History.emulated.pushState; /** * History.bugs * Which bugs are present */ History.bugs = { /** * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call * https://bugs.webkit.org/show_bug.cgi?id=56249 */ setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)), /** * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions * https://bugs.webkit.org/show_bug.cgi?id=42940 */ safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)), /** * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function) */ ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8), /** * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event */ hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7) }; /** * History.isEmptyObject(obj) * Checks to see if the Object is Empty * @param {Object} obj * @return {boolean} */ History.isEmptyObject = function(obj) { for ( var name in obj ) { return false; } return true; }; /** * History.cloneObject(obj) * Clones a object and eliminate all references to the original contexts * @param {Object} obj * @return {Object} */ History.cloneObject = function(obj) { var hash,newObj; if ( obj ) { hash = JSON.stringify(obj); newObj = JSON.parse(hash); } else { newObj = {}; } return newObj; }; History.extendObject = function(obj, extension) { for (var key in extension) { if (extension.hasOwnProperty(key)) { obj[key] = extension[key]; } } }; History.setSessionStorageItem = function(key, value) { try { sessionStorage.setItem(key, value); } catch(e) { try { // hack: Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply // removing/resetting the storage can work. sessionStorage.removeItem(key); sessionStorage.setItem(key, value); } catch(e) { try { // no permissions or quota exceed if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { History.Adapter.trigger(window, 'storageQuotaExceed'); sessionStorage.setItem(key, value); } } catch(e) { } } } } // ==================================================================== // URL Helpers /** * History.getRootUrl() * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com" * @return {String} rootUrl */ History.getRootUrl = function(){ // Create var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host); if ( document.location.port||false ) { rootUrl += ':'+document.location.port; } rootUrl += '/'; // Return return rootUrl; }; /** * History.getBaseHref() * Fetches the `href` attribute of the `<base href="...">` element if it exists * @return {String} baseHref */ History.getBaseHref = function(){ // Create var baseElements = document.getElementsByTagName('base'), baseElement = null, baseHref = ''; // Test for Base Element if ( baseElements.length === 1 ) { // Prepare for Base Element baseElement = baseElements[0]; baseHref = baseElement.href.replace(/[^\/]+$/,''); } // Adjust trailing slash baseHref = baseHref.replace(/\/+$/,''); if ( baseHref ) baseHref += '/'; // Return return baseHref; }; /** * History.getBaseUrl() * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first) * @return {String} baseUrl */ History.getBaseUrl = function(){ // Create var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl(); // Return return baseUrl; }; /** * History.getPageUrl() * Fetches the URL of the current page * @return {String} pageUrl */ History.getPageUrl = function(){ // Fetch var State = History.getState(false,false), stateUrl = (State||{}).url||document.location.href, pageUrl; // Create pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){ return (/\./).test(part) ? part : part+'/'; }); // Return return pageUrl; }; /** * History.getBasePageUrl() * Fetches the Url of the directory of the current page * @return {String} basePageUrl */ History.getBasePageUrl = function(){ // Create var basePageUrl = document.location.href.replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){ return (/[^\/]$/).test(part) ? '' : part; }).replace(/\/+$/,'')+'/'; // Return return basePageUrl; }; /** * History.getFullUrl(url) * Ensures that we have an absolute URL and not a relative URL * @param {string} url * @param {Boolean} allowBaseHref * @return {string} fullUrl */ History.getFullUrl = function(url,allowBaseHref){ // Prepare var fullUrl = url, firstChar = url.substring(0,1); allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref; // Check if ( /[a-z]+\:\/\//.test(url) ) { // Full URL } else if ( firstChar === '/' ) { // Root URL fullUrl = History.getRootUrl()+url.replace(/^\/+/,''); } else if ( firstChar === '#' ) { // Anchor URL fullUrl = History.getPageUrl().replace(/#.*/,'')+url; } else if ( firstChar === '?' ) { // Query URL fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url; } else { // Relative URL if ( allowBaseHref ) { fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,''); } else { fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,''); } // We have an if condition above as we do not want hashes // which are relative to the baseHref in our URLs // as if the baseHref changes, then all our bookmarks // would now point to different locations // whereas the basePageUrl will always stay the same } // Return return fullUrl.replace(/\#$/,''); }; /** * History.getShortUrl(url) * Ensures that we have a relative URL and not a absolute URL * @param {string} url * @return {string} url */ History.getShortUrl = function(url){ // Prepare var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl(); // Trim baseUrl if ( History.emulated.pushState ) { // We are in a if statement as when pushState is not emulated // The actual url these short urls are relative to can change // So within the same session, we the url may end up somewhere different shortUrl = shortUrl.replace(baseUrl,''); } // Trim rootUrl shortUrl = shortUrl.replace(rootUrl,'/'); // Ensure we can still detect it as a state if ( History.isTraditionalAnchor(shortUrl) ) { shortUrl = './'+shortUrl; } // Clean It shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,''); // Return return shortUrl; }; // ==================================================================== // State Storage /** * History.store * The store for all session specific data */ History.store = {}; /** * History.idToState * 1-1: State ID to State Object */ History.idToState = History.idToState||{}; /** * History.stateToId * 1-1: State String to State ID */ History.stateToId = History.stateToId||{}; /** * History.urlToId * 1-1: State URL to State ID */ History.urlToId = History.urlToId||{}; /** * History.storedStates * Store the states in an array */ History.storedStates = History.storedStates||[]; /** * History.savedStates * Saved the states in an array */ History.savedStates = History.savedStates||[]; /** * History.noramlizeStore() * Noramlize the store by adding necessary values */ History.normalizeStore = function(){ History.store.idToState = History.store.idToState||{}; History.store.urlToId = History.store.urlToId||{}; History.store.stateToId = History.store.stateToId||{}; }; /** * History.getState() * Get an object containing the data, title and url of the current state * @param {Boolean} friendly * @param {Boolean} create * @return {Object} State */ History.getState = function(friendly,create){ // Prepare if ( typeof friendly === 'undefined' ) { friendly = true; } if ( typeof create === 'undefined' ) { create = true; } // Fetch var State = History.getLastSavedState(); // Create if ( !State && create ) { State = History.createStateObject(); } // Adjust if ( friendly ) { State = History.cloneObject(State); State.url = State.cleanUrl||State.url; } // Return return State; }; /** * History.getIdByState(State) * Gets a ID for a State * @param {State} newState * @return {String} id */ History.getIdByState = function(newState){ // Fetch ID var id = History.extractId(newState.url), lastSavedState, str; if ( !id ) { // Find ID via State String str = History.getStateString(newState); if ( typeof History.stateToId[str] !== 'undefined' ) { id = History.stateToId[str]; } else if ( typeof History.store.stateToId[str] !== 'undefined' ) { id = History.store.stateToId[str]; } else { id = sessionStorage ? sessionStorage.getItem('uniqId') : new Date().getTime(); if (id == undefined){ id = 0; } lastSavedState = History.getLastSavedState(); if (lastSavedState) { id = lastSavedState.id + 1; if (sessionStorage) { History.setSessionStorageItem('uniqId', id); } } else { // Generate a new ID while (true) { ++id; if (typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined') { if (sessionStorage) { History.setSessionStorageItem('uniqId', id); } break; } } } // Apply the new State to the ID History.stateToId[str] = id; History.idToState[id] = newState; } } // Return ID return id; }; /** * History.normalizeState(State) * Expands a State Object * @param {object} State * @return {object} */ History.normalizeState = function(oldState){ // Variables var newState, dataNotEmpty; // Prepare if ( !oldState || (typeof oldState !== 'object') ) { oldState = {}; } // Check if ( typeof oldState.normalized !== 'undefined' ) { return oldState; } // Adjust if ( !oldState.data || (typeof oldState.data !== 'object') ) { oldState.data = {}; } // ---------------------------------------------------------------- // Create newState = {}; newState.normalized = true; newState.title = oldState.title||''; newState.url = History.getFullUrl(History.unescapeString(oldState.url||document.location.href)); newState.hash = History.getShortUrl(newState.url); newState.data = History.cloneObject(oldState.data); // Fetch ID newState.id = History.getIdByState(newState); // ---------------------------------------------------------------- // Clean the URL newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,''); newState.url = newState.cleanUrl; // Check to see if we have more than just a url dataNotEmpty = !History.isEmptyObject(newState.data); // Apply if ( newState.title || dataNotEmpty ) { // Add ID to Hash newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,''); if ( !/\?/.test(newState.hash) ) { newState.hash += '?'; } newState.hash += '&_suid='+newState.id; } // Create the Hashed URL newState.hashedUrl = History.getFullUrl(newState.hash); // ---------------------------------------------------------------- // Update the URL if we have a duplicate if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) { newState.url = newState.hashedUrl; } // ---------------------------------------------------------------- // Return return newState; }; /** * History.createStateObject(data,title,url) * Creates a object based on the data, title and url state params * @param {object} data * @param {string} title * @param {string} url * @return {object} */ History.createStateObject = function(data,title,url){ // Hashify var State = { 'data': data, 'title': title, 'url': url }; // Expand the State State = History.normalizeState(State); // Return object return State; }; /** * History.getStateById(id) * Get a state by it's UID * @param {String} id */ History.getStateById = function(id){ // Prepare id = String(id); // Retrieve var State = History.idToState[id] || History.store.idToState[id] || undefined; // Return State return State; }; /** * Get a State's String * @param {State} passedState */ History.getStateString = function(passedState){ // Prepare var State, cleanedState, str; // Fetch State = History.normalizeState(passedState); // Clean cleanedState = { data: State.data, title: passedState.title, url: passedState.url }; // Fetch str = JSON.stringify(cleanedState); // Return return str; }; /** * Get a State's ID * @param {State} passedState * @return {String} id */ History.getStateId = function(passedState){ // Prepare var State, id; // Fetch State = History.normalizeState(passedState); // Fetch id = State.id; // Return return id; }; /** * History.getHashByState(State) * Creates a Hash for the State Object * @param {State} passedState * @return {String} hash */ History.getHashByState = function(passedState){ // Prepare var State, hash; // Fetch State = History.normalizeState(passedState); // Hash hash = State.hash; // Return return hash; }; /** * History.extractId(url_or_hash) * Get a State ID by it's URL or Hash * @param {string} url_or_hash * @return {string} id */ History.extractId = function ( url_or_hash ) { // Prepare var id,parts,url; // Extract parts = /(.*)\&_suid=([0-9]+)$/.exec(url_or_hash); url = parts ? (parts[1]||url_or_hash) : url_or_hash; id = parts ? String(parts[2]||'') : ''; // Return return id||false; }; /** * History.isTraditionalAnchor * Checks to see if the url is a traditional anchor or not * @param {String} url_or_hash * @return {Boolean} */ History.isTraditionalAnchor = function(url_or_hash){ // Check var isTraditional = !(/[\/\?\.]/.test(url_or_hash)); // Return return isTraditional; }; /** * History.extractState * Get a State by it's URL or Hash * @param {String} url_or_hash * @return {State|null} */ History.extractState = function(url_or_hash,create){ // Prepare var State = null, id, url; create = create||false; // Fetch SUID id = History.extractId(url_or_hash); if ( id ) { State = History.getStateById(id); } // Fetch SUID returned no State if ( !State ) { // Fetch URL url = History.getFullUrl(url_or_hash); // Check URL id = History.getIdByUrl(url)||false; if ( id ) { State = History.getStateById(id); } // Create State if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) { State = History.createStateObject(null,null,url); } } // Return return State; }; /** * History.getIdByUrl() * Get a State ID by a State URL */ History.getIdByUrl = function(url){ // Fetch var id = History.urlToId[url] || History.store.urlToId[url] || undefined; // Return return id; }; /** * History.getLastSavedState() * Get an object containing the data, title and url of the current state * @return {Object} State */ History.getLastSavedState = function(){ return History.savedStates[History.savedStates.length-1]||undefined; }; /** * History.getLastStoredState() * Get an object containing the data, title and url of the current state * @return {Object} State */ History.getLastStoredState = function(){ return History.storedStates[History.storedStates.length-1]||undefined; }; /** * History.hasUrlDuplicate * Checks if a Url will have a url conflict * @param {Object} newState * @return {Boolean} hasDuplicate */ History.hasUrlDuplicate = function(newState) { // Prepare var hasDuplicate = false, oldState; // Fetch oldState = History.extractState(newState.url); // Check hasDuplicate = oldState && oldState.id !== newState.id; // Return return hasDuplicate; }; /** * History.storeState * Store a State * @param {Object} newState * @return {Object} newState */ History.storeState = function(newState){ // Store the State History.urlToId[newState.url] = newState.id; // Push the State History.storedStates.push(History.cloneObject(newState)); // Return newState return newState; }; /** * History.isLastSavedState(newState) * Tests to see if the state is the last state * @param {Object} newState * @return {boolean} isLast */ History.isLastSavedState = function(newState){ // Prepare var isLast = false, newId, oldState, oldId; // Check if ( History.savedStates.length ) { newId = newState.id; oldState = History.getLastSavedState(); oldId = oldState.id; // Check isLast = (newId === oldId); } // Return return isLast; }; /** * History.saveState * Push a State * @param {Object} newState * @return {boolean} changed */ History.saveState = function(newState){ // Check Hash if ( History.isLastSavedState(newState) ) { return false; } // Push the State History.savedStates.push(History.cloneObject(newState)); // Return true return true; }; /** * History.getStateByIndex() * Gets a state by the index * @param {integer} index * @return {Object} */ History.getStateByIndex = function(index){ // Prepare var State = null; // Handle if ( typeof index === 'undefined' ) { // Get the last inserted State = History.savedStates[History.savedStates.length-1]; } else if ( index < 0 ) { // Get from the end State = History.savedStates[History.savedStates.length+index]; } else { // Get from the beginning State = History.savedStates[index]; } // Return State return State; }; // ==================================================================== // Hash Helpers /** * History.getHash() * Gets the current document hash * @return {string} */ History.getHash = function(){ var hash = History.unescapeHash(document.location.hash); return hash; }; /** * History.unescapeString() * Unescape a string * @param {String} str * @return {string} */ History.unescapeString = function(str){ // Prepare var result = str, tmp; // Unescape hash while ( true ) { tmp = window.unescape(result); if ( tmp === result ) { break; } result = tmp; } // Return result return result; }; /** * History.unescapeHash() * normalize and Unescape a Hash * @param {String} hash * @return {string} */ History.unescapeHash = function(hash){ // Prepare var result = History.normalizeHash(hash); // Unescape hash result = History.unescapeString(result); // Return result return result; }; /** * History.normalizeHash() * normalize a hash across browsers * @return {string} */ History.normalizeHash = function(hash){ // Prepare var result = hash.replace(/[^#]*#/,'').replace(/#.*/, ''); // Return result return result; }; /** * History.setHash(hash) * Sets the document hash * @param {string} hash * @return {History} */ History.setHash = function(hash,queue){ // Prepare var adjustedHash, State, pageUrl; // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.setHash: we must wait', arguments); History.pushQueue({ scope: History, callback: History.setHash, args: arguments, queue: queue }); return false; } // Log //History.debug('History.setHash: called',hash); // Prepare adjustedHash = History.escapeHash(hash); // Make Busy + Continue History.busy(true); // Check if hash is a state State = History.extractState(hash,true); if ( State && !History.emulated.pushState ) { // Hash is a state so skip the setHash //History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments); // PushState History.pushState(State.data,State.title,State.url,false); } else if ( document.location.hash !== adjustedHash ) { // Hash is a proper hash, so apply it // Handle browser bugs if ( History.bugs.setHash ) { // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249 // Fetch the base page pageUrl = History.getPageUrl(); // Safari hash apply History.pushState(null,null,pageUrl+'#'+adjustedHash,false); } else { // Normal hash apply document.location.hash = adjustedHash; } } // Chain return History; }; /** * History.escape() * normalize and Escape a Hash * @return {string} */ History.escapeHash = function(hash){ // Prepare var result = History.normalizeHash(hash); // Escape hash result = window.escape(result); // IE6 Escape Bug if ( !History.bugs.hashEscape ) { // Restore common parts result = result .replace(/\%21/g,'!') .replace(/\%26/g,'&') .replace(/\%3D/g,'=') .replace(/\%3F/g,'?'); } // Return result return result; }; /** * History.getHashByUrl(url) * Extracts the Hash from a URL * @param {string} url * @return {string} url */ History.getHashByUrl = function(url){ // Extract the hash var hash = String(url) .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2') ; // Unescape hash hash = History.unescapeHash(hash); // Return hash return hash; }; /** * History.setTitle(title) * Applies the title to the document * @param {State} newState * @return {Boolean} */ History.setTitle = function(newState){ // Prepare var title = newState.title, firstState; // Initial if ( !title ) { firstState = History.getStateByIndex(0); if ( firstState && firstState.url === newState.url ) { title = firstState.title||History.options.initialTitle; } } // Apply try { document.getElementsByTagName('title')[0].innerHTML = title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; '); } catch ( Exception ) { } document.title = title; // Chain return History; }; // ==================================================================== // Queueing /** * History.queues * The list of queues to use * First In, First Out */ History.queues = []; /** * History.busy(value) * @param {boolean} value [optional] * @return {boolean} busy */ History.busy = function(value){ // Apply if ( typeof value !== 'undefined' ) { //History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length); History.busy.flag = value; } // Default else if ( typeof History.busy.flag === 'undefined' ) { History.busy.flag = false; } // Queue if ( !History.busy.flag ) { // Execute the next item in the queue clearTimeout(History.busy.timeout); var fireNext = function(){ var i, queue, item; if ( History.busy.flag ) return; for ( i=History.queues.length-1; i >= 0; --i ) { queue = History.queues[i]; if ( queue.length === 0 ) continue; item = queue.shift(); History.fireQueueItem(item); History.busy.timeout = setTimeout(fireNext,History.options.busyDelay); } }; History.busy.timeout = setTimeout(fireNext,History.options.busyDelay); } // Return return History.busy.flag; }; /** * History.busy.flag */ History.busy.flag = false; /** * History.fireQueueItem(item) * Fire a Queue Item * @param {Object} item * @return {Mixed} result */ History.fireQueueItem = function(item){ return item.callback.apply(item.scope||History,item.args||[]); }; /** * History.pushQueue(callback,args) * Add an item to the queue * @param {Object} item [scope,callback,args,queue] */ History.pushQueue = function(item){ // Prepare the queue History.queues[item.queue||0] = History.queues[item.queue||0]||[]; // Add to the queue History.queues[item.queue||0].push(item); // Chain return History; }; /** * History.queue (item,queue), (func,queue), (func), (item) * Either firs the item now if not busy, or adds it to the queue */ History.queue = function(item,queue){ // Prepare if ( typeof item === 'function' ) { item = { callback: item }; } if ( typeof queue !== 'undefined' ) { item.queue = queue; } // Handle if ( History.busy() ) { History.pushQueue(item); } else { History.fireQueueItem(item); } // Chain return History; }; /** * History.clearQueue() * Clears the Queue */ History.clearQueue = function(){ History.busy.flag = false; History.queues = []; return History; }; // ==================================================================== // IE Bug Fix /** * History.stateChanged * States whether or not the state has changed since the last double check was initialised */ History.stateChanged = false; /** * History.doubleChecker * Contains the timeout used for the double checks */ History.doubleChecker = false; /** * History.doubleCheckComplete() * Complete a double check * @return {History} */ History.doubleCheckComplete = function(){ // Update History.stateChanged = true; // Clear History.doubleCheckClear(); // Chain return History; }; /** * History.doubleCheckClear() * Clear a double check * @return {History} */ History.doubleCheckClear = function(){ // Clear if ( History.doubleChecker ) { clearTimeout(History.doubleChecker); History.doubleChecker = false; } // Chain return History; }; /** * History.doubleCheck() * Create a double check * @return {History} */ History.doubleCheck = function(tryAgain){ // Reset History.stateChanged = false; History.doubleCheckClear(); // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does) // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940 if ( History.bugs.ieDoubleCheck ) { // Apply Check History.doubleChecker = setTimeout( function(){ History.doubleCheckClear(); if ( !History.stateChanged ) { //History.debug('History.doubleCheck: State has not yet changed, trying again', arguments); // Re-Attempt tryAgain(); } return true; }, History.options.doubleCheckInterval ); } // Chain return History; }; // ==================================================================== // Safari Bug Fix /** * History.safariStatePoll() * Poll the current state * @return {History} */ History.safariStatePoll = function(){ // Poll the URL // Get the Last State which has the new URL var urlState = History.extractState(document.location.href), newState; // Check for a difference if ( !History.isLastSavedState(urlState) ) { newState = urlState; } else { return; } // Check if we have a state with that url // If not create it if ( !newState ) { //History.debug('History.safariStatePoll: new'); newState = History.createStateObject(); } // Apply the New State //History.debug('History.safariStatePoll: trigger'); History.Adapter.trigger(window,'popstate'); // Chain return History; }; // ==================================================================== // State Aliases /** * History.back(queue) * Send the browser history back one item * @param {Integer} queue [optional] */ History.back = function(queue){ //History.debug('History.back: called', arguments); // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.back: we must wait', arguments); History.pushQueue({ scope: History, callback: History.back, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Fix certain browser bugs that prevent the state from changing History.doubleCheck(function(){ History.back(false); }); // Go back history.go(-1); // End back closure return true; }; /** * History.forward(queue) * Send the browser history forward one item * @param {Integer} queue [optional] */ History.forward = function(queue){ //History.debug('History.forward: called', arguments); // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.forward: we must wait', arguments); History.pushQueue({ scope: History, callback: History.forward, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Fix certain browser bugs that prevent the state from changing History.doubleCheck(function(){ History.forward(false); }); // Go forward history.go(1); // End forward closure return true; }; /** * History.go(index,queue) * Send the browser history back or forward index times * @param {Integer} queue [optional] */ History.go = function(index,queue){ //History.debug('History.go: called', arguments); // Prepare var i; // Handle if ( index > 0 ) { // Forward for ( i=1; i<=index; ++i ) { History.forward(queue); } } else if ( index < 0 ) { // Backward for ( i=-1; i>=index; --i ) { History.back(queue); } } else { throw new Error('History.go: History.go requires a positive or negative integer passed.'); } // Chain return History; }; // ==================================================================== // HTML5 State Support // Non-Native pushState Implementation if ( History.emulated.pushState ) { /* * Provide Skeleton for HTML4 Browsers */ // Prepare var emptyFunction = function(){}; History.pushState = History.pushState||emptyFunction; History.replaceState = History.replaceState||emptyFunction; } // History.emulated.pushState // Native pushState Implementation else { /* * Use native HTML5 History API Implementation */ /** * History.onPopState(event,extra) * Refresh the Current State */ History.onPopState = function(event,extra){ // Prepare var stateId = false, newState = false, currentHash, currentState; // Reset the double check History.doubleCheckComplete(); // Check for a Hash, and handle apporiatly currentHash = History.getHash(); if ( currentHash ) { // Expand Hash currentState = History.extractState(currentHash||document.location.href,true); if ( currentState ) { // We were able to parse it, it must be a State! // Let's forward to replaceState //History.debug('History.onPopState: state anchor', currentHash, currentState); History.replaceState(currentState.data, currentState.title, currentState.url, false); } else { // Traditional Anchor //History.debug('History.onPopState: traditional anchor', currentHash); History.Adapter.trigger(window,'anchorchange'); History.busy(false); } // We don't care for hashes History.expectedStateId = false; return false; } // Ensure stateId = History.Adapter.extractEventData('state',event,extra) || false; // Fetch State if ( stateId ) { // Vanilla: Back/forward button was used newState = History.getStateById(stateId); } else if ( History.expectedStateId ) { // Vanilla: A new state was pushed, and popstate was called manually newState = History.getStateById(History.expectedStateId); } else { // Initial State newState = History.extractState(document.location.href); } // The State did not exist in our store if ( !newState ) { // Regenerate the State newState = History.createStateObject(null,null,document.location.href); } // Clean History.expectedStateId = false; // Check if we are the same state if ( History.isLastSavedState(newState) ) { // There has been no change (just the page's hash has finally propagated) //History.debug('History.onPopState: no change', newState, History.savedStates); History.busy(false); return false; } // Store the State History.storeState(newState); History.saveState(newState); // Force update of the title History.setTitle(newState); // Fire Our Event History.Adapter.trigger(window,'statechange'); History.busy(false); // Return true return true; }; History.Adapter.bind(window,'popstate',History.onPopState); /** * History.pushState(data,title,url) * Add a new State to the history object, become it, and trigger onpopstate * We have to trigger for HTML4 compatibility * @param {object} data * @param {string} title * @param {string} url * @return {true} */ History.pushState = function(data,title,url,queue){ //History.debug('History.pushState: called', arguments); // Check the State if ( History.getHashByUrl(url) && History.emulated.pushState ) { throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).'); } // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.pushState: we must wait', arguments); History.pushQueue({ scope: History, callback: History.pushState, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Create the newState var newState = History.createStateObject(data,title,url); // Check it if ( History.isLastSavedState(newState) ) { // Won't be a change History.busy(false); } else { //remove previously stored state, because it can be and can be non empty History.Adapter.trigger(window, 'stateremove', { stateId: newState.id }); // Store the newState History.storeState(newState); History.expectedStateId = newState.id; // Push the newState history.pushState(newState.id,newState.title,newState.url); // Fire HTML5 Event History.Adapter.trigger(window,'popstate'); } // End pushState closure return true; }; /** * History.replaceState(data,title,url) * Replace the State and trigger onpopstate * We have to trigger for HTML4 compatibility * @param {object} data * @param {string} title * @param {string} url * @param {object} queue * @param {boolean} createNewState * @return {true} */ History.replaceState = function(data,title,url,queue,createNewState){ //History.debug('History.replaceState: called', arguments); // Check the State if ( History.getHashByUrl(url) && History.emulated.pushState ) { throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).'); } // Handle Queueing if ( queue !== false && History.busy() ) { // Wait + Push to Queue //History.debug('History.replaceState: we must wait', arguments); History.pushQueue({ scope: History, callback: History.replaceState, args: arguments, queue: queue }); return false; } // Make Busy + Continue History.busy(true); // Create the newState var newState; if (createNewState) { data.rnd = new Date().getTime(); newState = History.createStateObject(data, title, url); } else { newState = History.getState(); newState.data = data; History.idToState[newState.id] = newState; History.extendObject(History.getLastSavedState(), newState); } // Check it if ( History.isLastSavedState(newState) ) { // Won't be a change History.busy(false); } else { // Store the newState History.storeState(newState); History.expectedStateId = newState.id; // Push the newState history.replaceState(newState.id,newState.title,newState.url); // Fire HTML5 Event History.Adapter.trigger(window,'popstate'); } // End replaceState closure return true; }; } // !History.emulated.pushState // ==================================================================== // Initialise /** * Load the Store */ if ( sessionStorage ) { // Fetch try { History.store = JSON.parse(/*LZString.decompress*/(sessionStorage.getItem('History.store')))||{}; } catch ( err ) { History.store = {}; } // Normalize History.normalizeStore(); } else { // Default Load History.store = {}; History.normalizeStore(); } /** * Clear Intervals on exit to prevent memory leaks */ History.Adapter.bind(window,"beforeunload",History.clearAllIntervals); History.Adapter.bind(window,"unload",History.clearAllIntervals); /** * Create the initial State */ History.saveState(History.storeState(History.extractState(document.location.href,true))); /** * Bind for Saving Store */ if ( sessionStorage ) { // When the page is closed History.onUnload = function(){ // Prepare var currentStore, item; // Fetch try { currentStore = JSON.parse(/*LZString.decompress*/(sessionStorage.getItem('History.store')))||{}; } catch ( err ) { currentStore = {}; } // Ensure currentStore.idToState = currentStore.idToState || {}; currentStore.urlToId = currentStore.urlToId || {}; currentStore.stateToId = currentStore.stateToId || {}; // Sync for ( item in History.idToState ) { if ( !History.idToState.hasOwnProperty(item) ) { continue; } currentStore.idToState[item] = History.idToState[item]; } for ( item in History.urlToId ) { if ( !History.urlToId.hasOwnProperty(item) ) { continue; } currentStore.urlToId[item] = History.urlToId[item]; } for ( item in History.stateToId ) { if ( !History.stateToId.hasOwnProperty(item) ) { continue; } currentStore.stateToId[item] = History.stateToId[item]; } var historyEntries = []; var maxHistoryEntriesCount = 10; //slice overweight entries for ( item in currentStore.idToState ) { if ( !currentStore.idToState.hasOwnProperty(item) ) { continue; } currentStore.idToState[item].entryId = item; historyEntries.push(currentStore.idToState[item]); } if (historyEntries.length > maxHistoryEntriesCount) { historyEntries.sort(function(e1, e2) { return e1.entryId - e2.entryId; }); var excludedEntries = historyEntries.slice(0, historyEntries.length - maxHistoryEntriesCount); for (var entryIndex = 0; entryIndex < excludedEntries.length; entryIndex++) { var entry = excludedEntries[entryIndex]; delete currentStore.idToState[entry.entryId]; for (var url in currentStore.urlToId ) { if (currentStore.urlToId.hasOwnProperty(url) && currentStore.urlToId[url] == entry.entryId) { delete currentStore.urlToId[url]; } } for (var state in currentStore.stateToId ) { if (currentStore.stateToId.hasOwnProperty(state) && currentStore.stateToId[state] == entry.entryId) { delete currentStore.stateToId[state]; } } History.Adapter.trigger(window, 'stateremove', { stateId: entry.entryId }); } } // Update History.store = currentStore; History.normalizeStore(); // Store History.setSessionStorageItem('History.store', /*LZString.compress*/(JSON.stringify(currentStore))); }; // For Internet Explorer History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval)); // For Other Browsers History.Adapter.bind(window,'beforeunload',History.onUnload); History.Adapter.bind(window,'unload',History.onUnload); // Both are enabled for consistency } // Non-Native pushState Implementation if ( !History.emulated.pushState ) { // Be aware, the following is only for native pushState implementations // If you are wanting to include something for all browsers // Then include it above this if block /** * Setup Safari Fix */ if ( History.bugs.safariPoll ) { History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval)); } /** * Ensure Cross Browser Compatibility */ if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) { /** * Fix Safari HashChange Issue */ // Setup Alias History.Adapter.bind(window,'hashchange',function(){ History.Adapter.trigger(window,'popstate'); }); // Initialise Alias if ( History.getHash() ) { History.Adapter.onDomLoad(function(){ History.Adapter.trigger(window,'hashchange'); }); } } } // !History.emulated.pushState }; // History.initCore // Try and Initialise History History.init(); })(window);
SkReD/history.js
scripts/uncompressed/history.js
JavaScript
bsd-3-clause
50,992
'use strict'; module.exports = function (Logger, $rootScope) { return { restrict: 'A', scope: { hasRank: '=' }, link: function ($scope, elem, attrs) { $rootScope.$watch('currentUser', function () { Logger.info('Checking for rank: ' + $scope.hasRank); if ($rootScope.currentUser && $rootScope.currentUser.rank >= $scope.hasRank) { elem.show(); } else { elem.hide(); } }); } }; };
e1528532/libelektra
src/tools/rest-frontend/resources/assets/js/directives/permission/HasRankDirective.js
JavaScript
bsd-3-clause
571
/** * @file * Money is a value object representing a monetary value. It does not use * floating point numbers, so it avoids rounding errors. * The only operation that may cause stray cents is split, it assures that no * cents vanish by distributing as evenly as possible among the parts it splits into. * * Money has no notion of currency, so working in a single currency -- no matter * which one -- is appropriate usage. * * In lack of better terminology, Money uses "dollars" and "cents". * * One dollar is assumed to be 100 cents. * * The cent number is guaranteed to be below 100. */ Module("Cactus.Data", function (m) { /** * @param natural dollars * @param natural cents * if > 100 then dollars are added until cents < 100. */ var Money = Class("Money", { has : { /** * @type int */ amount : null }, methods : { BUILD : function (dollars, cents) { var dollars = parseInt(dollars, 10); var cents = parseInt(cents, 10); if (dollars !== 0 && cents < 0) { throw new Error("Money: cents < 0"); } if (isNaN(dollars)) { throw new Error("Money: dollars is NaN"); } if (isNaN(cents)) { throw new Error("Money: cents is NaN"); } return { amount : dollars * 100 + (dollars < 0 ? -1 * cents : cents) }; }, /** * @return int */ _getAmount : function () { return this.amount; }, /** * @return natural */ getDollars : function () { if (this.amount < 0) { return Math.ceil(this.amount / 100); } else { return Math.floor(this.amount / 100); } }, /** * @return natural */ getCents : function () { if (this.amount < 0 && this.getDollars() === 0) { return this.amount % 100; } else { return Math.abs(this.amount % 100); } }, /** * The value with zero padded cents if < 100, and . used as the decimal * separator. * * @return string */ toString : function () { if (this.isNegative()) { if (this.gt(new Money(-1, 0))) { var cents = (-this.getCents()) < 10 ? "0" + (-this.getCents()) : (-this.getCents()); return "-0." + cents; } } var cents = this.getCents() < 10 ? "0" + this.getCents() : this.getCents(); return this.getDollars() + "." + cents; }, /** * @param Money money * @return Money */ add : function (money) { return Money._fromAmount(this._getAmount() + money._getAmount()); }, /** * @param Money money * @return Money */ sub : function (money) { return Money._fromAmount(this._getAmount() - money._getAmount()); }, /** * @param number multiplier * @return Money */ mult : function (multiplier) { return Money._fromAmount(this._getAmount() * multiplier); }, /** * @return Boolean */ isPositive : function () { return this._getAmount() > 0; }, /** * @return Boolean */ isNegative : function () { return this._getAmount() < 0; }, /** * @return Boolean */ isZero : function () { return this._getAmount() === 0; }, /** * @param Money money * @return Boolean */ equals : function (money) { return this._getAmount() === money._getAmount(); }, /** * @param Money money * @return Boolean */ gt : function (money) { return this._getAmount() > money._getAmount(); }, /** * @param Money money * @return Boolean */ lt : function (money) { return money.gt(this); }, /** * @param Money money * @return Money */ negate : function () { return Money._fromAmount(-this._getAmount()); }, /** * Splits the object into parts, the remaining cents are distributed from * the first element of the result and onward. * * @param int divisor * @return Array<Money> */ split : function (divisor) { var dividend = this._getAmount(); var quotient = Math.floor(dividend / divisor); var remainder = dividend - quotient * divisor; var res = []; var moneyA = Money._fromAmount(quotient + 1); var moneyB = Money._fromAmount(quotient); for (var i = 0; i < remainder; i++) { res.push(moneyA); } for (i = 0; i < divisor - remainder; i++) { res.push(moneyB); } return res; }, /** * @return Hash{ * dollars : int, * cents : int * } */ serialize : function () { return { dollars : this.getDollars(), cents : this.getCents() }; } } }); /** * @param String s * @return Money */ Money.fromString = function (s) { if (s === null) { throw new Error("Money.fromString: String was null."); } if (s === "") { throw new Error("Money.fromString: String was empty."); } if (!/^-?\d+(?:\.\d{2})?$/.test(s)) { throw new Error("Money.fromString: Invalid format, got: " + s); } var a = s.split("."); if (a.length === 1) { return new Money(parseInt(a[0], 10), 0); } else if (a.length === 2) { return new Money(parseInt(a[0], 10), parseInt(a[1], 10)); } else { throw new Error("Money:fromString: BUG: RegExp should have prevent this from happening."); } }; /** * @param int amount * @return Money */ Money._fromAmount = function (amount) { if (amount > 0) { return new Money(Math.floor(amount / 100), amount % 100); } else { return new Money(Math.ceil(amount / 100), Math.abs(amount) < 100 ? (amount % 100) : -(amount % 100)); } }; /** * @param Array<Money> ms * @return Money */ Money.sum = function (ms) { var sum = new Money(0, 0); for (var i = 0; i < ms.length; i++) { sum = sum.add(ms[i]); } return sum; }; m.Money = Money; });
bergmark/Cactus
module/Core/lib/Data/Money.js
JavaScript
bsd-3-clause
6,415
// An object that encapsulates everything we need to run a 'find' // operation, encoded in the REST API format. var Parse = require('parse/node').Parse; import { default as FilesController } from './Controllers/FilesController'; // restOptions can include: // skip // limit // order // count // include // keys // redirectClassNameForKey function RestQuery(config, auth, className, restWhere = {}, restOptions = {}) { this.config = config; this.auth = auth; this.className = className; this.restWhere = restWhere; this.response = null; this.findOptions = {}; if (!this.auth.isMaster) { this.findOptions.acl = this.auth.user ? [this.auth.user.id] : null; if (this.className == '_Session') { if (!this.findOptions.acl) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'This session token is invalid.'); } this.restWhere = { '$and': [this.restWhere, { 'user': { __type: 'Pointer', className: '_User', objectId: this.auth.user.id } }] }; } } this.doCount = false; // The format for this.include is not the same as the format for the // include option - it's the paths we should include, in order, // stored as arrays, taking into account that we need to include foo // before including foo.bar. Also it should dedupe. // For example, passing an arg of include=foo.bar,foo.baz could lead to // this.include = [['foo'], ['foo', 'baz'], ['foo', 'bar']] this.include = []; for (var option in restOptions) { switch(option) { case 'keys': this.keys = new Set(restOptions.keys.split(',')); this.keys.add('objectId'); this.keys.add('createdAt'); this.keys.add('updatedAt'); break; case 'count': this.doCount = true; break; case 'skip': case 'limit': this.findOptions[option] = restOptions[option]; break; case 'order': var fields = restOptions.order.split(','); var sortMap = {}; for (var field of fields) { if (field[0] == '-') { sortMap[field.slice(1)] = -1; } else { sortMap[field] = 1; } } this.findOptions.sort = sortMap; break; case 'include': var paths = restOptions.include.split(','); var pathSet = {}; for (var path of paths) { // Add all prefixes with a .-split to pathSet var parts = path.split('.'); for (var len = 1; len <= parts.length; len++) { pathSet[parts.slice(0, len).join('.')] = true; } } this.include = Object.keys(pathSet).sort((a, b) => { return a.length - b.length; }).map((s) => { return s.split('.'); }); break; case 'redirectClassNameForKey': this.redirectKey = restOptions.redirectClassNameForKey; this.redirectClassName = null; break; default: throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad option: ' + option); } } } // A convenient method to perform all the steps of processing a query // in order. // Returns a promise for the response - an object with optional keys // 'results' and 'count'. // TODO: consolidate the replaceX functions RestQuery.prototype.execute = function() { return Promise.resolve().then(() => { return this.buildRestWhere(); }).then(() => { return this.runFind(); }).then(() => { return this.runCount(); }).then(() => { return this.handleInclude(); }).then(() => { return this.response; }); }; RestQuery.prototype.buildRestWhere = function() { return Promise.resolve().then(() => { return this.getUserAndRoleACL(); }).then(() => { return this.redirectClassNameForKey(); }).then(() => { return this.validateClientClassCreation(); }).then(() => { return this.replaceSelect(); }).then(() => { return this.replaceDontSelect(); }).then(() => { return this.replaceInQuery(); }).then(() => { return this.replaceNotInQuery(); }); } // Uses the Auth object to get the list of roles, adds the user id RestQuery.prototype.getUserAndRoleACL = function() { if (this.auth.isMaster || !this.auth.user) { return Promise.resolve(); } return this.auth.getUserRoles().then((roles) => { roles.push(this.auth.user.id); this.findOptions.acl = roles; return Promise.resolve(); }); }; // Changes the className if redirectClassNameForKey is set. // Returns a promise. RestQuery.prototype.redirectClassNameForKey = function() { if (!this.redirectKey) { return Promise.resolve(); } // We need to change the class name based on the schema return this.config.database.redirectClassNameForKey( this.className, this.redirectKey).then((newClassName) => { this.className = newClassName; this.redirectClassName = newClassName; }); }; // Validates this operation against the allowClientClassCreation config. RestQuery.prototype.validateClientClassCreation = function() { let sysClass = ['_User', '_Installation', '_Role', '_Session', '_Product']; if (this.config.allowClientClassCreation === false && !this.auth.isMaster && sysClass.indexOf(this.className) === -1) { return this.config.database.collectionExists(this.className).then((hasClass) => { if (hasClass === true) { return Promise.resolve(); } throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'This user is not allowed to access ' + 'non-existent class: ' + this.className); }); } else { return Promise.resolve(); } }; // Replaces a $inQuery clause by running the subquery, if there is an // $inQuery clause. // The $inQuery clause turns into an $in with values that are just // pointers to the objects returned in the subquery. RestQuery.prototype.replaceInQuery = function() { var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery'); if (!inQueryObject) { return; } // The inQuery value must have precisely two keys - where and className var inQueryValue = inQueryObject['$inQuery']; if (!inQueryValue.where || !inQueryValue.className) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $inQuery'); } var subquery = new RestQuery( this.config, this.auth, inQueryValue.className, inQueryValue.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push({ __type: 'Pointer', className: inQueryValue.className, objectId: result.objectId }); } delete inQueryObject['$inQuery']; if (Array.isArray(inQueryObject['$in'])) { inQueryObject['$in'] = inQueryObject['$in'].concat(values); } else { inQueryObject['$in'] = values; } // Recurse to repeat return this.replaceInQuery(); }); }; // Replaces a $notInQuery clause by running the subquery, if there is an // $notInQuery clause. // The $notInQuery clause turns into a $nin with values that are just // pointers to the objects returned in the subquery. RestQuery.prototype.replaceNotInQuery = function() { var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery'); if (!notInQueryObject) { return; } // The notInQuery value must have precisely two keys - where and className var notInQueryValue = notInQueryObject['$notInQuery']; if (!notInQueryValue.where || !notInQueryValue.className) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $notInQuery'); } var subquery = new RestQuery( this.config, this.auth, notInQueryValue.className, notInQueryValue.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push({ __type: 'Pointer', className: notInQueryValue.className, objectId: result.objectId }); } delete notInQueryObject['$notInQuery']; if (Array.isArray(notInQueryObject['$nin'])) { notInQueryObject['$nin'] = notInQueryObject['$nin'].concat(values); } else { notInQueryObject['$nin'] = values; } // Recurse to repeat return this.replaceNotInQuery(); }); }; // Replaces a $select clause by running the subquery, if there is a // $select clause. // The $select clause turns into an $in with values selected out of // the subquery. // Returns a possible-promise. RestQuery.prototype.replaceSelect = function() { var selectObject = findObjectWithKey(this.restWhere, '$select'); if (!selectObject) { return; } // The select value must have precisely two keys - query and key var selectValue = selectObject['$select']; // iOS SDK don't send where if not set, let it pass if (!selectValue.query || !selectValue.key || typeof selectValue.query !== 'object' || !selectValue.query.className || Object.keys(selectValue).length !== 2) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $select'); } var subquery = new RestQuery( this.config, this.auth, selectValue.query.className, selectValue.query.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push(result[selectValue.key]); } delete selectObject['$select']; if (Array.isArray(selectObject['$in'])) { selectObject['$in'] = selectObject['$in'].concat(values); } else { selectObject['$in'] = values; } // Keep replacing $select clauses return this.replaceSelect(); }) }; // Replaces a $dontSelect clause by running the subquery, if there is a // $dontSelect clause. // The $dontSelect clause turns into an $nin with values selected out of // the subquery. // Returns a possible-promise. RestQuery.prototype.replaceDontSelect = function() { var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect'); if (!dontSelectObject) { return; } // The dontSelect value must have precisely two keys - query and key var dontSelectValue = dontSelectObject['$dontSelect']; if (!dontSelectValue.query || !dontSelectValue.key || typeof dontSelectValue.query !== 'object' || !dontSelectValue.query.className || Object.keys(dontSelectValue).length !== 2) { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $dontSelect'); } var subquery = new RestQuery( this.config, this.auth, dontSelectValue.query.className, dontSelectValue.query.where); return subquery.execute().then((response) => { var values = []; for (var result of response.results) { values.push(result[dontSelectValue.key]); } delete dontSelectObject['$dontSelect']; if (Array.isArray(dontSelectObject['$nin'])) { dontSelectObject['$nin'] = dontSelectObject['$nin'].concat(values); } else { dontSelectObject['$nin'] = values; } // Keep replacing $dontSelect clauses return this.replaceDontSelect(); }) }; // Returns a promise for whether it was successful. // Populates this.response with an object that only has 'results'. RestQuery.prototype.runFind = function() { return this.config.database.find( this.className, this.restWhere, this.findOptions).then((results) => { if (this.className == '_User') { for (var result of results) { delete result.password; } } this.config.filesController.expandFilesInObject(this.config, results); if (this.keys) { var keySet = this.keys; results = results.map((object) => { var newObject = {}; for (var key in object) { if (keySet.has(key)) { newObject[key] = object[key]; } } return newObject; }); } if (this.redirectClassName) { for (var r of results) { r.className = this.redirectClassName; } } this.response = {results: results}; }); }; // Returns a promise for whether it was successful. // Populates this.response.count with the count RestQuery.prototype.runCount = function() { if (!this.doCount) { return; } this.findOptions.count = true; delete this.findOptions.skip; delete this.findOptions.limit; return this.config.database.find( this.className, this.restWhere, this.findOptions).then((c) => { this.response.count = c; }); }; // Augments this.response with data at the paths provided in this.include. RestQuery.prototype.handleInclude = function() { if (this.include.length == 0) { return; } var pathResponse = includePath(this.config, this.auth, this.response, this.include[0]); if (pathResponse.then) { return pathResponse.then((newResponse) => { this.response = newResponse; this.include = this.include.slice(1); return this.handleInclude(); }); } else if (this.include.length > 0) { this.include = this.include.slice(1); return this.handleInclude(); } return pathResponse; }; // Adds included values to the response. // Path is a list of field names. // Returns a promise for an augmented response. function includePath(config, auth, response, path) { var pointers = findPointers(response.results, path); if (pointers.length == 0) { return response; } var className = null; var objectIds = {}; for (var pointer of pointers) { if (className === null) { className = pointer.className; } else { if (className != pointer.className) { throw new Parse.Error(Parse.Error.INVALID_JSON, 'inconsistent type data for include'); } } objectIds[pointer.objectId] = true; } if (!className) { throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad pointers'); } // Get the objects for all these object ids var where = {'objectId': {'$in': Object.keys(objectIds)}}; var query = new RestQuery(config, auth, className, where); return query.execute().then((includeResponse) => { var replace = {}; for (var obj of includeResponse.results) { obj.__type = 'Object'; obj.className = className; if(className == "_User"){ delete obj.sessionToken; } replace[obj.objectId] = obj; } var resp = { results: replacePointers(response.results, path, replace) }; if (response.count) { resp.count = response.count; } return resp; }); } // Object may be a list of REST-format object to find pointers in, or // it may be a single object. // If the path yields things that aren't pointers, this throws an error. // Path is a list of fields to search into. // Returns a list of pointers in REST format. function findPointers(object, path) { if (object instanceof Array) { var answer = []; for (var x of object) { answer = answer.concat(findPointers(x, path)); } return answer; } if (typeof object !== 'object') { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'can only include pointer fields'); } if (path.length == 0) { if (object.__type == 'Pointer') { return [object]; } throw new Parse.Error(Parse.Error.INVALID_QUERY, 'can only include pointer fields'); } var subobject = object[path[0]]; if (!subobject) { return []; } return findPointers(subobject, path.slice(1)); } // Object may be a list of REST-format objects to replace pointers // in, or it may be a single object. // Path is a list of fields to search into. // replace is a map from object id -> object. // Returns something analogous to object, but with the appropriate // pointers inflated. function replacePointers(object, path, replace) { if (object instanceof Array) { return object.map((obj) => replacePointers(obj, path, replace)); } if (typeof object !== 'object') { return object; } if (path.length == 0) { if (object.__type == 'Pointer') { return replace[object.objectId]; } return object; } var subobject = object[path[0]]; if (!subobject) { return object; } var newsub = replacePointers(subobject, path.slice(1), replace); var answer = {}; for (var key in object) { if (key == path[0]) { answer[key] = newsub; } else { answer[key] = object[key]; } } return answer; } // Finds a subobject that has the given key, if there is one. // Returns undefined otherwise. function findObjectWithKey(root, key) { if (typeof root !== 'object') { return; } if (root instanceof Array) { for (var item of root) { var answer = findObjectWithKey(item, key); if (answer) { return answer; } } } if (root && root[key]) { return root; } for (var subkey in root) { var answer = findObjectWithKey(root[subkey], key); if (answer) { return answer; } } } module.exports = RestQuery;
aneeshd16/parse-server
src/RestQuery.js
JavaScript
bsd-3-clause
17,157
/* * jQuery File Upload Plugin JS Example 8.9.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* global $, window */ $(function () { 'use strict'; // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: root_url + '/media/upload' }); // Enable iframe cross-domain access via redirect option: $('#fileupload').fileupload( 'option', 'redirect', window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); if (window.location.hostname === 'blueimp.github.io') { // Demo settings: $('#fileupload').fileupload('option', { url: '//jquery-file-upload.appspot.com/', // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), maxFileSize: 5000000, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i }); // Upload server status check for browsers with CORS support: if ($.support.cors) { $.ajax({ url: '//jquery-file-upload.appspot.com/', type: 'HEAD' }).fail(function () { $('<div class="alert alert-danger"/>') .text('Upload server currently unavailable - ' + new Date()) .appendTo('#fileupload'); }); } } else { // Load existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ // Uncomment the following to send cross-domain cookies: //xhrFields: {withCredentials: true}, url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, $.Event('done'), {result: result}); }); } /////////////////////////////////////////////// });
vohoanglong07/yii_basic
web/js/fileupload/main.js
JavaScript
bsd-3-clause
2,550
/*! * speedt * Copyright(c) 2015 speedt <[email protected]> * BSD 3 Licensed */ 'use strict'; var utils = require('speedt-utils'); var Service = function(app){ var self = this; // TODO self.serverId = app.getServerId(); self.connCount = 0; self.loginedCount = 0; self.logined = {}; }; module.exports = Service; var proto = Service.prototype; proto.increaseConnectionCount = function(){ return ++this.connCount; }; proto.decreaseConnectionCount = function(uid){ var self = this; // TODO var result = [--self.connCount]; // TODO if(uid) result.push(removeLoginedUser.call(self, uid)); return result; }; proto.replaceLoginedUser = function(uid, info){ var self = this; // TODO var user = self.logined[uid]; if(user) return updateUserInfo.call(self, user, info); // TODO self.loginedCount++; // TODO info.uid = uid; self.logined[uid] = info; }; var updateUserInfo = function(user, info){ var self = this; // TODO for(var p in info){ if(info.hasOwnProperty(p) && typeof 'function' !== info[p]){ self.logined[user.uid][p] = info[p]; } // END } // END }; var removeLoginedUser = function(uid){ var self = this; // TODO if(!self.logined[uid]) return; // TODO delete self.logined[uid]; // TODO return --self.loginedCount; }; proto.getStatisticsInfo = function(){ var self = this; return { serverId: self.serverId, connCount: self.connCount, loginedCount: self.loginedCount, logined: self.logined }; };
3203317/st
server/lib/common/services/connectionService.js
JavaScript
bsd-3-clause
1,457
exports.dbname = "lrdata"; exports.dbuser = "lrdata"; exports.dbpassword = "test"; exports.lfmApiKey = 'c0db7c8bfb98655ab25aa2e959fdcc68'; exports.lfmApiSecret = 'aff4890d7cb9492bc72250abbeffc3e1'; exports.tagAgeBeforeRefresh = 14; // In days exports.tagFetchFrequency = 1000; // In milliseconds
alnorth/listening-room-add-ons-site
config.js
JavaScript
bsd-3-clause
298
const initialState = { country: 'es', language: 'es-ES' } const settings = (state = initialState, action) => { switch (action.type) { default: return state } } export default settings
emoriarty/podcaster
src/reducers/settings.js
JavaScript
bsd-3-clause
200
/** Copyright (c) 2014, Nathan Carver 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. Neither the name of the copyright holder 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. */ /** * @file Code to run the TEETH Smart Toothbrush Holder on Intel Edison board. * * Code is maintained at https://github.com/ncarver/TEETH-IotToothbrushHolder. * * All code and modules are defined in this file, main.js. * * @author Nathan Carver * @copyright Nathan Carver 2014 * @version 0.0.1 */ /* * Required libraries * * You will need these libraries to interface with the services and hardware. */ var MRAA = require('mraa'); //require MRAA for communicating with hardware pins var LCD = require('jsupm_i2clcd'); //require LCD libraries for signaling the LCD screen var LED = require('jsupm_grove'); //require SEEED Grove library for photoresister var BUZZ = require("jsupm_buzzer"); //require SEEED Grove library for buzzer var MAILER = require('nodemailer'); //require for sending emails over SMTP var NET = require('net'); //require for sending cloud data to Edison service on TCP /** * Change the constants properties to customize the operation of the TEETH Smart Toothbrush Timer * @global */ var constants = { 'LOG_LEVEL': 3, //Change this value to limit loggin output: 0-none, 1-err, 2-warn, 3-info, 4-debug, 5-all 'USE_SOUND': true, 'PINS': { //Change these values to match the pins on your Edison build 'brushSwitch': [8, 4], //digital pins monitoring switches for toothbrushes 'buzzer': 3, //digital pin for signaling the buzzer 'roomLightSensor': 0, //analog pin for getting room light readings from photoresister on 10K external pullup 'roomLightThreshold' : 80 //value that indicates that room is dark }, 'MAIL': { //Change these values based on documentation at nodemailer to use your SMTP account 'service': 'Gmail', //Account service name, ex. "Gmail" 'user': '[email protected]', //user name to login to your service 'pass': 'pass****', //password to login to your service 'from': 'TEETH <[email protected]>', //appears in the "From:" section of your emails 'brushTo': ['[email protected]', '[email protected]'], //email value for each toothbrush 'subject': 'Great job on TEETH!', //appears as the subject of your emails 'body': 'You met the goal today. Way to go!' //the body text of your emails }, 'METRICS': { //Change these values to match the custom components of your Intel Cloud Analytics 'brushComponent': ['brush1', 'brush2'] //component value for each toothbrush }, 'SCREEN_MSG': { //Messages that appear on the LCD screen during the timer prep and countdown 'ready': '...get ready', //message to display during start of prep time 'set': '.....get set', //message to display last five seconds of prep time 'countdown': 'Countdown:', //message to display during countdown 'percent25': '...almost there!', //message to display 25% of the way through countdown 'percent50': 'good...halfway ', //message to display 50% of the way through countdown 'percent75': 'you\'re doing it ', //message to display 75% of the way through countdown 'finish': 'GREAT JOB!', //message to display at the end of countdown 'brushName': ['Nathan', 'Sarah'] //name to display during countdwon, one value for each toothbrush }, 'TIME': { //Time focused constants for timer, buzzer sounds 'brushPreptime': [10, 30], //seconds of prep time for each toothbrush 'brushGoaltime': [30, 120], //seconds of countdown time for each toothbrush 'buzzDuration': 20, //milliseconds of buzzer time for start and stop sounds 'buzzInterval': 150 //milliseconds between buzzer sounds for start and stop signals }, 'COLOR': { //Colors to use on the LCD screen 'off': [ 0, 0, 0], //black - use when LCD is off 'ready': [100, 100, 100], //light grey - use during prep time 'percent0': [255, 68, 29], //red - use at start of countdown 'percent25': [232, 114, 12], //brown - use when countdown is 25% finished 'percent50': [255, 179, 0], //orange - use when countdown is 50% finished 'percent75': [232, 211, 12], //yellow - use when countdown is 75% finished 'finish': [ 89, 132, 13], //green - use when countdown is finished 'colorFadeDuration': 1000, //milliseconds to fade to new color during countdown mode 'fadeSteps': 100 //number of fading steps to take during colorFadeDuration } }; /** * These values hold the setTimeout and setInterval handles so they can be cleared as part of a timer interuption * @global */ var timers = { 'fadeColor': null, //timer fading the color on the LCD screen 'buzzerPlay': null, //timer playing the buzzer sounds 'buzzerWait': null, //timer waiting in between buzzer sounds 'prepCountdown': null, //timer for the main prep time 'startCountdown': null, //timer for the last five seconds of prep time 'countdown': null, //timer for the main countdown 'lightsOut': null //timer lookin for "lights out" interuption }; /** * Creates a new Logger object and the helper methods used to send messages to console. * Highest level of logging, ERR (1), only outputs errors during code execution. * Lowest level DEBUG (4) outputs all logging messages. * * @see constants.LOG_LEVEL Use the constant constants.LOG_LEVEL to adjust the level of output. * @class */ var Logger = function () { this.ERR = 1; this.WARN = 2; this.INFO = 3; this.DEBUG = 4; /** * @private */ var logLevels = ['', 'err', 'warn', 'info', 'debug']; /** * @param {string} msg message to send to logger * @param {int} level log level for this message * @public */ this.it = function (msg, level) { if (constants.LOG_LEVEL >= level || level === undefined) { console.log('%s - %s: %s', new Date(), logLevels[level], msg); } }; /* * @param {string} msg message to send to logger at log level ERR (1) * @public */ this.err = function (msg) { this.it(msg, this.ERR); }; /* * @param {string} msg message to send to logger at log level WARN (2) * @public */ this.warn = function (msg) { this.it(msg, this.WARN); }; /* * @param {string} msg message to send to logger at log level INFO (3) * @public */ this.info = function (msg) { this.it(msg, this.INFO); }; /* * @param {string} msg message to send to logger at log level DEBUG (4) * @public */ this.debug = function (msg) { this.it(msg, this.DEBUG); }; }; /** * Creates a new Sensors object to monitor the hardware connected to the Edison * @requires mraa:Gpio * @requires mraa:Aio * @param {Logger} log object for logging output * @see constants.PINS Use the constant constants.PINS to identify the hardware connections * @class */ var Sensors = function (log) { log.info('instatiate Sensors'); /** * @private */ var i; /** * the array of switches associated with each toothbrush are initialized * as INPUT pins during instatiation. * @public */ this.brushSwitch = []; for (i = 0; i < constants.PINS.brushSwitch.length; i = i + 1) { this.brushSwitch[i] = new MRAA.Gpio(constants.PINS.brushSwitch[i]); this.brushSwitch[i].dir(MRAA.DIR_IN); } /** * the analog pin for monitoring the phototransister is initialized * during instatiation. Expected that this photo cell will have a 10K * external pulldown resistor. * @public */ // this.roomLightSensor = new MRAA.Aio(constants.PINS.roomLightSensor); }; /** * Creates a new Buzzer object to play a sound on the buzzer connected to the Edison * @requires jsupm_buzzer:Buzzer * @param {Logger} log object for logging output * @see constants.TIME Use the properties of constants.TIME to adjust the buzzer sounds * @class */ var Buzzer = function (log) { log.info('instatiate Buzzer'); var buzzer = new BUZZ.Buzzer(constants.PINS.buzzer); /** * play calls the playSound method of the low-level buzzer class for a simple tone value * @private */ function play(buzzingTime) { log.debug('(buzzer.play for ' + buzzingTime + ')'); if (!constants.USE_SOUND) { return; } buzzer.playSound(BUZZ.DO, 5000); timers.buzzerPlay = setTimeout(function () { buzzer.playSound(BUZZ.DO, 0); }, buzzingTime); } /** * plays the standard sound for the buzz duration, then waits, and plays again * expected to be called at the beginning of the countdown * @public */ this.playStartSound = function () { log.info('buzzer.playStartSound'); play(constants.TIME.buzzDuration); timers.buzzerWait = setTimeout(function () { play(constants.TIME.buzzDuration); }, constants.TIME.buzzInterval); }; /** * plays the standard sound for the buzz duration, then waits, and plays again * expected to be called at the end of the countdown * @public */ this.playStopSound = function () { log.info('buzzer.playStopSound'); play(constants.TIME.buzzDuration); timers.buzzerWait = setTimeout(function () { play(constants.TIME.buzzDuration); }, constants.TIME.buzzInterval); }; }; /** * Creates a new Screen object to display messages and colors RGB LCD connected to the Edison over I2C * @requires jsupm_i2clcd:Jhd1313m1 * @param {Logger} log object for logging output * @see constants.COLOR Use the properties of constants.COLOR to adjust the screen background colors * @see constants.SCREEN_MSG Use the properties of constants.SCREEN_MSG to change the messages displayed on screen * @class */ var Screen = function (log) { log.info('instatiate Screen'); /** * Instance variables to connect to LCD screen and manage the color fading * @private */ var lcd = new LCD.Jhd1313m1(6, 0x3E, 0x62), //standard I2C bus interval = constants.COLOR.colorFadeDuration / constants.COLOR.fadeSteps, lastColor = constants.COLOR.off, steps = constants.COLOR.fadeSteps; /** * getRemainingSteps identifies how many more steps are needed before fade is finished * @returns {int} number of steps remaining * @private */ function getRemainingSteps() { log.debug('(screen.getRemainingSteps)'); return steps; } /** * setRemainingSteps sets how many more steps are needed before fade is finished * @params {int} remainingSteps new number of steps remaining * @private */ function setRemainingSteps(remainingSteps) { log.debug('(screen.setRemainingSteps: ' + remainingSteps + ')'); steps = remainingSteps; } /** * setScreen color calls low-level methods to set RGB values of screen background * also sets the instance variable "lastColor" to help with fade control * @param {array} colorArray array of decimal color values in Red Green Blue order [r,g,b] * @private */ function setScreenColor(colorArray) { log.debug('(screen.setScreenColor to ' + colorArray + ')'); lcd.setColor(colorArray[0], colorArray[1], colorArray[2]); lastColor = colorArray; } /** * Inner method called by timeouts to fade background color from current color to the * updated color passed RGB color array * @private */ function _fadeColor(colorArray) { log.debug('(screen._fadeColor: ' + colorArray + ')'); var step = getRemainingSteps(); if (step > 0) { var diffRed = colorArray[0] - lastColor[0], diffGrn = colorArray[1] - lastColor[1], diffBlu = colorArray[2] - lastColor[2], stepRed = parseInt(diffRed / step, 10), stepGrn = parseInt(diffGrn / step, 10), stepBlu = parseInt(diffBlu / step, 10), nextRed = lastColor[0] + stepRed, nextGrn = lastColor[1] + stepGrn, nextBlu = lastColor[2] + stepBlu; setScreenColor([nextRed, nextGrn, nextBlu]); setRemainingSteps(step - 1); timers.fadeColor = setTimeout(function () { _fadeColor(colorArray); }, interval); } } /** * Starts a timout sequence to slowy change the LCD RGB screen background from its current * color to the one passed in the parameters. The speed and number of steps used for fading * are controlled by the constants. * * @param {array} colorArray a 3-member array of decimal numbers describing the color to display * on the screen background: [r,g,b] * @public */ this.fadeColor = function (colorArray) { log.info('screen.fadeColor: ' + colorArray); setRemainingSteps(constants.COLOR.fadeSteps); _fadeColor(colorArray); }; /** * Helper method combines clearing the screen of all text content and returning the cursor * position back to the top left. * @public */ this.reset = function () { log.info('screen.reset'); lcd.clear(); lcd.setCursor(0, 0); }; /** * Helper method combines reseting the screen and returning the screen color to "off" * @public */ this.resetAndTurnOff = function () { log.info('screen.resetAndTurnOff'); this.reset(); setScreenColor(constants.COLOR.off); }; /** * Turns the screen on and displays the "ready" message defined in constants for the given toothbrush * * @param {int} componentIndex identifies the toothbrush by it's array index * @public */ this.displayReady = function (componentIndex) { log.info('screen.displayReady for ' + componentIndex); lcd.clear(); setScreenColor(constants.COLOR.ready); this.write(constants.SCREEN_MSG.brushName[componentIndex], 0, 0); this.write(constants.SCREEN_MSG.ready, 1, 0); }; /** * Changes the "ready" message to the "set" message defined in constants for the given toothbrush * * @param {int} componentIndex identifies the toothbrush by it's array index * @public */ this.displaySet = function (componentIndex) { log.info('screen.displaySet for ' + componentIndex); this.write(constants.SCREEN_MSG.set, 1, 0); }; /** * Helper message combines writing the given message to the screen at (optional) given coordinates * * @param {string} msg the string to ouput to the screen * @param {int} col (optional) 0-indexed column number to set the cursor * @param {int} row (optional) 0-indexed row number to set the cursor * @public */ this.write = function (msg, col, row) { //log.info('screen.write msg ' + msg); var i; if (!(col === undefined || row === undefined)) { lcd.setCursor(col, row); for (i = 0; i < 10000000; i = i + 1) { //wait for slow LCD } } lcd.write(msg); }; //initialize the LCD screen during instatiation this.resetAndTurnOff(); }; /** * Creates a new Mailer object to send mail over SMTP * @requires nodemailer * @param {Logger} log object for logging output * @see constants.MAIL Use the properties of constants.MAIL to configure your SMTP service * @class */ var Mailer = function (log) { log.info('instatiate Mailer'); /** * Instance options taken from constants.MAIL are used by createTransport to authenticate SMTP * @private */ var mailOptions = { from: constants.MAIL.from, // sender address to: constants.MAIL.brushTo[0], // list of receivers subject: constants.MAIL.subject, // Subject line text: constants.MAIL.body, // plaintext body html: constants.MAIL.body // html body }, transporter = MAILER.createTransport({ service: constants.MAIL.service, auth: { user: constants.MAIL.user, pass: constants.MAIL.pass } }); /** * Sends the message defined in constants.MAIL for the given toothbrush. * Errors are sent to the log Logger object. * @param {int} componentIndex identifies the toothbrush by it's array index in constants * @public */ this.sendCongratsEmail = function (componentIndex) { log.info('mailer.sendCongratsEmail for ' + componentIndex); mailOptions.to = constants.MAIL.brushTo[componentIndex]; transporter.sendMail(mailOptions, function (error, info) { if (error) { log.err('mail error ' + error + '.'); } else { log.info('mail sent.'); } }); }; }; /** * Creates a new Metrics object to connect to Intel Cloud Analytics over TCP * @requires net:socket * @param {Logger} log object for logging output * @class */ var Metrics = function (log) { log.info('instatiate metrics'); /** * instance objects and options to connect over TCP to Edison iot-agent * @private */ var client = new NET.Socket(), options = { host : 'localhost', //use the Intel analytics client running locally on the Edison port : 7070 //on default TCP port }; /** * sendObservation concatenates the string expected by cloud analytics based on the parameter values * @param {string} name custom component name registered with Intel analytics * @param {float} value data value to send to cloud * @private */ function sendObservation(name, value) { log.debug('(metrics.sendObservation for ' + name + ', ' + value + ')'); var msg = JSON.stringify({ n: name, v: value }), sentMsg = msg.length + "#" + msg; //syntax for Intel analytics client.write(sentMsg); } /** * Method combines the activity of connecting to the Edision service and then sending data to the cloud * @param {int} itemIndex array index of component names registered with Intel analytics * @param {float} timeValue data value to send to cloud, expecting fractional number of seconds * @public */ this.addDataToCloud = function (itemIndex, timeValue) { log.info('metrics.addDataToCloud for ' + itemIndex + ', ' + timeValue); client.on('error', function () { log.err('Could not connect to cloud'); }); client.connect(options.port, options.host, function () { sendObservation(constants.METRICS.brushComponent[itemIndex], timeValue); }); }; }; /** * Creates a new Teeth object to manage the countdown timer * @param {Logger} log object for logging output * @param {Sensors} sensor object for listening to hardware sensors * @param {Buzzer} buzzer object for controlling the sounds * @param {Screen} screen object for display on the RGB LCD screen * @param {Mailer} mailer object for sending email * @param {Metrics} metrics object for sending data to cloud * @see constants.TIME Use the properties of constants.TIME to adjust the length of the countdown * @class */ var Teeth = function (log, sensors, buzzer, lcdScreen, mailer, metrics) { log.info('instatiate teeth'); /** * flags to make sure fadeColor only called once for each color * @private */ var fades = [], currentComponent = -1, timeSpent = 0; /** * clearAllTimers loops through all timers in constants to clear them and set to null * @private */ function clearAllTimers() { log.debug('(teeth.clearAllTimers)'); var key, timer; for (key in timers) { if (timers.hasOwnProperty(key)) { timer = timers[key]; if (timer !== null) { clearTimeout(timer); timer = null; } } } fades = []; currentComponent = -1; } /** * finishCountdown clears the screen, plays the stop sound, and starts the waiting process again * @param {int} componentIndex array index number of the toothbrush that is finishing the countdown * @private */ function finishCountdown(componentIndex) { log.debug('(teeth.finishCountdown for ' + componentIndex + ')'); clearAllTimers(); lcdScreen.reset(); buzzer.playStopSound(); mailer.sendCongratsEmail(componentIndex); lcdScreen.write(constants.SCREEN_MSG.finish); metrics.addDataToCloud(componentIndex, constants.TIME.brushGoaltime[componentIndex]); setTimeout(function () { lcdScreen.resetAndTurnOff(); wait(); }, 1000); } /** * countdown generates messages and colors to the screen during the countdown, * called continuously until time is over * @param {int} componentIndex array index number of the toothbrush that is in the middle of the countdown * @param {int} timeRemaining the amount of time remaining in seconds before the countdown is over * @private */ function countdown(componentIndex, timeRemaining) { log.debug('(teeth.countdown for ' + componentIndex + ': ' + timeRemaining + ')'); var originalValue = constants.TIME.brushGoaltime[componentIndex]; timeSpent = originalValue - timeRemaining; if (timeRemaining > 0) { lcdScreen.write(constants.SCREEN_MSG.countdown + timeRemaining + ' ', 0, 0); if (timeRemaining <= (0.25 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent25, 1, 0); if (fades[constants.COLOR.percent25] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent25); fades[constants.COLOR.percent25] = 1; } } else if (timeRemaining <= (0.5 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent50, 1, 0); if (fades[constants.COLOR.percent50] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent50); fades[constants.COLOR.percent50] = 1; } } else if (timeRemaining <= (0.75 * originalValue)) { lcdScreen.write(constants.SCREEN_MSG.percent75, 1, 0); if (fades[constants.COLOR.percent75] !== 1) { lcdScreen.fadeColor(constants.COLOR.percent75); fades[constants.COLOR.percent75] = 1; } } timers.countdown = setTimeout(function () { countdown(componentIndex, timeRemaining - 1); }, 1000); } else { finishCountdown(componentIndex); } } /** * startCountdown plays the sound and begins the first call to countdown * @param {int} componentIndex array index number of the toothbrush that is starting the countdown * @private */ function startCountdown(componentIndex) { log.info('(teeth.startCountdown for ' + componentIndex + ')'); buzzer.playStartSound(); lcdScreen.reset(); currentComponent = componentIndex; countdown(componentIndex, constants.TIME.brushGoaltime[componentIndex]); } /** * prepCountdown prepares the screen and waits for real countdown to begin, displays * an additional warning with five seconds to go * @param {int} componentIndex array index number of the toothbrush that is starting the countdown * @private */ function prepCountdown(componentIndex) { log.debug('(teeth.prepCountdown for ' + componentIndex + ')'); lcdScreen.displayReady(componentIndex); var prepTime = constants.TIME.brushPreptime[componentIndex]; timers.prepCountdown = setTimeout(function () { log.debug('setTimeout: prepCountdown'); lcdScreen.displaySet(componentIndex); }, (prepTime - 5) * 1000); timers.startCountdown = setTimeout(function () { log.debug('setTimeout: startCountdown'); startCountdown(componentIndex); }, prepTime * 1000); } /** * watchForLightsOut polls the photoresistor to see if the room is dark, then stops all activity * @private */ function watchForLightsOut() { //do not log.debug >> called every 50ms return; var val = sensors.roomLightSensor.read(); if (val < constants.PINS.roomLightThreshold) { log.info('Trigger for lights out: Stop Timer (early) then wait 5 seconds to start again'); if (currentComponent >= 0) { metrics.addDataToCloud(currentComponent, timeSpent); } clearAllTimers(); lcdScreen.resetAndTurnOff(); setTimeout(wait, 5000); } } /** * wait is the main entry to this class, it polls the switches regularly to see if it should start the countdown * @private */ function wait() { //do not log.debug >> called every 100ms var i, val; for (i = 0; i < sensors.brushSwitch.length; i = i + 1) { val = sensors.brushSwitch[i].read(); if (val === 0) { //0 for NO (normally open switch), 1 for NC (normally closed) log.info('Trigger for toothbrush ' + i + ': Start Timer'); prepCountdown(i); timers.lightsOut = setInterval(watchForLightsOut, 50); break; } } if (i >= sensors.brushSwitch.length) { setTimeout(wait, 100); } } /** * Entry point to Teeth, the start command initiates the Smart Toothbrush Holder and begins the process of waiting for a countdown * @public */ this.start = function () { log.info('Teeth.start waiting for toothbrush events'); wait(); }; }; /* Create instance objects of the classes needed by TEETH */ var log = new Logger(), sensors = new Sensors(log), buzzer = new Buzzer(log), lcdScreen = new Screen(log), mailer = new Mailer(log), metrics = new Metrics(log), teeth = new Teeth(log, sensors, buzzer, lcdScreen, mailer, metrics); /* Get the code running by invoking the start method of the Teeth controller */ teeth.start();
ncarver/TEETH
main.js
JavaScript
bsd-3-clause
28,665
define(['App', 'jquery', 'underscore', 'backbone', 'hbs!template/subreddit-picker-item', 'view/basem-view'], function(App, $, _, Backbone, SRPitemTmpl, BaseView) { return BaseView.extend({ template: SRPitemTmpl, events: { 'click .add': 'subscribe', 'click .remove': 'unsubscribe' }, initialize: function(data) { this.model = data.model; }, subscribe: function(e) { e.preventDefault() e.stopPropagation() var target = this.$(e.currentTarget) target.removeClass('add').addClass('remove').html('unsubscribe') var params = { action: 'sub', sr: this.model.get('name'), sr_name: this.model.get('name'), uh: $.cookie('modhash') }; console.log(params) this.api("api/subscribe", 'POST', params, function(data) { console.log("subscribe done", data) //edit the window and cookie App.trigger('header:refreshSubreddits') }); }, unsubscribe: function(e) { e.preventDefault() e.stopPropagation() var target = this.$(e.currentTarget) target.removeClass('remove').addClass('add').html('subscribe') var params = { action: 'unsub', sr: this.model.get('name'), uh: $.cookie('modhash') }; console.log(params) this.api("api/subscribe", 'POST', params, function(data) { console.log("unsubscribe done", data) App.trigger('header:refreshSubreddits') }); } }); });
BenjaminAdams/RedditJS
public/js/app/view/subreddit-picker-item-view.js
JavaScript
bsd-3-clause
1,957
"use strict"; var mapnik = require('../'); var assert = require('assert'); var path = require('path'); mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input')); describe('mapnik.Geometry ', function() { it('should throw with invalid usage', function() { // geometry cannot be created directly for now assert.throws(function() { mapnik.Geometry(); }); }); it('should access a geometry from a feature', function() { var feature = new mapnik.Feature(1); var point = { "type": "MultiPoint", "coordinates": [[0,0],[1,1]] }; var input = { type: "Feature", properties: {}, geometry: point }; var f = new mapnik.Feature.fromJSON(JSON.stringify(input)); var geom = f.geometry(); assert.equal(geom.type(),mapnik.Geometry.MultiPoint); assert.deepEqual(JSON.parse(geom.toJSONSync()),point); var expected_wkb = new Buffer('0104000000020000000101000000000000000000000000000000000000000101000000000000000000f03f000000000000f03f', 'hex'); assert.deepEqual(geom.toWKB(),expected_wkb); }); it('should fail on toJSON due to bad parameters', function() { var feature = new mapnik.Feature(1); var point = { "type": "MultiPoint", "coordinates": [[0,0],[1,1]] }; var input = { type: "Feature", properties: {}, geometry: point }; var f = new mapnik.Feature.fromJSON(JSON.stringify(input)); var geom = f.geometry(); assert.equal(geom.type(),mapnik.Geometry.MultiPoint); assert.throws(function() { geom.toJSONSync(null); }); assert.throws(function() { geom.toJSONSync({transform:null}); }); assert.throws(function() { geom.toJSONSync({transform:{}}); }); assert.throws(function() { geom.toJSON(null, function(err,json) {}); }); assert.throws(function() { geom.toJSON({transform:null}, function(err, json) {}); }); assert.throws(function() { geom.toJSON({transform:{}}, function(err, json) {}); }); }); it('should throw if we attempt to create a Feature from a geojson geometry (rather than geojson feature)', function() { var geometry = { type: 'Point', coordinates: [ 7.415119300000001, 43.730364300000005 ] }; // starts throwing, as expected, at Mapnik v3.0.9 (https://github.com/mapnik/node-mapnik/issues/560) if (mapnik.versions.mapnik_number >= 300009) { assert.throws(function() { var transformed = mapnik.Feature.fromJSON(JSON.stringify(geometry)); }); } }); it('should throw from empty geometry from toWKB', function() { var s = new mapnik.Feature(1); assert.throws(function() { var geom = s.geometry().toWKB(); }); }); });
langateam/node-mapnik
test/geometry.test.js
JavaScript
bsd-3-clause
2,955