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
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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 configuration = require('./configuration.json'); const bodyParser = require('body-parser'); const atob = require('atob'); function getConfiguration(req, res) { res.json(configuration); } function downloadZip(req, res) { const data = atob(req.body.project); console.log(data); const options = { root: `${__dirname}/../public/`, dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, }, }; const fileName = 'example.zip'; res.sendFile(fileName, options, err => { if (err) { res.status(500).send(err); } else { console.log('Sent:', fileName); } }); } function createOnGithub(req, res) { console.log(req.body); res.json({ success: true }); } function setup(app) { app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.get('/api/project/configuration', getConfiguration); app.post('/api/project/zip/form', downloadZip); app.post('/api/project/openapi/zip/form', downloadZip); app.post('/api/project/github', createOnGithub); } module.exports = setup;
chmyga/component-runtime
component-starter-server/src/main/frontend/backend/index.js
JavaScript
apache-2.0
1,677
sap.ui.define([ "sap/ui/core/UIComponent" ], function(UIComponent) { "use strict"; return UIComponent.extend("sap.ui.webc.main.sample.FileUploader.Component", { metadata: { manifest: "json" } }); });
SAP/openui5
src/sap.ui.webc.main/test/sap/ui/webc/main/demokit/sample/FileUploader/Component.js
JavaScript
apache-2.0
213
'use strict'; /** * Tests for when Zotero is down/inaccessible */ const assert = require('../../utils/assert.js'); const Server = require('../../utils/server.js'); describe('Zotero service down or disabled:', function () { describe('unreachable', function () { this.timeout(20000); const server = new Server(); // Give Zotero port which is it is not running from- // Mimics Zotero being down. before(() => server.start({ zoteroPort: 1971 })); after(() => server.stop()); // PMID on NIH website that is not found in the id converter api // This will fail when Zotero is disabled because we no longer directly scrape pubMed central URLs, // as they have blocked our UA in the past. it('PMID not in doi id converter api', function () { const pmid = '14656957'; return server.query(pmid, 'mediawiki', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.checkError(err, 404); // Exact error may differ as may be interpreted as pmcid or pmid }); }); // PMID on NIH website that is found in the id converter api- should convert to DOI // Uses three sources, crossref, pubmed and citoid it('PMCID present in doi id converter api', function () { return server.query('PMC3605911').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Viral Phylodynamics'); assert.deepEqual(res.body[0].url, 'https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002947'); assert.isInArray(res.body[0].source, 'Crossref'); assert.isInArray(res.body[0].source, 'PubMed'); assert.deepEqual(res.body[0].PMCID, 'PMC3605911'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Should contain ISSN'); // From highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // JSTOR page, uses crossRef it('JSTOR page', function () { return server.query('http://www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Should contain ISSN'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Article with doi within DublinCore metadata + highwire data', function () { return server.query('http://www.sciencemag.org/content/303/5656/387.short').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Multiple Ebola Virus Transmission Events and Rapid Decline of Central African Wildlife'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].date, '2004-01-16'); // Field uses highwire data with bePress translator assert.deepEqual(res.body[0].DOI, '10.1126/science.1092528'); // DOI from DC metadata assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('doi spage and epage fields in crossRef coins data', function () { return server.query('http://doi.org/10.1002/jlac.18571010113').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Ueber einige Derivate des Naphtylamins'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].pages, '90–93', 'Missing pages'); // Uses en dash assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses highwire press metadata', function () { return server.query('http://mic.microbiologyresearch.org/content/journal/micro/10.1099/mic.0.082289-0').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Resistance to bacteriocins produced by Gram-positive bacteria'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Missing ISSN'); // Comes from highwire assert.deepEqual(res.body[0].author.length, 3, 'Should have 3 authors'); assert.deepEqual(res.body[0].pages, '683–700', 'Incorrect or missing pages'); // Comes from crossRef assert.deepEqual(res.body[0].date, '2015-04-01', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses bepress press metadata alone', function () { return server.query('http://uknowledge.uky.edu/upk_african_history/1/').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'South Africa and the World: The Foreign Policy of Apartheid'); assert.deepEqual(res.body[0].author.length, 1, 'Should have 1 author'); assert.deepEqual(res.body[0].date, '1970', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); // Actually is a book but no way to tell from metadata :( }); }); it('Dead url with correct doi', function () { return server.query('http://mic.sgmjournals.org/content/journal/micro/10.1099/mic.0.26954-0').then(function (res) { assert.status(res, 200); assert.isInArray(res.body[0].source, 'Crossref'); assert.checkCitation(res, 'Increased transcription rates correlate with increased reversion rates in leuB and argH Escherichia coli auxotrophs'); // Title from crossRef assert.deepEqual(res.body[0].date, '2004-05-01'); assert.deepEqual(res.body[0].DOI, '10.1099/mic.0.26954-0'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Get error for bibtex export', function () { return server.query('http://www.example.com', 'bibtex', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.deepEqual(err.body.Error, 'Unable to serve bibtex format at this time'); assert.status(err, 404); // assert.checkError(err, 404, 'Unable to serve bibtex format at this time'); }); }); it('requires cookie handling', function () { return server.query('www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); }); }); // Ensure DOI is present in non-zotero scraped page where scraping fails it('DOI pointing to resource that can\'t be scraped - uses crossRef', function () { return server.query('10.1038/scientificamerican0200-90') .then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // Ensure DOI is present in non-zotero scraped page when request from DOI link it('dx.DOI link - uses crossRef', function () { return server.query('http://dx.DOI.org/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Case sensitive DOI with 5 digit registrant code and unknown genre in crossRef', function () { return server.query('10.14344/IOC.ML.4.4').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'IOC World Bird List 4.4'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); }); }); it('gets date from crossRef REST API', function () { return server.query('10.1016/S0305-0491(98)00022-4').then(function (res) { // Not sending the correct link to zotero - investigate assert.status(res, 200); assert.checkCitation(res, 'Energetics and biomechanics of locomotion by red kangaroos (Macropus rufus)'); assert.deepEqual(res.body[0].date, '1998-05'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'journalArticle'); }); }); it('gets editors from crossRef REST API for book-tract type', function () { return server.query('10.1017/isbn-9780511132971.eh1-7').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Population of the slave states, by state, race, and slave status: 1860-1870'); assert.deepEqual(!!res.body[0].date, false); // null date in crossRef assert.deepEqual(!!res.body[0].editor, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'bookSection'); }); }); it('gets proceedings from crossRef REST API', function () { return server.query('10.4271/2015-01-0821').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Simulating a Complete Performance Map of an Ethanol-Fueled Boosted HCCI Engine'); assert.deepEqual(res.body[0].date, '2015-04-14'); // null date in crossRef assert.deepEqual(!!res.body[0].author, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'conferencePaper'); }); }); // Prefer original url for using native scraper it('uses original url', function () { const url = 'http://www.google.com'; return server.query(url).then(function (res) { assert.checkCitation(res, 'Google'); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); assert.deepEqual(res.body[0].url, url); }); }); it('websiteTitle but no publicationTitle', function () { return server.query('http://blog.woorank.com/2013/04/dublin-core-metadata-for-seo-and-usability/').then(function (res) { assert.checkCitation(res); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); assert.deepEqual(!!res.body[0].websiteTitle, true, 'Missing websiteTitle field'); assert.deepEqual(res.body[0].publicationTitle, undefined, 'Invalid field publicationTitle'); }); }); it('dublinCore data with multiple identifiers in array', function () { return server.query('http://apps.who.int/iris/handle/10665/70863').then(function (res) { assert.checkCitation(res, 'Consensus document on the epidemiology of severe acute respiratory syndrome (SARS)'); assert.deepEqual(res.body[0].itemType, 'journalArticle'); assert.deepEqual(res.body[0].publisher, undefined); // TODO: Investigate why this is undefined assert.deepEqual(res.body[0].publicationTitle, undefined); // TODO: Investigate why this is undefined }); }); it('has page range in direct scrape', function () { return server.query('10.1017/s0305004100013554').then(function (res) { assert.checkCitation(res, 'Discussion of Probability Relations between Separated Systems'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].pages, '555–563', 'Wrong pages item; expected 555–563, got ' + res.body[0].pages); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // Unable to scrape and ends up with crossRef data it('DOI with redirect - Wiley', function () { return server.query('10.1029/94WR00436').then(function (res) { assert.checkCitation(res, 'A distributed hydrology-vegetation model for complex terrain'); assert.deepEqual(res.body[0].publicationTitle, 'Water Resources Research', 'Incorrect publicationTitle; Expected "Water Resources Research", got' + res.body[0].publicationTitle); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); }); }); }); describe('disabled in conf', function () { const server = new Server(); this.timeout(40000); before(() => server.start({ zotero: false })); after(() => server.stop()); // PMID on NIH website that is not found in the id converter api // This will fail when Zotero is disabled because we no longer directly scrape pubMed central URLs, // as they have blocked our UA in the past. it('PMID not in doi id converter api', function () { const pmid = '14656957'; return server.query(pmid, 'mediawiki', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.checkError(err, 404); // Error may be for pmcid or pmid }); }); // PMID on NIH website that is found in the id converter api- should convert to DOI // Uses three sources, crossref, pubmed and citoid it('PMCID present in doi id converter api', function () { return server.query('PMC3605911').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Viral Phylodynamics'); assert.deepEqual(res.body[0].url, 'https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002947'); assert.isInArray(res.body[0].source, 'Crossref'); assert.isInArray(res.body[0].source, 'PubMed'); assert.deepEqual(res.body[0].PMCID, 'PMC3605911'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Should contain ISSN'); // From highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // JSTOR page with tabs in natively scraped title it('JSTOR page with tabs in natively scraped title', function () { return server.query('http://www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Missing ISSN'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Article with doi within DublinCore metadata + highwire data', function () { return server.query('http://www.sciencemag.org/content/303/5656/387.short').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Multiple Ebola Virus Transmission Events and Rapid Decline of Central African Wildlife'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].date, '2004-01-16'); // Field uses highwire data with bePress translator assert.deepEqual(res.body[0].DOI, '10.1126/science.1092528'); // DOI from DC metadata assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('doi spage and epage fields in crossRef coins data', function () { return server.query('http://dx.doi.org/10.1002/jlac.18571010113').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Ueber einige Derivate des Naphtylamins'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].pages, '90–93', 'Missing pages'); // Uses en dash assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses highwire press metadata', function () { return server.query('http://mic.microbiologyresearch.org/content/journal/micro/10.1099/mic.0.082289-0').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Resistance to bacteriocins produced by Gram-positive bacteria'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Missing ISSN'); // Comes from highwire assert.deepEqual(res.body[0].author.length, 3, 'Should have 3 authors'); assert.deepEqual(res.body[0].pages, '683–700', 'Incorrect or missing pages'); // Comes from crossRef assert.deepEqual(res.body[0].date, '2015-04-01', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses bepress press metadata alone', function () { return server.query('http://uknowledge.uky.edu/upk_african_history/1/').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'South Africa and the World: The Foreign Policy of Apartheid'); assert.deepEqual(res.body[0].author.length, 1, 'Should have 1 author'); assert.deepEqual(res.body[0].date, '1970', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); // Actually is a book but no way to tell from metadata :( }); }); it('Dead url with doi', function () { return server.query('http://mic.sgmjournals.org/content/journal/micro/10.1099/mic.0.26954-0').then(function (res) { assert.status(res, 200); assert.isInArray(res.body[0].source, 'Crossref'); assert.checkCitation(res, 'Increased transcription rates correlate with increased reversion rates in leuB and argH Escherichia coli auxotrophs'); // Title from crossRef assert.deepEqual(res.body[0].date, '2004-05-01'); assert.deepEqual(res.body[0].DOI, '10.1099/mic.0.26954-0'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Get error for bibtex export', function () { return server.query('http://www.example.com', 'bibtex', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.deepEqual(err.body.Error, 'Unable to serve bibtex format at this time'); assert.status(err, 404); // assert.checkError(err, 404, 'Unable to serve bibtex format at this time'); }); }); it('requires cookie handling', function () { return server.query('www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); }); }); // Ensure DOI is present in non-zotero scraped page where scraping fails it('DOI pointing to resource that can\'t be scraped - uses crossRef', function () { return server.query('10.1038/scientificamerican0200-90') .then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // Ensure DOI is present in non-zotero scraped page when request from DOI link it('dx.DOI link - uses crossRef', function () { return server.query('http://dx.DOI.org/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Case sensitive DOI with 5 digit registrant code and unknown genre in crossRef', function () { return server.query('10.14344/IOC.ML.4.4').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'IOC World Bird List 4.4'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); }); }); it('gets date from crossRef REST API', function () { return server.query('10.1016/S0305-0491(98)00022-4').then(function (res) { // Not sending the correct link to zotero - investigate assert.status(res, 200); assert.checkCitation(res, 'Energetics and biomechanics of locomotion by red kangaroos (Macropus rufus)'); assert.deepEqual(res.body[0].date, '1998-05'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'journalArticle'); }); }); it('gets editors from crossRef REST API for book-tract type', function () { return server.query('10.1017/isbn-9780511132971.eh1-7').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Population of the slave states, by state, race, and slave status: 1860-1870'); assert.deepEqual(!!res.body[0].date, false); // null date in crossRef assert.deepEqual(!!res.body[0].editor, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'bookSection'); }); }); it('gets proceedings from crossRef REST API', function () { return server.query('10.4271/2015-01-0821').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Simulating a Complete Performance Map of an Ethanol-Fueled Boosted HCCI Engine'); assert.deepEqual(res.body[0].date, '2015-04-14'); // null date in crossRef assert.deepEqual(!!res.body[0].author, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'conferencePaper'); }); }); it('PMCID but no PMID', function () { return server.query('PMC2096233', 'mediawiki', 'en', 'true').then(function (res) { assert.status(res, 200); assert.deepEqual(!!res.body[0].PMCID, true, '2096233'); assert.deepEqual(res.body[0].PMID, undefined, 'PMID is null'); }); }); // Unable to scrape and ends up with crossRef data it('DOI with redirect - Wiley', function () { return server.query('10.1029/94WR00436').then(function (res) { assert.checkCitation(res, 'A distributed hydrology-vegetation model for complex terrain'); assert.deepEqual(res.body[0].publicationTitle, 'Water Resources Research', 'Incorrect publicationTitle; Expected "Water Resources Research", got' + res.body[0].publicationTitle); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); }); }); }); });
wikimedia/citoid
test/features/scraping/no-zotero.js
JavaScript
apache-2.0
28,920
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint sub: true */ /** * @description The Javascript memory adapter for Aura Storage Service. * @constructor */ var MemoryAdapter = function MemoryAdapter(config) { this.reset(); this.maxSize = config["maxSize"]; this.instanceName = config["name"]; this.debugLoggingEnabled = config["debugLoggingEnabled"]; }; MemoryAdapter.NAME = "memory"; /** * Resets memory objects */ MemoryAdapter.prototype.reset = function() { this.backingStore = {}; this.mru = []; this.cachedSize = 0; }; /** * Returns the name of memory adapter, "memory". * @returns {String} the name of this adapter ("memory") */ MemoryAdapter.prototype.getName = function() { return MemoryAdapter.NAME; }; /** * Returns an approximate size of the storage. * @returns {Promise} a promise that resolves with the size. */ MemoryAdapter.prototype.getSize = function() { return Promise["resolve"](this.cachedSize); }; /** * Gets item from storage. * @param {String} key storage key of item to retrieve. * @return {Promise} a promise that resolves with the item or null if not found. */ MemoryAdapter.prototype.getItem = function(key) { var that = this; return new Promise(function(success) { var value = that.backingStore[key]; if (!$A.util.isUndefinedOrNull(value)) { // Update the MRU that.updateMRU(key); success(value.getItem()); } else { success(); } }); }; /** * Gets all items from storage. * @returns {Promise} a promise that resolves with an array of all items in storage. */ MemoryAdapter.prototype.getAll = function() { var that = this; return new Promise(function(success) { var store = that.backingStore; var values = []; var value, innerValue; for (var key in store) { if (store.hasOwnProperty(key)) { value = store[key]; if (!$A.util.isUndefinedOrNull(value)) { innerValue = value.getItem(); values.push({ "key": key, "value": innerValue["value"], "expires": innerValue["expires"] }); that.updateMRU(key); } } } success(values); }); }; /** * Updates a key in the most recently used list. * @param {String} key the key to update */ MemoryAdapter.prototype.updateMRU = function(key) { var index = this.mru.indexOf(key); if (index > -1) { this.mru.splice(index, 1); this.mru.push(key); } }; /** * Stores item into storage. * @param {String} key key for item * @param {*} item item item to store * @param {Number} size of item value * @returns {Promise} a promise that resolves when the item is stored. */ MemoryAdapter.prototype.setItem = function(key, item, size) { var that = this; return new Promise(function(success) { // existing item ? var existingItem = that.backingStore[key], existingItemSize = 0; if (!$A.util.isUndefinedOrNull(existingItem)) { existingItemSize = existingItem.getSize(); } var itemSize = size - existingItemSize, spaceNeeded = itemSize + that.cachedSize - that.maxSize; that.backingStore[key] = new MemoryAdapter.Entry(item, size); // Update the MRU var index = that.mru.indexOf(key); if (index > -1) { that.mru.splice(index, 1); } that.mru.push(key); that.cachedSize += itemSize; // async evict that.evict(spaceNeeded) .then(undefined, function(error) { $A.warning("Failed to evict items from storage: " + error); }); success(); }); }; /** * Removes an item from storage. * @param {String} key the key of the item to remove. * @return {Promise} a promise that resolves with the removed object or null if the item was not found. */ MemoryAdapter.prototype.removeItem = function(key) { var that = this; return new Promise(function(success) { // Update the MRU var value = that.backingStore[key]; if (!$A.util.isUndefinedOrNull(value)) { var index = that.mru.indexOf(key); if (index >= 0) { that.mru.splice(index, 1); } // adjust actual size that.cachedSize -= value.getSize(); delete that.backingStore[key]; } success(value); }); }; /** * Clears storage. * @returns {Promise} a promise that resolves when clearing is complete. */ MemoryAdapter.prototype.clear = function() { var that = this; return new Promise(function(success) { that.reset(); success(); }); }; /** * Returns currently expired items. * @returns {Promise} a promise that resolves with an array of expired items */ MemoryAdapter.prototype.getExpired = function() { var that = this; return new Promise(function(success) { var now = new Date().getTime(); var expired = []; for (var key in that.backingStore) { var expires = that.backingStore[key].getItem()["expires"]; if (now > expires) { expired.push(key); } } success(expired); }); }; /** * Removes items using an LRU algorithm until the requested space is freed. * @param {Number} spaceNeeded The amount of space to free. * @returns {Promise} a promise that resolves when the requested space is freed. */ MemoryAdapter.prototype.evict = function(spaceNeeded) { var that = this; var spaceReclaimed = 0; return new Promise(function(success, reject) { if (spaceReclaimed > spaceNeeded || that.mru.length <= 0) { success(); return; } var pop = function() { var key = that.mru[0]; that.removeItem(key) .then(function(itemRemoved) { spaceReclaimed += itemRemoved.getSize(); if (that.debugLoggingEnabled) { var msg = ["evicted", key, itemRemoved, spaceReclaimed].join(" "); that.log(msg); } if(spaceReclaimed > spaceNeeded || that.mru.length <= 0) { success(); } else { pop(); } })["catch"](function(error) { reject(error); }); }; pop(); }); }; /** * Gets the most-recently-used list. * @returns {Promise} a promise that results with the an array of keys representing the MRU. */ MemoryAdapter.prototype.getMRU = function() { return Promise["resolve"](this.mru); }; /** * Log message if debug logging is enabled */ MemoryAdapter.prototype.log = function(msg, obj) { if (this.debugLoggingEnabled) { $A.log("MemoryAdapter '" + this.instanceName + "' " + msg + ":", obj); } }; /** * Removes expired items * @returns {Promise} when sweep completes */ MemoryAdapter.prototype.sweep = function() { var that = this; return this.getExpired().then(function (expired) { // note: expired includes any key prefix. and it may // include items with different key prefixes which // we want to expire first. thus remove directly from the // adapter to avoid re-adding the key prefix. if (expired.length === 0) { return; } var promiseSet = []; var key; for (var n = 0; n < expired.length; n++) { key = expired[n]; that.log("sweep() - expiring item with key: " + key); promiseSet.push(that.removeItem(key)); } // When all of the remove promises have completed... return Promise.all(promiseSet).then( //eslint-disable-line consistent-return function () { that.log("sweep() - complete"); }, function (err) { that.log("Error while sweep() was removing items: " + err); } ); }); }; /** * delete storage simply resets memory object */ MemoryAdapter.prototype.deleteStorage = function() { this.reset(); return Promise["resolve"](); }; /** * @description A cache entry in the backing store of the MemoryAdapter. * @constructor * @private */ MemoryAdapter.Entry = function Entry(item, size) { this.item = item; this.size = size; }; /** * @returns {Object} the stored item. */ MemoryAdapter.Entry.prototype.getItem = function() { return this.item; }; /** * @returns {Number} the size of the cache entry. */ MemoryAdapter.Entry.prototype.getSize = function() { return this.size; }; $A.storageService.registerAdapter({ "name": MemoryAdapter.NAME, "adapterClass": MemoryAdapter, "secure": true }); Aura.Storage.MemoryAdapter = MemoryAdapter;
DebalinaDey/AuraDevelopDeb
aura-impl/src/main/resources/aura/storage/adapters/MemoryAdapter.js
JavaScript
apache-2.0
9,685
const TextBasedChannel = require('./interfaces/TextBasedChannel'); const Constants = require('../util/Constants'); const { Presence } = require('./Presence'); const UserProfile = require('./UserProfile'); const Snowflake = require('../util/Snowflake'); const { Error } = require('../errors'); /** * Represents a user on Discord. * @implements {TextBasedChannel} */ class User { constructor(client, data) { /** * The client that created the instance of the user * @name User#client * @type {Client} * @readonly */ Object.defineProperty(this, 'client', { value: client }); if (data) this.setup(data); } setup(data) { /** * The ID of the user * @type {Snowflake} */ this.id = data.id; /** * The username of the user * @type {string} */ this.username = data.username; /** * A discriminator based on username for the user * @type {string} */ this.discriminator = data.discriminator; /** * The ID of the user's avatar * @type {string} */ this.avatar = data.avatar; /** * Whether or not the user is a bot * @type {boolean} */ this.bot = Boolean(data.bot); /** * The ID of the last message sent by the user, if one was sent * @type {?Snowflake} */ this.lastMessageID = null; /** * The Message object of the last message sent by the user, if one was sent * @type {?Message} */ this.lastMessage = null; } patch(data) { for (const prop of ['id', 'username', 'discriminator', 'avatar', 'bot']) { if (typeof data[prop] !== 'undefined') this[prop] = data[prop]; } if (data.token) this.client.token = data.token; } /** * The timestamp the user was created at * @type {number} * @readonly */ get createdTimestamp() { return Snowflake.deconstruct(this.id).timestamp; } /** * The time the user was created * @type {Date} * @readonly */ get createdAt() { return new Date(this.createdTimestamp); } /** * The presence of this user * @type {Presence} * @readonly */ get presence() { if (this.client.presences.has(this.id)) return this.client.presences.get(this.id); for (const guild of this.client.guilds.values()) { if (guild.presences.has(this.id)) return guild.presences.get(this.id); } return new Presence(); } /** * A link to the user's avatar * @param {Object} [options={}] Options for the avatar url * @param {string} [options.format='webp'] One of `webp`, `png`, `jpg`, `gif`. If no format is provided, * it will be `gif` for animated avatars or otherwise `webp` * @param {number} [options.size=128] One of `128`, `256`, `512`, `1024`, `2048` * @returns {?string} */ avatarURL({ format, size } = {}) { if (!this.avatar) return null; return Constants.Endpoints.CDN(this.client.options.http.cdn).Avatar(this.id, this.avatar, format, size); } /** * A link to the user's default avatar * @type {string} * @readonly */ get defaultAvatarURL() { return Constants.Endpoints.CDN(this.client.options.http.cdn).DefaultAvatar(this.discriminator % 5); } /** * A link to the user's avatar if they have one. Otherwise a link to their default avatar will be returned * @param {Object} [options={}] Options for the avatar url * @param {string} [options.format='webp'] One of `webp`, `png`, `jpg`, `gif`. If no format is provided, * it will be `gif` for animated avatars or otherwise `webp` * @param {number} [options.size=128] One of `128`, '256', `512`, `1024`, `2048` * @returns {string} */ displayAvatarURL(options) { return this.avatarURL(options) || this.defaultAvatarURL; } /** * The Discord "tag" for this user * @type {string} * @readonly */ get tag() { return `${this.username}#${this.discriminator}`; } /** * The note that is set for the user * <warn>This is only available when using a user account.</warn> * @type {?string} * @readonly */ get note() { return this.client.user.notes.get(this.id) || null; } /** * Check whether the user is typing in a channel. * @param {ChannelResolvable} channel The channel to check in * @returns {boolean} */ typingIn(channel) { channel = this.client.resolver.resolveChannel(channel); return channel._typing.has(this.id); } /** * Get the time that the user started typing. * @param {ChannelResolvable} channel The channel to get the time in * @returns {?Date} */ typingSinceIn(channel) { channel = this.client.resolver.resolveChannel(channel); return channel._typing.has(this.id) ? new Date(channel._typing.get(this.id).since) : null; } /** * Get the amount of time the user has been typing in a channel for (in milliseconds), or -1 if they're not typing. * @param {ChannelResolvable} channel The channel to get the time in * @returns {number} */ typingDurationIn(channel) { channel = this.client.resolver.resolveChannel(channel); return channel._typing.has(this.id) ? channel._typing.get(this.id).elapsedTime : -1; } /** * The DM between the client's user and this user * @type {?DMChannel} * @readonly */ get dmChannel() { return this.client.channels.filter(c => c.type === 'dm').find(c => c.recipient.id === this.id); } /** * Creates a DM channel between the client and the user. * @returns {Promise<DMChannel>} */ createDM() { if (this.dmChannel) return Promise.resolve(this.dmChannel); return this.client.api.users(this.client.user.id).channels.post({ data: { recipient_id: this.id, } }) .then(data => this.client.actions.ChannelCreate.handle(data).channel); } /** * Deletes a DM channel (if one exists) between the client and the user. Resolves with the channel if successful. * @returns {Promise<DMChannel>} */ deleteDM() { if (!this.dmChannel) return Promise.reject(new Error('USER_NO_DMCHANNEL')); return this.client.api.channels(this.dmChannel.id).delete() .then(data => this.client.actions.ChannelDelete.handle(data).channel); } /** * Get the profile of the user. * <warn>This is only available when using a user account.</warn> * @returns {Promise<UserProfile>} */ fetchProfile() { return this.client.api.users(this.id).profile.get().then(data => new UserProfile(this, data)); } /** * Sets a note for the user. * <warn>This is only available when using a user account.</warn> * @param {string} note The note to set for the user * @returns {Promise<User>} */ setNote(note) { return this.client.api.users('@me').notes(this.id).put({ data: { note } }) .then(() => this); } /** * Checks if the user is equal to another. It compares ID, username, discriminator, avatar, and bot flags. * It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties. * @param {User} user User to compare with * @returns {boolean} */ equals(user) { let equal = user && this.id === user.id && this.username === user.username && this.discriminator === user.discriminator && this.avatar === user.avatar && this.bot === Boolean(user.bot); return equal; } /** * When concatenated with a string, this automatically concatenates the user's mention instead of the User object. * @returns {string} * @example * // logs: Hello from <@123456789>! * console.log(`Hello from ${user}!`); */ toString() { return `<@${this.id}>`; } // These are here only for documentation purposes - they are implemented by TextBasedChannel /* eslint-disable no-empty-function */ send() {} } TextBasedChannel.applyToClass(User); module.exports = User;
zajrik/discord.js
src/structures/User.js
JavaScript
apache-2.0
7,871
module.exports = { entry: { app : './app/app.js' }, output: { filename: '[name]_bundle.js', path: './dist' } };
remibantos/jeeshop
admin/src/main/webapp/webpack.config.js
JavaScript
apache-2.0
151
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // global vars var jq = jQuery.noConflict(); // clear out blockUI css, using css class overrides jQuery.blockUI.defaults.css = {}; jQuery.blockUI.defaults.overlayCSS = {}; // script cleanup flag var scriptCleanup; //stickyContent globals var stickyContent; var stickyContentOffset; var currentHeaderHeight = 0; var currentFooterHeight = 0; var stickyFooterContent; var applicationFooter; // validation init var pageValidatorReady = false; var validateClient = true; var messageSummariesShown = false; var pauseTooltipDisplay = false; var haltValidationMessaging = false; var pageValidationPhase = false; var gAutoFocus = false; var clientErrorStorage = new Object(); var summaryTextExistence = new Object(); var clientErrorExistsCheck = false; var skipPageSetup = false; var groupValidationDefaults; var fieldValidationDefaults; // Action option defaults var actionDefaults; // dirty form state management var dirtyFormState; // view state var initialViewLoad = false; var originalPageTitle; var errorImage; var errorGreyImage; var warningImage; var infoImage; var detailsOpenImage; var detailsCloseImage; var refreshImage; var navigationImage; var ajaxReturnHandlers = {}; var activeDialogId; var sessionWarningTimer; var sessionTimeoutTimer; // delay function var delay = (function () { var timer = 0; return function (callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); // map of componentIds and refreshTimers var refreshTimerComponentMap = {}; // setup handler for opening form content popups with errors jQuery(document).on(kradVariables.PAGE_LOAD_EVENT, function (event) { openPopoverContentsWithErrors(); }); // common event registering done here through JQuery ready event jQuery(document).ready(function () { time(true, "viewSetup-phase-1"); // mark initial view load initialViewLoad = true; // determine whether we need to refresh or update the page skipPageSetup = handlePageAndCacheRefreshing(); dirtyFormState = new DirtyFormState(); // script cleanup setting scriptCleanup = getConfigParam("scriptCleanup").toLowerCase() === "true"; // buttons jQuery("input:submit, input:button, a.button, .uif-dialogButtons").button(); jQuery(".uif-dialogButtons").next('label').addClass('uif-primaryDialogButton'); // common ajax setup jQuery.ajaxSetup({ error: function (jqXHR, textStatus, errorThrown) { showGrowl(getMessage(kradVariables.MESSAGE_STATUS_ERROR, null, null, textStatus, errorThrown), getMessage(kradVariables.MESSAGE_SERVER_RESPONSE_ERROR), 'errorGrowl'); }, complete: function (jqXHR, textStatus) { resetSessionTimers(); }, statusCode: {403: function (jqXHR, textStatus) { handleAjaxSessionTimeout(jqXHR.responseText); }} }); // stop previous loading message hideLoading(); // hide the ajax progress display screen if the page is replaced e.g. by a login page when the session expires jQuery(window).unload(function () { hideLoading(); }); time(false, "viewSetup-phase-1"); // show the page jQuery("#" + kradVariables.APP_ID).show(); // run all the scripts runHiddenScripts(""); time(true, "viewSetup-phase-2"); // setup dirty field processing dirtyFormState.dirtyHandlerSetup(); // handler is for catching a fancybox close and re-enabling dirty checks because main use of fancybox is for // lookup dialogs which turn them off temporarily jQuery(document).on("afterClose.fancybox", function () { dirtyFormState.skipDirtyChecks = false; }); // disclosure handler setup setupDisclosureHandler(); setupHelperTextHandler(); // setup document level handling of drag and drop for files setupFileDragHandlers(); // setup the various event handlers for fields - THIS IS IMPORTANT initFieldHandlers(); jQuery(window).unbind("resize.tooltip"); jQuery(window).bind("resize.tooltip", function () { var visibleTooltips = jQuery(".popover:visible"); visibleTooltips.each(function () { // bug with popover plugin does not reposition tooltip on window resize, forcing it here jQuery(this).prev("[data-hasTooltip]").popover("show"); }); }); // setup the handler for inline field editing initInlineEditFields(); // setup the handler for enter key event actions initEnterKeyHandler(); // setup any potential sticky/fixed content setupStickyHeaderAndFooter(); hideEmptyCells(); jQuery(document).on(kradVariables.PAGE_LOAD_EVENT, function () { initialViewLoad = false; }); time(false, "viewSetup-phase-2"); }); /** * Sets up and initializes the handlers for enter key actions. * * <p>This function determines which button/action should fire when the enter key is pressed while focus is on a configured input</p> * */ function initEnterKeyHandler() { jQuery(document).on("keyup", "[data-enter_key]", function (event) { // grab the keycode based on browser var keycode = (event.keyCode ? event.keyCode : event.which); // check for enter key if (keycode !== 13) { return; } event.preventDefault(); event.stopPropagation(); // using event bubbling, we search for inner most element with data attribute kradVariables.ENTER_KEY_SUFFIX and assign it's value as an ID var enterKeyId = jQuery(event.currentTarget).data(kradVariables.ENTER_KEY_SUFFIX); // make sure the targeted action is a permitted element if (jQuery(event.target).is(":not(a, button, submit, img[data-role='" + kradVariables.DATA_ROLES.ACTION + "'], input[data-role='" + kradVariables.DATA_ROLES.ACTION + "'] )")) { // check to see if primary enter key action button is targeted if (enterKeyId === kradVariables.ENTER_KEY_DEFAULT) { // find all primary action buttons on page with attribute data-default_enter_key_action='true' var primaryButtons = jQuery(event.currentTarget).find("[data-default_enter_key_action='true']"); // filter the buttons only one parent section deep var primaryButton = primaryButtons.filter(function () { return jQuery(this).parents('[data-enter_key]').length < 2; }); // if the button exists get it's id if (primaryButton.length) { enterKeyId = primaryButton.attr("id"); } } // if enterKeyAction is still set to ENTER_KEY_PRIMARY value, do nothing, button doesn't exist if (enterKeyId === kradVariables.ENTER_KEY_DEFAULT) { return false; } // make sure action button is visible and not disabled before we fire it if (jQuery('#' + enterKeyId).is(":visible") && jQuery('#' + enterKeyId).is(":disabled") === false) { jQuery(document).find('#' + enterKeyId).click(); } } }); // a hack to capture the native browser enter key behavior.. keydown and keyup jQuery(document).on("keydown", "[data-enter_key], [data-inline_edit] [data-role='Control']", function (event) { // grab the keycode based on browser var keycode = (event.keyCode ? event.keyCode : event.which); // check for enter key if (keycode === 13 && jQuery(event.target).is("[data-role='Control']")) { event.preventDefault(); return false; } }); } /** * Sets up and initializes the handlers for sticky header and footer content */ function setupStickyHeaderAndFooter() { // sticky(header) content variables must be initialized here to retain sticky location across page request stickyContent = jQuery("[data-sticky='true']:visible"); if (stickyContent.length) { stickyContent.each(function () { jQuery(this).data("offset", jQuery(this).offset()); }); stickyContentOffset = stickyContent.offset(); initStickyContent(); } // find and initialize stickyFooters stickyFooterContent = jQuery("[data-sticky_footer='true']:visible"); applicationFooter = jQuery("#" + kradVariables.APPLICATION_FOOTER_WRAPPER); initStickyFooterContent(); // bind scroll and resize events to dynamically update sticky content positions jQuery(window).unbind("scroll.sticky"); jQuery(window).bind("scroll.sticky", function () { handleStickyContent(); handleStickyFooterContent(); }); jQuery(window).unbind("resize.sticky"); jQuery(window).bind("resize.sticky", function () { handleStickyContent(); handleStickyFooterContent(); }); } /** * Sets up the various handlers for various field controls. * This function includes handlers that are critical to the behavior of KRAD validation and message frameworks * on the client */ function initFieldHandlers() { time(true, "field-handlers"); // add global action handler jQuery(document).on("click", "a[data-role='Action'], button[data-role='Action'], " + "img[data-role='Action'], input[data-role='Action']", function (e) { e.preventDefault(); var action = jQuery(this); // Disabled check if (action.hasClass(kradVariables.DISABLED_CLASS)) { return false; } initActionData(action); // Dirty check (if enabled) if (action.data(kradVariables.PERFORM_DIRTY_VALIDATION) === true && dirtyFormState.checkDirty(e)) { return; } var functionData = action.data(kradVariables.ACTION_ONCLICK_DATA); eval("var actionFunction = function(e) {" + functionData + "};"); return actionFunction.call(this, e); }); // add a focus handler for scroll manipulation when there is a sticky header or footer, so content stays in view jQuery("[data-role='Page']").on("focus", "a[href], area[href], input:not([disabled]), " + "select:not([disabled]), textarea:not([disabled]), button:not([disabled]), " + "iframe, object, embed, *[tabindex], *[contenteditable]", function () { var element = jQuery(this); var buffer = 10; var elementHeight = element.outerHeight(); if (!elementHeight) { elementHeight = 24; } // if something is focused under the footer, adjust the scroll if (stickyFooterContent && stickyFooterContent.length) { var footerOffset = stickyFooterContent.offset().top; if (element.offset().top + elementHeight > footerOffset) { var visibleContentSize = jQuery(window).height() - currentHeaderHeight - currentFooterHeight; jQuery(document).scrollTo(element.offset().top + elementHeight + buffer - currentHeaderHeight - visibleContentSize); return true; } } // if something is focused under the header content, adjust the scroll if (stickyContent && stickyContent.length) { var reversedStickyContent = jQuery(stickyContent.get().reverse()); var headerOffset = reversedStickyContent.offset().top + reversedStickyContent.outerHeight(); if (element.offset().top < headerOffset) { jQuery(document).scrollTo(element.offset().top - currentHeaderHeight - buffer); return true; } } return true; }); jQuery(document).on("mouseenter", "div[data-role='InputField'] input:not([type='image'])," + "div[data-role='InputField'] fieldset, " + "div[data-role='InputField'] fieldset > span > input:radio," + "div[data-role='InputField'] fieldset > span > input:checkbox," + "div[data-role='InputField'] fieldset > span > label, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea", function (event) { var fieldId = jQuery(this).closest("div[data-role='InputField']").attr("id"); var data = getValidationData(jQuery("#" + fieldId)); if (data && data.useTooltip) { var elementInfo = getHoverElement(fieldId); var element = elementInfo.element; var tooltipElement = this; var focus = jQuery(tooltipElement).is(":focus"); if (elementInfo.type == "fieldset") { // for checkbox/radio fieldsets we put the tooltip on the label of the first input tooltipElement = jQuery(element).filter(".uif-tooltip"); // if the fieldset or one of the inputs have focus then the fieldset is considered focused focus = jQuery(element).filter("fieldset").is(":focus") || jQuery(element).filter("input").is(":focus"); } var hasMessages = jQuery("[data-messages_for='" + fieldId + "']").children().length; // only display the tooltip if not already focused or already showing if (!focus && hasMessages) { showMessageTooltip(fieldId); } } }); jQuery(document).on("mouseleave", "div[data-role='InputField'] input," + "div[data-role='InputField'] fieldset, " + "div[data-role='InputField'] fieldset > span > input:radio," + "div[data-role='InputField'] fieldset > span > input:checkbox," + "div[data-role='InputField'] fieldset > span > label, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea", function (event) { var fieldId = jQuery(this).closest("div[data-role='InputField']").attr("id"); var data = getValidationData(jQuery("#" + fieldId)); if (data && data.useTooltip) { var elementInfo = getHoverElement(fieldId); var element = elementInfo.element; var tooltipElement = this; var focus = jQuery(tooltipElement).is(":focus"); if (elementInfo.type == "fieldset") { // for checkbox/radio fieldsets we put the tooltip on the label of the first input tooltipElement = jQuery(element).filter(".uif-tooltip"); // if the fieldset or one of the inputs have focus then the fieldset is considered focused focus = jQuery(element).filter("fieldset").is(":focus") || jQuery(element).filter("input").is(":focus"); } if (!focus) { hideMessageTooltip(fieldId); } } }); // when these fields are focus store what the current errors are if any and show the messageTooltip jQuery(document).on("focus", "div[data-role='InputField'] input:text, " + "div[data-role='InputField'] input:password, " + "div[data-role='InputField'] input:file, " + "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio," + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea, " + "div[data-role='InputField'] option", function () { var id = getAttributeId(jQuery(this).attr('id')); if (!id) { return; } // keep track of what errors it had on initial focus var data = getValidationData(jQuery("#" + id)); if (data && data.errors) { data.focusedErrors = data.errors; } //show tooltip on focus showMessageTooltip(id, false); }); // when these fields are focused out validate and if this field never had an error before, show and close, otherwise // immediately close the tooltip jQuery(document).on("focusout", "div[data-role='InputField'] input:text, " + "div[data-role='InputField'] input:password, " + "div[data-role='InputField'] input:file, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea", function (event) { var id = getAttributeId(jQuery(this).attr('id')); if (!id || isRelatedTarget(this.parentElement, event) === true) { return; } var data = getValidationData(jQuery("#" + id)); var hadError = false; if (data && data.focusedErrors) { hadError = data.focusedErrors.length; } var valid = true; if (validateClient) { valid = validateFieldValue(this); } // mouse in tooltip check var mouseInTooltip = false; if (data && data.useTooltip && data.mouseInTooltip) { mouseInTooltip = data.mouseInTooltip; } if (!hadError && !valid) { // never had a client error before, so pop-up and delay showMessageTooltip(id, true, true); } else if (!mouseInTooltip) { hideMessageTooltip(id); } }); // when these fields are changed validate immediately jQuery(document).on("change", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio, " + "div[data-role='InputField'] select", function () { if (validateClient) { validateFieldValue(this); } }); // Greying out functionality jQuery(document).on("change", "div[data-role='InputField'] input:text, " + "div[data-role='InputField'] input:password, " + "div[data-role='InputField'] input:file, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea, " + "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio", function () { var id = getAttributeId(jQuery(this).attr('id')); if (!id) { return; } var field = jQuery("#" + id); var data = getValidationData(field); if (data) { data.fieldModified = true; field.data(kradVariables.VALIDATION_MESSAGES, data); } }); // special radio and checkbox control handling for click events jQuery(document).on("click", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio," + "fieldset[data-type='CheckboxSet'] span > label," + "fieldset[data-type='RadioSet'] span > label", function () { var event = jQuery.Event("handleFieldsetMessages"); event.element = this; //fire the handleFieldsetMessages event on every input of checkbox or radio fieldset jQuery("fieldset > span > input").not(this).trigger(event); }); // special radio and checkbox control handling for focus events jQuery(document).on("focus", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio", function () { var event = jQuery.Event("handleFieldsetMessages"); event.element = this; //fire the handleFieldsetMessages event on every input of checkbox or radio fieldset jQuery("fieldset > span > input").not(this).trigger(event); }); // when focused out the checkbox and radio controls that are part of a fieldset will check if another control in // their fieldset has received focus after a short period of time, otherwise the tooltip will close. // if not part of the fieldset, the closing behavior is similar to normal fields // in both cases, validation occurs when the field is considered to have lost focus (fieldset case - no control // in the fieldset has focus) jQuery(document).on("focusout", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio", function () { var parent = jQuery(this).parent(); var id = getAttributeId(jQuery(this).attr('id')); if (!id) { return; } var data = getValidationData(jQuery("#" + id)); //mouse in tooltip check var mouseInTooltip = false; if (data && data.useTooltip && data.mouseInTooltip) { mouseInTooltip = data.mouseInTooltip; } //radio/checkbox is in fieldset case if (parent.parent().is("fieldset")) { // we only ever want this to be handled once per attachment jQuery(this).one("handleFieldsetMessages", function (event) { var proceed = true; // if the element that invoked the event is part of THIS fieldset, we do not lose focus, so // do not proceed with close handling if (event.element && jQuery(event.element).is(jQuery(this).closest("fieldset").find("input"))) { proceed = false; } // the fieldset is focused out - proceed if (proceed) { var hadError = parent.parent().find("input").hasClass("error"); var valid = true; if (validateClient) { valid = validateFieldValue(this); } if (!hadError && !valid) { //never had a client error before, so pop-up and delay close showMessageTooltip(id, true, true); } else if (!mouseInTooltip) { hideMessageTooltip(id); } } }); var currentElement = this; // if no radios/checkboxes are reporting events assume we want to proceed with closing the message setTimeout(function () { var event = jQuery.Event("handleFieldsetMessages"); event.element = []; jQuery(currentElement).trigger(event); }, 500); } // non-fieldset case else if (!jQuery(this).parent().parent().is("fieldset")) { var hadError = jQuery(this).hasClass("error"); var valid = true; // not in a fieldset - so validate directly if (validateClient) { valid = validateFieldValue(this); } if (!hadError && !valid) { // never had a client error before, so pop-up and delay showMessageTooltip(id, true, true); } else if (!mouseInTooltip) { hideMessageTooltip(id); } } }); jQuery(document).on("change", "table.dataTable div[data-role='InputField'][data-total='change'] :input", function () { refreshDatatableCellRedraw(this); }); jQuery(document).on("input", "table.dataTable div[data-role='InputField'][data-total='keyup'] :input", function () { var input = this; delay(function () { refreshDatatableCellRedraw(input) }, 300); }); // capture tabbing through widget elements to make sure we only validate the control field when we leave the entire // widget var buttonHovered = false; var $currentControl; // capture mousing over button of the widget if there is one jQuery(document).on("mouseover", "div[data-role='InputField'] div.input-group div.input-group-btn a",function () { buttonHovered = true; // capture mousing out of button in the widget }).on("mouseout", "div[data-role='InputField'] div.input-group div.input-group-btn a",function () { buttonHovered = false; // capture leaving the control field }).on("focusout", "div[data-role='InputField'] div.input-group", function (event) { $currentControl = jQuery(this).children("[data-role='Control']"); // determine whether we are still in the widget. If we are out of the widget and the field // is not a radio button, then validate var radioButtons = jQuery(this).find('input:radio'); if (isRelatedTarget(this, event) !== true && buttonHovered === false && radioButtons.length == 0) { validateFieldValue($currentControl); } }); // capture datepicker widget button jQuery(document).on("mouseover", ".ui-datepicker",function () { buttonHovered = true; }).on("mouseout", ".ui-datepicker", function () { buttonHovered = false; }); // capture leaving a text expand window and force focus back on the control jQuery(document).on("focusout", ".fancybox-skin", function () { buttonHovered = false; $currentControl.focus(); }); time(false, "field-handlers"); } /** * Test if an input field is part of a widget by examining event.currentTarget and event.target * */ function isRelatedTarget(element, event) { if (!event) return true; try { // test for lightbox widget by matching a fancy-box event property for (var key in event.currentTarget) { if (key.match(/fancy/g) && key !== undefined) { console.log(key); return true; } } // here we check to see if the element we are focusing out of is nested in a input-group div or within // input-group-btn div. If so then they are related to the widget if (("relatedTarget" in event && event.relatedTarget !== null && element === event.relatedTarget.parentElement.parentElement) || ("relatedTarget" in event && event.relatedTarget !== null && element === event.relatedTarget.parentElement) ) { return true; } return false; } catch (e) { return false; } } /** * Setup a global disclosure handler which will handle click events on disclosure links to toggle them open and closed */ function setupDisclosureHandler() { jQuery(document).on("click", "a[data-role='" + kradVariables.DATA_ROLES.DISCLOSURE_LINK + "']", function (event) { event.preventDefault(); var link = jQuery(this); var disclosureContent = jQuery("#" + link.data("linkfor")); var isOpen = disclosureContent.attr(kradVariables.ATTRIBUTES.DATA_OPEN); var animationSpeed = link.data("speed"); var linkId = link.attr("id"); var widgetId = link.data("widgetid"); var ajax = link.data("ajax"); if (isOpen == "true") { disclosureContent.attr(kradVariables.ATTRIBUTES.DATA_OPEN, false); var options = { duration: animationSpeed, step: function () { disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); } }; disclosureContent.slideUp(options); link.find("#" + linkId + "_exp").hide(); link.find("#" + linkId + "_col").show(); setComponentState(widgetId, 'open', false); disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); } else { disclosureContent.attr(kradVariables.ATTRIBUTES.DATA_OPEN, true); // run scripts for previously hidden content runHiddenScripts(disclosureContent, true, false); link.find("#" + linkId + "_exp").show(); link.find("#" + linkId + "_col").hide(); setComponentState(widgetId, 'open', true); if (ajax && disclosureContent.data("role") == "placeholder") { // If there is a placeholder present, retrieve the new content showLoading("Loading...", disclosureContent, true); disclosureContent.show(); disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); // This a specialized methodToCall passed in for retrieving the originally generated component retrieveComponent(linkId.replace("_toggle", ""), null, null, null, true); } else { // If no ajax retrieval, slide down animationg var options = { duration: animationSpeed, step: function () { disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); } }; disclosureContent.slideDown(options); } } }); } /** * Sets up focus and blur events for inputs with helper text. */ function setupHelperTextHandler() { jQuery(document).on(kradVariables.EVENTS.UPDATE_CONTENT + " ready", function () { if (jQuery('.uif-helperText').length) { jQuery('.uif-helperText').slideUp(); } jQuery('.has-helper').on('focus', function () { if (jQuery(this).parent().find('.uif-helperText')) { jQuery(this).parent().find('.uif-helperText').slideDown(); } }); jQuery('.has-helper').on('blur', function () { if (jQuery(this).parent().find('.uif-helperText')) { jQuery(this).parent().find('.uif-helperText').slideUp(); } }); }); } /** * Setup document level dragover, drop, and dragleave events to handle file drops and indication when dropping a * file into appropriate elements */ function setupFileDragHandlers() { // Prevent drag and drop events on the document to support file drags into upload widget jQuery(document).on("dragover", function (e) { e.preventDefault(); var $fileCollections = jQuery(".uif-fileUploadCollection"); $fileCollections.each(function () { var $fileCollection = jQuery(this); var id = $fileCollection.attr("id"); var drop = $fileCollection.find(".uif-drop"); if (!drop.length) { drop = jQuery("<div class='uif-drop uif-dropBlock'></div>"); drop = drop.add("<span class='uif-drop uif-dropText'><span class='icon-plus'/> Drop Files to Add...</span>"); drop.bind("drop", function () { e.preventDefault(); jQuery("#" + id).trigger("drop"); jQuery(this).hide(); }); $fileCollection.append(drop); } else { drop.show(); } }); }); jQuery(document).on("drop dragleave", function (e) { e.preventDefault(); var fileCollections = jQuery(".uif-drop"); fileCollections.each(function () { jQuery(this).hide(); }); }); } function hideTooltips(element) { if (element != undefined && element.length) { jQuery(element).find("[data-hasTooltip]").popover("hide"); } else { jQuery("[data-hasTooltip]").popover("hide"); } } /** * Sets up the validator and the dirty check and other page scripts */ function setupPage(validate) { time(true, "page-setup"); dirtyFormState.resetDirtyFieldCount(); // if we are skipping this page setup, reset the flag, and return (this logic is for redirects) if (skipPageSetup) { skipPageSetup = false; return; } // update the top group per page var topGroupUpdateDiv = jQuery("#" + kradVariables.TOP_GROUP_UPDATE); var topGroupUpdate = topGroupUpdateDiv.find(">").detach(); if (topGroupUpdate.length && !initialViewLoad) { jQuery("#Uif-TopGroupWrapper >").replaceWith(topGroupUpdate); } topGroupUpdateDiv.remove(); // update the view header per page var headerUpdateDiv = jQuery("#" + kradVariables.VIEW_HEADER_UPDATE); var viewHeaderUpdate = headerUpdateDiv.find(".uif-viewHeader").detach(); if (viewHeaderUpdate.length && !initialViewLoad) { var currentHeader = jQuery(".uif-viewHeader"); if (currentHeader.data("offset")) { viewHeaderUpdate.data("offset", currentHeader.data("offset")); } jQuery(".uif-viewHeader").replaceWith(viewHeaderUpdate); stickyContent = jQuery("[data-sticky='true']:visible"); } headerUpdateDiv.remove(); originalPageTitle = document.title; setupImages(); // reinitialize sticky footer content because page footer can be sticky jQuery(document).on(kradVariables.EVENTS.ADJUST_STICKY, function () { stickyFooterContent = jQuery("[data-sticky_footer='true']"); initStickyFooterContent(); handleStickyFooterContent(); initStickyContent(); }); // Initialize global validation defaults if (groupValidationDefaults == undefined || fieldValidationDefaults == undefined) { groupValidationDefaults = jQuery("[data-role='View']").data(kradVariables.GROUP_VALIDATION_DEFAULTS); fieldValidationDefaults = jQuery("[data-role='View']").data(kradVariables.FIELD_VALIDATION_DEFAULTS); } if (actionDefaults == undefined) { actionDefaults = jQuery("[data-role='View']").data(kradVariables.ACTION_DEFAULTS); } // Reset summary state before processing each field - summaries are shown if server messages // or on client page validation messageSummariesShown = false; // flag to turn off and on validation mechanisms on the client validateClient = validate; // select current page var pageId = getCurrentPageId(); // update URL to reflect the current page updateRequestUrl(pageId); prevPageMessageTotal = 0; var page = jQuery("[data-role='Page']"); // skip input field iteration and validation message writing, if no server messages var hasServerMessagesData = page.data(kradVariables.SERVER_MESSAGES); if (hasServerMessagesData) { pageValidationPhase = true; // Handle messages at field, if any jQuery("div[data-role='InputField']").each(function () { var id = jQuery(this).attr('id'); handleMessagesAtField(id, true); }); // Write the result of the validation messages writeMessagesForPage(); messageSummariesShown = true; pageValidationPhase = false; } //TODO: Looks like this class is not being used anywhere - Remove? // focus on pageValidation header if there are messages on this page if (jQuery(".uif-pageValidationHeader").length) { jQuery(".uif-pageValidationHeader").focus(); } setupValidator(jQuery('#kualiForm')); jQuery(".required").each(function () { jQuery(this).attr("aria-required", "true"); }); jQuery(document).trigger(kradVariables.VALIDATION_SETUP_EVENT); pageValidatorReady = true; jQuery(document).trigger(kradVariables.PAGE_LOAD_EVENT); jQuery.watermark.showAll(); // If no focusId is specified through data attribute, default to FIRST input on the page var focusId = page.data(kradVariables.FOCUS_ID); if (!focusId) { focusId = "FIRST"; } // Perform focus and jumpTo based on the data attributes performFocusAndJumpTo(true, focusId, page.data(kradVariables.JUMP_TO_ID), page.data(kradVariables.JUMP_TO_NAME)); time(false, "page-setup"); } /** * Sets up the validator with the necessary default settings and methods on a form * * @param form */ function setupValidator(form) { jQuery(form).validate(); } /** * Initializes all of the image variables */ function setupImages() { errorImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/error.png' alt='" + getMessage(kradVariables.MESSAGE_ERROR) + "' /> "; errorGreyImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/error-grey.png' alt='" + getMessage(kradVariables.MESSAGE_ERROR_FIELD_MODIFIED) + "' /> "; warningImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/warning.png' alt='" + getMessage(kradVariables.MESSAGE_WARNING) + "' /> "; infoImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/info.png' alt='" + getMessage(kradVariables.MESSAGE_INFORMATION) + "' /> "; detailsOpenImage = jQuery("<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "details_open.png' alt='" + getMessage(kradVariables.MESSAGE_DETAILS) + "' /> "); detailsCloseImage = jQuery("<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "details_close.png' alt='" + getMessage(kradVariables.MESSAGE_CLOSE_DETAILS) + "' /> "); refreshImage = jQuery("<img src='" + getContext().blockUI.defaults.refreshOptions.blockingImage + "' alt='" + getMessage(kradVariables.MESSAGE_LOADING) + "' /> "); navigationImage = jQuery("<img src='" + getContext().blockUI.defaults.navigationOptions.blockingImage + "' alt='" + getMessage(kradVariables.MESSAGE_LOADING) + "' /> "); } /** * Retrieves the value for a configuration parameter * * @param paramName - name of the parameter to retrieve */ function getConfigParam(paramName) { var configParams = jQuery(document).data("ConfigParameters"); if (configParams) { return configParams[paramName]; } return ""; } jQuery.validator.setDefaults({ onsubmit: false, errorClass: kradVariables.ERROR_CLASS, validClass: kradVariables.VALID_CLASS, ignore: "." + kradVariables.IGNORE_VALIDATION_CLASS + ", ." + kradVariables.IGNORE_VALIDATION_TEMP_CLASS, wrapper: "", onfocusout: false, onclick: false, onkeyup: function (element) { if (validateClient) { var id = getAttributeId(jQuery(element).attr('id')); if (!id) { return; } var data = getValidationData(jQuery("#" + id)); // if this field previously had errors validate on key up if (data && data.focusedErrors && data.focusedErrors.length) { var valid = validateFieldValue(element); if (!valid) { showMessageTooltip(id, false, true); } } } }, highlight: function (element, errorClass, validClass) { jQuery(element).addClass(errorClass).removeClass(validClass); jQuery(element).attr("aria-invalid", "true"); }, unhighlight: function (element, errorClass, validClass) { removeClientValidationError(element); }, errorPlacement: function (error, element) { }, showErrors: function (nameErrorMap, elementObjectList) { this.defaultShowErrors(); for (var i in elementObjectList) { var element = elementObjectList[i].element; var message = elementObjectList[i].message; var id = getAttributeId(jQuery(element).attr('id')); if (!id) { return; } var field = jQuery("#" + id); var data = getValidationData(field); var exists = false; if (data && data.errors && data.errors.length) { for (var j in data.errors) { if (data.errors[j] === message) { exists = true; } } } if (!exists) { data.errors = []; data.errors.push(message); field.data(kradVariables.VALIDATION_MESSAGES, data); } if (data) { if (messageSummariesShown) { handleMessagesAtField(id); } else { writeMessagesAtField(id); } } if (data && !exists && !pauseTooltipDisplay) { } } }, success: function (label) { var htmlFor = jQuery(label).attr('for'); var id = ""; if (htmlFor.indexOf("_control") >= 0) { id = getAttributeId(htmlFor); if (!id) { return; } } else { id = jQuery("[name='" + escapeName(htmlFor) + "']:first").attr("id"); id = getAttributeId(id); if (!id) { return; } } var field = jQuery("#" + id); var data = getValidationData(field); if (data && data.errors && data.errors.length) { data.errors = []; field.data(kradVariables.VALIDATION_MESSAGES, data); if (messageSummariesShown) { handleMessagesAtField(id); } else { writeMessagesAtField(id); } showMessageTooltip(id, false, true); } } }); jQuery.validator.addMethod("minExclusive", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || value > param[0]; } else { return true; } }); jQuery.validator.addMethod("maxInclusive", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || value <= param[0]; } else { return true; } }); jQuery.validator.addMethod("minLengthConditional", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || this.getLength(jQuery.trim(value), element) >= param[0]; } else { return true; } }); jQuery.validator.addMethod("maxLengthConditional", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || this.getLength(jQuery.trim(value), element) <= param[0]; } else { return true; } }); /** * a plugin function for sorting values for columns marked with sType:kuali_date in aoColumns in ascending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_date-asc'] = function (a, b) { var date1 = a.split('/'); var date2 = b.split('/'); var x = (date1[2] + date1[0] + date1[1]) * 1; var y = (date2[2] + date2[0] + date2[1]) * 1; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; /** * a plugin function for sorting values for columns marked with sType:kuali_date in aoColumns in descending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_date-desc'] = function (a, b) { var date1 = a.split('/'); var date2 = b.split('/'); var x = (date1[2] + date1[0] + date1[1]) * 1; var y = (date2[2] + date2[0] + date2[1]) * 1; return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }; /** * a plugin function for sorting values for columns marked with sType:kuali_percent in aoColumns in ascending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_percent-asc'] = function (a, b) { var num1 = a.replace(/[^0-9]/g, ''); var num2 = b.replace(/[^0-9]/g, ''); num1 = (num1 == "-" || num1 === "" || isNaN(num1)) ? 0 : num1 * 1; num2 = (num2 == "-" || num2 === "" || isNaN(num2)) ? 0 : num2 * 1; return num1 - num2; }; /** * a plugin function for sorting values for columns marked with sType:kuali_percent in aoColumns in descending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_percent-desc'] = function (a, b) { var num1 = a.replace(/[^0-9]/g, ''); var num2 = b.replace(/[^0-9]/g, ''); num1 = (num1 == "-" || num1 === "" || isNaN(num1)) ? 0 : num1 * 1; num2 = (num2 == "-" || num2 === "" || isNaN(num2)) ? 0 : num2 * 1; return num2 - num1; }; /** * a plugin function for sorting values for columns marked with sType:kuali_currency in aoColumns in ascending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_currency-asc'] = function (a, b) { /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ var x = a == "-" ? 0 : a.replace(/,/g, ""); var y = b == "-" ? 0 : b.replace(/,/g, ""); /* Remove the currency sign */ if (x.charAt(0) == '$') { x = x.substring(1); } if (y.charAt(0) == '$') { y = y.substring(1); } /* Parse and return */ x = parseFloat(x); y = parseFloat(y); x = isNaN(x) ? 0 : x * 1; y = isNaN(y) ? 0 : y * 1; return x - y; }; /** * a plugin function for sorting values for columns marked with sType:kuali_currency in aoColumns in descending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_currency-desc'] = function (a, b) { /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ var x = a == "-" ? 0 : a.replace(/,/g, ""); var y = b == "-" ? 0 : b.replace(/,/g, ""); /* Remove the currency sign */ if (x.charAt(0) == '$') { x = x.substring(1); } if (y.charAt(0) == '$') { y = y.substring(1); } /* Parse and return */ x = parseFloat(x); y = parseFloat(y); x = isNaN(x) ? 0 : x; y = isNaN(y) ? 0 : y; return y - x; }; /** * retrieve column values for sorting a column marked with sSortDataType:dom-text in aoColumns * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-text'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var input = jQuery(td).find('input:text'); var value = ""; if (input.length != 0) { value = input.val(); } else { // check for linkField var linkField = jQuery(td).find('.uif-linkField'); if (linkField.length != 0) { value = linkField.text().trim(); } else { // find span for the data or input field and get its text var inputField = jQuery(td).find('.uif-field'); if (inputField.length != 0) { value = jQuery.trim(inputField.text()); } else { // just use the text within the cell value = jQuery(td).text().trim(); // strip leading $ if present if (value.charAt(0) == '$') { value = value.substring(1); } } } } var additionalDisplaySeparatorIndex = value.indexOf("*-*"); if (additionalDisplaySeparatorIndex != -1) { value = value.substring(0, additionalDisplaySeparatorIndex).trim(); } aData.push(value); }); return aData; } /** * retrieve column values for sorting a column marked with sSortDataType:dom-select in aoColumns * * <p>Create an array with the values of all the select options in a column</p> * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-select'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var selected = jQuery(td).find('select option:selected:first'); if (selected.length != 0) { aData.push(selected.text()); } else { var input1 = jQuery(td).find("[data-role='InputField']"); if (input1.length != 0) { aData.push(jQuery.trim(input1.text())); } else { aData.push(""); } } }); return aData; } /** * retrieve column values for sorting a column marked with sSortDataType:dom-checkbox in aoColumns * * <p>Create an array with the values of all the checkboxes in a column</p> * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-checkbox'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var checkboxes = jQuery(td).find('input:checkbox'); if (checkboxes.length != 0) { var str = ""; for (i = 0; i < checkboxes.length; i++) { var check = checkboxes[i]; if (check.checked == true && check.value.length > 0) { str += check.value + " "; } } aData.push(str); } else { var input1 = jQuery(td).find("[data-role='InputField']"); if (input1.length != 0) { aData.push(jQuery.trim(input1.text())); } else { aData.push(""); } } }); return aData; } /** * retrieve column values for sorting a column marked with sSortDataType:dom-radio in aoColumns * * <p>Create an array with the values of all the radio buttons in a column</p> * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-radio'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var radioButtons = jQuery(td).find('input:radio'); if (radioButtons.length != 0) { var value = ""; for (i = 0; i < radioButtons.length; i++) { var radio = radioButtons[i]; if (radio.checked == true) { value = radio.value; break; } } aData.push(value); } else { var input1 = jQuery(td).find("[data-role='InputField']"); if (input1.length != 0) { aData.push(jQuery.trim(input1.text())); } else { aData.push(""); } } }); return aData; } // setup window javascript error handler window.onerror = errorHandler; function errorHandler(msg, url, lno) { jQuery("#" + kradVariables.APP_ID).show(); jQuery("[data-role='Page']").show(); var context = getContext(); context.unblockUI(); var errorMessage = msg + '<br/>' + url + '<br/>' + lno; showGrowl(errorMessage, 'Javascript Error', 'errorGrowl'); if (window.console) { console.log(errorMessage); } return false; } // script that should execute when the page unloads // jQuery(window).bind('beforeunload', function (evt) { // clear server form if closing the browser tab/window or going back // TODO: work out back button problem so we can add this clearing // if (!event.pageY || (event.pageY < 0)) { // clearServerSideForm(); // } //});
mztaylor/rice-git
rice-framework/krad-web/src/main/webapp/krad/scripts/krad.initialize.js
JavaScript
apache-2.0
59,690
/** * Copyright 2016-2017 IBM 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'; var tape = require('tape'); var _test = require('tape-promise'); var test = _test(tape); var tar = require('tar-fs'); var gunzip = require('gunzip-maybe'); var fs = require('fs-extra'); var grpc = require('grpc'); var _policiesProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/common/policies.proto').common; var _mspPrProto = grpc.load(__dirname + '/../../fabric-client/lib/protos/common/msp_principal.proto').common; var hfc = require('fabric-client'); var testutil = require('./util.js'); var Peer = require('fabric-client/lib/Peer.js'); var Chain = require('fabric-client/lib/Chain.js'); var Packager = require('fabric-client/lib/Packager.js'); var Orderer = require('fabric-client/lib/Orderer.js'); var MSP = require('fabric-client/lib/msp/msp.js'); var MSPManager = require('fabric-client/lib/msp/msp-manager.js'); var idModule = require('fabric-client/lib/msp/identity.js'); var SigningIdentity = idModule.SigningIdentity; var _chain = null; var chainName = 'testChain'; var Client = hfc; var client = new Client(); testutil.resetDefaults(); var utils = require('fabric-client/lib/utils.js'); var logger = utils.getLogger('chain'); // Chain tests ///////////// test('\n\n ** Chain - constructor test **\n\n', function (t) { _chain = new Chain(chainName, client); if (_chain.getName() === chainName) t.pass('Chain constructor test: getName successful'); else t.fail('Chain constructor test: getName not successful'); t.throws( function () { _chain = new Chain(null, client); }, /^Error: Failed to create Chain. Missing requirement "name" parameter./, 'Chain constructor tests: Missing name parameter' ); t.throws( function () { _chain = new Chain(chainName, null); }, /^Error: Failed to create Chain. Missing requirement "clientContext" parameter./, 'Chain constructor tests: Missing clientContext parameter' ); t.end(); }); test('\n\n ** Chain - method tests **\n\n', function (t) { t.equal(_chain.isSecurityEnabled(), true, 'checking security setting'); t.doesNotThrow( function () { _chain.setPreFetchMode(true); }, null, 'checking the set of prefetchMode' ); t.equal(_chain.isPreFetchMode(), true, 'checking prefetchMode'); t.doesNotThrow( function () { _chain.setTCertBatchSize(123); }, null, 'checking the set of TCertBatchSize' ); t.equal(_chain.getTCertBatchSize(), 123, 'checking getTCertBatchSize'); t.doesNotThrow( function () { var orderer = new Orderer('grpc://somehost.com:1234'); _chain.addOrderer(orderer); }, null, 'checking the chain addOrderer()' ); t.equal(_chain.getOrderers()[0].toString(), ' Orderer : {url:grpc://somehost.com:1234}', 'checking chain getOrderers()'); t.throws( function () { var orderer = new Orderer('grpc://somehost.com:1234'); _chain.addOrderer(orderer); }, /^DuplicateOrderer: Orderer with URL/, 'Chain tests: checking that orderer already exists.' ); t.equal(_chain.toString(), '{"name":"testChain","orderers":" Orderer : {url:grpc://somehost.com:1234}|"}', 'checking chain toString'); t.notEquals(_chain.getMSPManager(),null,'checking the chain getMSPManager()'); t.doesNotThrow( function () { var msp_manager = new MSPManager(); _chain.setMSPManager(msp_manager); }, null, 'checking the chain setMSPManager()' ); t.notEquals(_chain.getOrganizationUnits(),null,'checking the chain getOrganizationUnits()'); t.end(); }); test('\n\n ** Chain query tests', function(t) { var peer = new Peer('grpc://localhost:7051'); _chain.addPeer(peer); var test_peer = new Peer('grpc://localhost:7051'); t.throws( function () { _chain.setPrimaryPeer(test_peer); }, /^Error: The primary peer must be on this chain\'s peer list/, 'Not able to set a primary peer even if has the same addresss' ); t.doesNotThrow( function () { _chain.setPrimaryPeer(peer); }, null, 'Able to set a primary peer as long as same peer' ); test_peer = new Peer('grpc://localhost:7099'); t.throws( function () { _chain.setPrimaryPeer(test_peer); }, /^Error: The primary peer must be on this chain\'s peer list/, 'Not Able to set a primary peer when not on the list' ); t.throws( function () { _chain.setPrimaryPeer(); }, /^Error: The primary peer must be on this chain\'s peer list/, 'Not Able to set a primary peer to a null peer' ); _chain.queryBlockByHash() .then( function(results) { t.fail('Error: Blockhash bytes are required'); t.end(); }, function(err) { var errMessage = 'Error: Blockhash bytes are required'; if(err.toString() == errMessage) t.pass(errMessage); else t.fail(errMessage); return _chain.queryTransaction(); } ).then( function(results) { t.fail('Error: Transaction id is required'); t.end(); }, function(err) { t.pass(err); return _chain.queryBlock('a'); } ).then( function(results) { t.fail('Error: block id must be integer'); t.end(); }, function(err) { var errMessage = 'Error: Block number must be a postive integer'; if(err.toString() == errMessage) t.pass(errMessage); else t.fail(errMessage); return _chain.queryBlock(); } ).then( function(results) { t.fail('Error: block id is required'); t.end(); }, function(err) { var errMessage = 'Error: Block number must be a postive integer'; if(err.toString() == errMessage) t.pass(errMessage); else t.fail(errMessage); return _chain.queryBlock(-1); } ).then( function(results) { t.fail('Error: block id must be postive integer'); t.end(); }, function(err) { var errMessage = 'Error: Block number must be a postive integer'; if(err.toString() == errMessage) t.pass(errMessage); else t.fail(errMessage); return _chain.queryBlock(10.5); } ).then( function(results) { t.fail('Error: block id must be integer'); t.end(); }, function(err) { var errMessage = 'Error: Block number must be a postive integer'; if(err.toString() == errMessage) t.pass(errMessage); else t.fail(errMessage); t.end(); } ).catch( function(err) { t.fail('should not have gotten the catch ' + err); t.end(); } ); }); test('\n\n ** Chain addPeer() duplicate tests **\n\n', function (t) { var chain_duplicate = new Chain('chain_duplicate', client); var peers = [ 'grpc://localhost:7051', 'grpc://localhost:7052', 'grpc://localhost:7053', 'grpc://localhost:7051' ]; var expected = peers.length - 1; peers.forEach(function (peer) { try { var _peer = new Peer(peer); chain_duplicate.addPeer(_peer); } catch (err) { if (err.name != 'DuplicatePeer'){ t.fail('Unexpected error ' + err.toString()); } else { t.pass('Expected error message "DuplicatePeer" thrown'); } } }); //check to see we have the correct number of peers if (chain_duplicate.getPeers().length == expected) { t.pass('Duplicate peer not added to the chain(' + expected + ' expected | ' + chain_duplicate.getPeers().length + ' found)'); } else { t.fail('Failed to detect duplicate peer (' + expected + ' expected | ' + chain_duplicate.getPeers().length + ' found)'); } t.end(); }); test('\n\n ** Chain joinChannel() tests **\n\n', function (t) { var c = new Chain('joinChannel', client); var orderer = new Orderer('grpc://localhost:7050'); var p1 = c.getGenesisBlock({} ).then(function () { t.fail('Should not have been able to resolve the promise because of orderer missing'); }).catch(function (err) { if (err.message.indexOf('Missing orderer') >= 0) { t.pass('Successfully caught missing orderer error'); } else { t.fail('Failed to catch the missing orderer error. Error: '); logger.error(err.stack ? err.stack : err); } }); c.addOrderer(orderer); var p2 = c.joinChannel( ).then(function () { t.fail('Should not have been able to resolve the promise because of missing request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing all') >= 0) { t.pass('Successfully caught missing request error'); } else { t.fail('Failed to catch the missing request error. Error: '); logger.error(err.stack ? err.stack : err); } }); var p3 = c.joinChannel({} ).then(function () { t.fail('Should not have been able to resolve the promise because of targets request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing targets') >= 0) { t.pass('Successfully caught missing targets request error'); } else { t.fail('Failed to catch the missing targets request error. Error: '); logger.error(err.stack ? err.stack : err); } }); var p4 = c.joinChannel({targets: 'targets'} ).then(function () { t.fail('Should not have been able to resolve the promise because of txId request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing txId') >= 0) { t.pass('Successfully caught missing txId request error'); } else { t.fail('Failed to catch the missing txId request error. Error: '); logger.error(err.stack ? err.stack : err); } }); var p4a = c.getGenesisBlock({targets: 'targets'} ).then(function () { t.fail('Should not have been able to resolve the promise because of txId request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing txId') >= 0) { t.pass('Successfully caught missing txId request error'); } else { t.fail('Failed to catch the missing txId request error. Error: '); logger.error(err.stack ? err.stack : err); } }); var p5 = c.joinChannel({targets: 'targets' , txId : 'txId' } ).then(function () { t.fail('Should not have been able to resolve the promise because of nonce request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing nonce') >= 0) { t.pass('Successfully caught missing nonce request error'); } else { t.fail('Failed to catch the missing nonce request error. Error: '); logger.error(err.stack ? err.stack : err); } }); var p5a = c.getGenesisBlock({targets: 'targets' , txId : 'txId' } ).then(function () { t.fail('Should not have been able to resolve the promise because of nonce request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing nonce') >= 0) { t.pass('Successfully caught missing nonce request error'); } else { t.fail('Failed to catch the missing nonce request error. Error: '); logger.error(err.stack ? err.stack : err); } }); Promise.all([p1, p2, p3, p4, p4a, p5, p5a]) .then( function (data) { t.end(); } ).catch( function (err) { t.fail('Chain joinChannel() tests, Promise.all: '); logger.error(err.stack ? err.stack : err); t.end(); } ); }); test('\n\n** Packager tests **\n\n', function(t) { Packager.package('blah','',true) .then((data) => { t.equal(data, null, 'Chain.packageChaincode() should return null for dev mode'); return Packager.package(null,'',false); }).then(() => { t.fail('Packager.package() should have rejected a call that does not have chaincodePath parameter'); t.end(); }, (err) => { var msg = 'Missing chaincodePath parameter'; if (err.message.indexOf(msg) >= 0) { t.pass('Should throw error: '+msg); } else { t.fail(err.message+' should be '+msg); t.end(); } testutil.setupChaincodeDeploy(); return Packager.package(testutil.CHAINCODE_PATH,'',false); }).then((data) => { t.comment('Verify byte data begin'); var tmpFile = '/tmp/test-deploy-copy.tar.gz'; var destDir = '/tmp/test-deploy-copy-tar-gz'; fs.writeFileSync(tmpFile, data); fs.removeSync(destDir); var pipe = fs.createReadStream(tmpFile).pipe(gunzip()).pipe(tar.extract(destDir)); pipe.on('close', function() { var checkPath = path.join(destDir, 'src', 'github.com', 'example_cc'); t.equal(fs.existsSync(checkPath), true, 'The tar.gz file produced by Packager.package() has the "src/github.com/example_cc" folder'); t.comment('Verify byte data on close'); }); t.comment('Verify byte data end'); t.end(); }).catch((err) => { t.fail('Caught error in Package.package tests'); t.comment(err.stack ? err.stack : err); t.end(); }); }); var TWO_ORG_MEMBERS_AND_ADMIN = [{ role: { name: 'member', mspId: 'org1' } }, { role: { name: 'member', mspId: 'org2' } }, { role: { name: 'admin', mspId: 'masterOrg' } }]; var ONE_OF_TWO_ORG_MEMBER = { identities: TWO_ORG_MEMBERS_AND_ADMIN, policy: { '1-of': [{ 'signed-by': 0 }, { 'signed-by': 1 }] } }; var TWO_OF_TWO_ORG_MEMBER = { identities: TWO_ORG_MEMBERS_AND_ADMIN, policy: { '2-of': [{ 'signed-by': 0 }, { 'signed-by': 1 }] } }; var ONE_OF_TWO_ORG_MEMBER_AND_ADMIN = { identities: TWO_ORG_MEMBERS_AND_ADMIN, policy: { '2-of': [{ '1-of': [{ 'signed-by': 0 }, { 'signed-by': 1 }] }, { 'signed-by': 2 }] } }; var CRAZY_SPEC = { identities: TWO_ORG_MEMBERS_AND_ADMIN, policy: { '2-of': [{ '1-of': [{ 'signed-by': 0 }, { '1-of': [{ 'signed-by': 1 }, { 'signed-by': 2 }] }] }, { '1-of': [{ '2-of': [{ 'signed-by': 0 }, { 'signed-by': 1 }, { 'signed-by': 2 }] }, { '2-of': [{ 'signed-by': 2 }, { '1-of': [{ 'signed-by': 0 }, { 'signed-by': 1 }] }] }] }] } }; test('\n\n ** Chain _buildDefaultEndorsementPolicy() tests **\n\n', function (t) { var c = new Chain('does not matter', client); t.throws( () => { c._buildEndorsementPolicy(); }, /Verifying MSPs not found in the chain object, make sure "intialize\(\)" is called first/, 'Checking that "initialize()" must be called before calling "instantiate()" that uses the endorsement policy' ); // construct dummy msps and msp manager to test default policy construction var msp1 = new MSP({ id: 'msp1', cryptoSuite: 'crypto1' }); var msp2 = new MSP({ id: 'msp2', cryptoSuite: 'crypto2' }); var mspm = new MSPManager(); mspm._msps = { 'msp1': msp1, 'msp2': msp2 }; c._msp_manager = mspm; var policy; t.doesNotThrow( () => { policy = c._buildEndorsementPolicy(); }, null, 'Checking that after initializing the chain with dummy msps and msp manager, _buildEndorsementPolicy() can be called without error' ); t.equal(Buffer.isBuffer(policy), true, 'Checking default policy has an identities array'); var env = _policiesProto.SignaturePolicyEnvelope.decode(policy); t.equal(Array.isArray(env.identities), true, 'Checking decoded default policy has an "identities" array'); t.equal(env.identities.length, 2, 'Checking decoded default policy has two array items'); t.equal(env.identities[0].getPrincipalClassification(), _mspPrProto.MSPPrincipal.Classification.ROLE, 'Checking decoded default policy has a ROLE identity'); t.equal(typeof env.getPolicy().get('n_out_of'), 'object', 'Checking decoded default policy has an "n_out_of" policy'); t.equal(env.getPolicy().get('n_out_of').getN(), 1, 'Checking decoded default policy has an "n_out_of" policy with N = 1'); t.throws( () => { c._buildEndorsementPolicy({identities: null}); }, /Invalid policy, missing the "identities" property/, 'Checking policy spec: must have identities' ); t.throws( () => { c._buildEndorsementPolicy({identities: {}}); }, /Invalid policy, the "identities" property must be an array/, 'Checking policy spec: identities must be an array' ); t.throws( () => { c._buildEndorsementPolicy({identities: []}); }, /Invalid policy, missing the "policy" property/, 'Checking policy spec: must have "policy"' ); t.throws( () => { c._buildEndorsementPolicy({identities: [{dummy: 'value', dummer: 'value'}], policy: {}}); }, /Invalid identity type found: must be one of role, organization-unit or identity, but found dummy,dummer/, 'Checking policy spec: each identity must be "role", "organization-unit" or "identity"' ); t.throws( () => { c._buildEndorsementPolicy({identities: [{role: 'value'}], policy: {}}); }, /Invalid role name found: must be one of "member" or "admin", but found/, 'Checking policy spec: value identity type "role" must have valid "name" value' ); t.throws( () => { c._buildEndorsementPolicy({identities: [{'organization-unit': 'value'}], policy: {}}); }, /NOT IMPLEMENTED/, 'Checking policy spec: value identity type "organization-unit"' ); t.throws( () => { c._buildEndorsementPolicy({identities: [{identity: 'value'}], policy: {}}); }, /NOT IMPLEMENTED/, 'Checking policy spec: value identity type "identity"' ); t.throws( () => { c._buildEndorsementPolicy({identities: [{role: {name: 'member', mspId: 'value'}}], policy: {dummy: 'value'}}); }, /Invalid policy type found: must be one of "n-of" or "signed-by" but found "dummy"/, 'Checking policy spec: policy type must be "n-of" or "signed-by"' ); t.doesNotThrow( () => { policy = c._buildEndorsementPolicy(ONE_OF_TWO_ORG_MEMBER); }, null, 'Building successfully from valid policy spec ONE_OF_TWO_ORG_MEMBER' ); env = _policiesProto.SignaturePolicyEnvelope.decode(policy); t.equals(Array.isArray(env.identities) && env.identities.length === 3 && env.identities[0].getPrincipalClassification() === _mspPrProto.MSPPrincipal.Classification.ROLE, true, 'Checking decoded custom policy has two items' ); t.equals(env.policy['n_out_of'].getN(), 1, 'Checking decoded custom policy has "1 out of"'); t.equals(env.policy['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has two target policies'); t.doesNotThrow( () => { policy = c._buildEndorsementPolicy(TWO_OF_TWO_ORG_MEMBER); }, null, 'Building successfully from valid policy spec TWO_OF_TWO_ORG_MEMBER' ); env = _policiesProto.SignaturePolicyEnvelope.decode(policy); t.equals(env.policy['n_out_of'].getN(), 2, 'Checking decoded custom policy has "2 out of"'); t.equals(env.policy['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has two target policies'); t.doesNotThrow( () => { policy = c._buildEndorsementPolicy(ONE_OF_TWO_ORG_MEMBER_AND_ADMIN); }, null, 'Building successfully from valid policy spec ONE_OF_TWO_ORG_MEMBER_AND_ADMIN' ); env = _policiesProto.SignaturePolicyEnvelope.decode(policy); t.equals(env.policy['n_out_of'].getN(), 2, 'Checking decoded custom policy has "2 out of"'); t.equals(env.policy['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has two target policies'); t.equals(env.policy['n_out_of'].policies[0]['n_out_of'].getN(), 1, 'Checking decoded custom policy has "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[0]['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has two target policies inside the "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['signed_by'], 2, 'Checking decoded custom policy has "signed-by: 2" inside the "2 out of"'); t.doesNotThrow( () => { policy = c._buildEndorsementPolicy(CRAZY_SPEC); }, null, 'Building successfully from valid policy spec CRAZY_SPEC' ); env = _policiesProto.SignaturePolicyEnvelope.decode(policy); t.equals(env.policy['n_out_of'].getN(), 2, 'Checking decoded custom policy has "2 out of"'); t.equals(env.policy['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has two target policies'); t.equals(env.policy['n_out_of'].policies[0]['n_out_of'].getN(), 1, 'Checking decoded custom policy has "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[0]['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has two target policies inside the "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getN(), 1, 'Checking decoded custom policy has "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has two target policies inside the "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getPolicies()[0]['n_out_of'].getN(), 2, 'Checking decoded custom policy has "2 out of " inside "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getPolicies()[0]['n_out_of'].getPolicies().length, 3, 'Checking decoded custom policy has 3 target policies for "2 out of " inside "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getPolicies()[1]['n_out_of'].getN(), 2, 'Checking decoded custom policy has "2 out of " inside "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getPolicies()[1]['n_out_of'].getPolicies().length, 2, 'Checking decoded custom policy has 2 target policies for "2 out of " inside "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getPolicies()[1]['n_out_of'].getPolicies()[0]['signed_by'], 2, 'Checking decoded custom policy has "signed-by: 2" for "2 out of " inside "1 out of" inside the "2 out of"'); t.equals(env.policy['n_out_of'].policies[1]['n_out_of'].getPolicies()[1]['n_out_of'].getPolicies()[1]['n_out_of'].getN(), 1, 'Checking decoded custom policy has "1 out of" inside "2 out of " inside "1 out of" inside the "2 out of"'); t.end(); }); test('\n\n ** Chain sendInstantiateProposal() tests **\n\n', function (t) { var c = new Chain('does not matter', client); var peer = new Peer('grpc://localhost:7051'); c.addPeer(peer); var p1 = c.sendInstantiateProposal({ targets: [new Peer('grpc://localhost:7051')], chaincodePath: 'blah', chaincodeId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], chainId: 'blah', txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "chaincodeVersion" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "chaincodeVersion" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing chaincodeVersion error'); } else { t.fail('Failed to catch the missing chaincodeVersion error. Error: '); logger.error(err.stack ? err.stack : err); } }); var p2 = c.sendInstantiateProposal({ targets: [new Peer('grpc://localhost:7051')], chaincodePath: 'blah', chaincodeId: 'blah', chaincodeVersion: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "chainId" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "chainId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing chainId error'); } else { t.fail('Failed to catch the missing chainId error. Error: ' + err.stack ? err.stack : err); } }); var p3 = c.sendInstantiateProposal({ targets: [new Peer('grpc://localhost:7051')], chaincodePath: 'blah', chaincodeVersion: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "chaincodeId" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "chaincodeId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing chaincodeId error'); } else { t.fail('Failed to catch the missing chaincodeId error. Error: ' + err.stack ? err.stack : err); } }); c.removePeer(peer); var p4 = c.sendInstantiateProposal({ chaincodePath: 'blah', chaincodeId: 'blah', chaincodeVersion: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "peer" objects on chain'); }).catch(function (err) { var msg = 'Missing peer objects in Instantiate proposal'; if (err.message.indexOf(msg) >= 0) { t.pass('Successfully caught error: '+msg); } else { t.fail('Failed to catch error: '+msg+'. Error: ' + err.stack ? err.stack : err); } }); c.addPeer(peer); var p5 = c.sendInstantiateProposal({ targets: [new Peer('grpc://localhost:7051')], chaincodePath: 'blah', chaincodeId: 'blah', chaincodeVersion: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "txId" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "txId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing txId error'); } else { t.fail('Failed to catch the missing txId error. Error: ' + err.stack ? err.stack : err); } }); var p6 = c.sendInstantiateProposal({ targets: [new Peer('grpc://localhost:7051')], chaincodePath: 'blah', chaincodeId: 'blah', chaincodeVersion: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "nonce" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "nonce" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing nonce error'); } else { t.fail('Failed to catch the missing nonce error. Error: ' + err.stack ? err.stack : err); } }); var p7 = c.sendInstantiateProposal().then(function () { t.fail('Should not have been able to resolve the promise because of missing request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing input request object on the proposal request') >= 0) { t.pass('Successfully caught missing request error'); } else { t.fail('Failed to catch the missing request error. Error: ' + err.stack ? err.stack : err); } }); Promise.all([p1, p2, p3, p4, p6, p7]) .then( function (data) { t.end(); } ).catch( function (err) { t.fail('Chain sendInstantiateProposal() tests, Promise.all: '+err.stack ? err.stack : err); t.end(); } ); }); test('\n\n ** Chain sendTransactionProposal() tests **\n\n', function (t) { var c = new Chain('does not matter', client); var peer = new Peer('grpc://localhost:7051'); c.addPeer(peer); var p1 = c.sendTransactionProposal({ chaincodeId : 'blah', fcn: 'invoke', chainId: 'blah', txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "args" parameter'); }).catch(function (err) { var msg = 'Missing "args" in Transaction proposal request'; if (err.message.indexOf(msg) >= 0) { t.pass('Successfully caught error: '+msg); } else { t.fail('Failed to catch error: '+msg+'. Error: ' + err.stack ? err.stack : err); } }); var p2 = c.sendTransactionProposal({ chaincodeId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "chainId" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "chainId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing chainId error'); } else { t.fail('Failed to catch the missing chainId error. Error: ' + err.stack ? err.stack : err); } }); var p3 = c.sendTransactionProposal({ chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "chaincodeId" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "chaincodeId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing chaincodeId error'); } else { t.fail('Failed to catch the missing chaincodeId error. Error: ' + err.stack ? err.stack : err); } }); c.removePeer(peer); var p4 = c.sendTransactionProposal({ chaincodeId: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "peer" objects on chain'); }).catch(function (err) { var msg = 'Missing peer objects in Transaction proposal'; if (err.message.indexOf(msg) >= 0) { t.pass('Successfully caught error: '+msg); } else { t.fail('Failed to catch error: '+msg+'. Error: ' + err.stack ? err.stack : err); } }); c.addPeer(peer); var p5 = c.sendTransactionProposal({ chaincodeId: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "txId" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "txId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing txId error'); } else { t.fail('Failed to catch the missing txId error. Error: ' + err.stack ? err.stack : err); } }); var p6 = c.sendTransactionProposal({ chaincodeId: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "nonce" parameter'); }).catch(function (err) { if (err.message.indexOf('Missing "nonce" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing nonce error'); } else { t.fail('Failed to catch the missing nonce error. Error: ' + err.stack ? err.stack : err); } }); var p7 = c.sendTransactionProposal().then(function () { t.fail('Should not have been able to resolve the promise because of missing request parameter'); }).catch(function (err) { if (err.message.indexOf('Missing request object for this transaction proposal') >= 0) { t.pass('Successfully caught missing request error'); } else { t.fail('Failed to catch the missing request error. Error: ' + err.stack ? err.stack : err); } }); Promise.all([p1, p2, p3, p4, p5, p6, p7]) .then( function (data) { t.end(); } ).catch( function (err) { t.fail('Chain sendTransactionProposal() tests, Promise.all: '+err.stack ? err.stack : err); t.end(); } ); }); test('\n\n ** Client queryByChaincode() tests **\n\n', function (t) { var c = client.newChain('any chain goes'); var peer = new Peer('grpc://localhost:7051'); c.addPeer(peer); var p1 = c.queryByChaincode({ chaincodeId : 'blah', fcn: 'invoke', chainId: 'blah', txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "args" parameter in queryByChaincode'); }).catch(function (err) { var msg = 'Missing "args" in Transaction proposal request'; if (err.message.indexOf(msg) >= 0 ) { t.pass('Successfully caught error: '+msg); } else { t.fail('Failed to catch queryByChaincode error: '+msg+'. Error: ' + err.stack ? err.stack : err); } }); var p2 = c.queryByChaincode({ chaincodeId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "chainId" parameter in queryByChaincode'); }).catch(function (err) { if (err.message.indexOf('Missing "chainId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing chainId error'); } else { t.fail('Failed to catch the queryByChaincode missing chainId error. Error: ' + err.stack ? err.stack : err); } }); var p3 = c.queryByChaincode({ chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "chaincodeId" parameter in queryByChaincode'); }).catch(function (err) { if (err.message.indexOf('Missing "chaincodeId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing chaincodeId error'); } else { t.fail('Failed to catch the queryByChaincode missing chaincodeId error. Error: ' + err.stack ? err.stack : err); } }); c.removePeer(peer); var p4 = c.queryByChaincode({ chaincodeId: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah', nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "peers" on chain in queryByChaincode'); }).catch(function (err) { var msg = 'Missing peer objects in Transaction proposal'; if (err.message.indexOf(msg) >= 0) { t.pass('Successfully caught error: '+msg); } else { t.fail('Failed to catch queryByChaincode error: '+msg+'. Error: ' + err.stack ? err.stack : err); } }); c.addPeer(peer); var p5 = c.queryByChaincode({ chaincodeId: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], nonce: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "txId" parameter in queryByChaincode'); }).catch(function (err) { if (err.message.indexOf('Missing "txId" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing txId error'); } else { t.fail('Failed to catch the queryByChaincode missing txId error. Error: ' + err.stack ? err.stack : err); } }); var p6 = c.queryByChaincode({ chaincodeId: 'blah', chainId: 'blah', fcn: 'init', args: ['a', '100', 'b', '200'], txId: 'blah' }).then(function () { t.fail('Should not have been able to resolve the promise because of missing "nonce" parameter in queryByChaincode'); }).catch(function (err) { if (err.message.indexOf('Missing "nonce" parameter in the proposal request') >= 0) { t.pass('Successfully caught missing nonce error'); } else { t.fail('Failed to catch the queryByChaincode missing nonce error. Error: ' + err.stack ? err.stack : err); } }); var p7 = c.queryByChaincode().then(function () { t.fail('Should not have been able to resolve the promise because of missing request parameter in queryByChaincode'); }).catch(function (err) { if (err.message.indexOf('Missing request object for this transaction proposal') >= 0) { t.pass('Successfully caught missing request error'); } else { t.fail('Failed to catch the queryByChaincode missing request error. Error: ' + err.stack ? err.stack : err); } }); Promise.all([p1, p2, p3, p4, p5, p6, p7]) .then( function (data) { t.end(); } ).catch( function (err) { t.fail('Client queryByChaincode() tests, Promise.all: '); logger.error(err.stack ? err.stack : err); t.end(); } ); }); test('\n\n ** Chain sendTransaction() tests **\n\n', function (t) { let o = _chain.getOrderers(); for (let i = 0; i < o.length; i++) { _chain.removeOrderer(o[i]); } var p1 = _chain.sendTransaction() .then(function () { t.fail('Should not have been able to resolve the promise because of missing parameters'); }, function (err) { if (err.message.indexOf('Missing input request object on the proposal request') >= 0) { t.pass('Successfully caught missing request error'); } else { t.fail('Failed to catch the missing request error. Error: ' + err.stack ? err.stack : err); } }); var p2 = _chain.sendTransaction({ proposal: 'blah', header: 'blah' }) .then(function () { t.fail('Should not have been able to resolve the promise because of missing parameters'); }, function (err) { if (err.message.indexOf('Missing "proposalResponses" parameter in transaction request') >= 0) { t.pass('Successfully caught missing proposalResponses error'); } else { t.fail('Failed to catch the missing proposalResponses error. Error: ' + err.stack ? err.stack : err); } }); var p3 = _chain.sendTransaction({ proposalResponses: 'blah', header: 'blah' }) .then(function () { t.fail('Should not have been able to resolve the promise because of missing parameters'); }, function (err) { if (err.message.indexOf('Missing "proposal" parameter in transaction request') >= 0) { t.pass('Successfully caught missing proposal error'); } else { t.fail('Failed to catch the missing proposal error. Error: ' + err.stack ? err.stack : err); } }); var p4 = _chain.sendTransaction({ proposalResponses: 'blah', proposal: 'blah' }) .then(function () { t.fail('Should not have been able to resolve the promise because of missing parameters'); }, function (err) { if (err.message.indexOf('Missing "header" parameter in transaction request') >= 0) { t.pass('Successfully caught missing header error'); } else { t.fail('Failed to catch the missing header error. Error: ' + err.stack ? err.stack : err); } }); Promise.all([p1, p2, p3, p4]) .then( function (data) { t.end(); } ).catch( function (err) { t.fail('Chain sendTransaction() tests, Promise.all: '+err.stack ? err.stack : err); t.end(); } ); }); // // Orderer via chain setOrderer/getOrderer // // Set the orderer URL through the chain setOrderer method. Verify that the // orderer URL was set correctly through the getOrderer method. Repeat the // process by updating the orderer URL to a different address. // test('\n\n** TEST ** orderer via chain setOrderer/getOrderer', function(t) { // // Create and configure the test chain // utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); hfc.newDefaultKeyValueStore({ path: testutil.KVS }) .then ( function (store) { client.setStateStore(store); var chain = client.newChain('testChain-orderer-member'); try { var orderer = new Orderer('grpc://localhost:7050'); chain.addOrderer(orderer); t.pass('Successfully set the new orderer URL'); var orderers = chain.getOrderers(); if(orderers !== null && orderers.length > 0 && orderers[0].getUrl() === 'grpc://localhost:7050') { t.pass('Successfully retrieved the new orderer URL from the chain'); } else { t.fail('Failed to retieve the new orderer URL from the chain'); t.end(); } try { var orderer2 = new Orderer('grpc://localhost:5152'); chain.addOrderer(orderer2); t.pass('Successfully updated the orderer URL'); var orderers = chain.getOrderers(); if(orderers !== null && orderers.length > 0 && orderers[1].getUrl() === 'grpc://localhost:5152') { t.pass('Successfully retrieved the upated orderer URL from the chain'); } else { t.fail('Failed to retieve the updated orderer URL from the chain'); } t.end(); } catch(err2) { t.fail('Failed to update the order URL ' + err2); t.end(); } } catch(err) { t.fail('Failed to set the new order URL ' + err); t.end(); } }); }); // // Orderer via chain set/get bad address // // Set the orderer URL to a bad address through the chain setOrderer method. // Verify that an error is reported when trying to set a bad address. // test('\n\n** TEST ** orderer via chain set/get bad address', function(t) { // // Create and configure the test chain // var chain = client.newChain('testChain-orderer-member1'); t.throws( function() { var order_address = 'xxx'; chain.addOrderer(new Orderer(order_address)); }, /InvalidProtocol: Invalid protocol: undefined/, 'Test setting a bad orderer address' ); t.throws( function() { chain.addOrderer(new Orderer()); }, /TypeError: Parameter "url" must be a string, not undefined/, 'Test setting an empty orderer address' ); t.end(); }); //Verify the verify compareProposalResponseResults method. // test('\n\n** TEST ** verify compareProposalResponseResults', function(t) { // // Create and configure the test chain // var chain = client.newChain('testChain-compareProposal'); t.throws( function() { chain.compareProposalResponseResults(); }, /Error: Missing proposal responses/, 'Test compareProposalResponseResults with empty parameter' ); t.throws( function() { chain.compareProposalResponseResults({}); }, /Error: Parameter must be an array of ProposalRespone Objects/, 'Test compareProposalResponseResults with an object parameter' ); t.throws( function() { chain.compareProposalResponseResults([]); }, /Error: Parameter proposal responses does not contain a PorposalResponse/, 'Test compareProposalResponseResults with an empty array parameter' ); t.throws( function() { chain.compareProposalResponseResults([{}]); }, /Error: Parameter must be a ProposalResponse Object/, 'Test compareProposalResponseResults with an array without the correct endorsements parameter' ); t.end(); }); //Verify the verify verifyProposalResponse method. // test('\n\n** TEST ** verify verifyProposalResponse', function(t) { // // Create and configure the test chain // var chain = client.newChain('testChain-compareProposal2'); t.throws( function() { chain.verifyProposalResponse(); }, /Error: Missing proposal response/, 'Test verifyProposalResponse with empty parameter' ); t.throws( function() { chain.verifyProposalResponse({}); }, /Error: Parameter must be a ProposalResponse Object/, 'Test verifyProposalResponse with an object parameter' ); t.throws( function() { chain.verifyProposalResponse([]); }, /Error: Parameter must be a ProposalResponse Object/, 'Test verifyProposalResponse with an empty array parameter' ); t.throws( function() { chain.verifyProposalResponse([{}]); }, /Error: Parameter must be a ProposalResponse Object/, 'Test verifyProposalResponse with an array without the correct endorsements parameter' ); t.end(); }); test('\n\n ** test related APIs for update channel **\n\n', function (t) { var chain = client.newChain('testChain-update'); var p1= chain.buildChannelConfig( ).then(function () { t.fail('Should not have been able to resolve the promise'); }).catch(function (err) { if (err.message.indexOf('Channel definition parameter is required') >= 0) { t.pass('Successfully caught Channel config_definition parameter is required error'); } else { t.fail('Failed to catch Channel config_definition parameter is required Error: '); console.log(err.stack ? err.stack : err); } }); var p2= chain.buildChannelConfigUpdate( ).then(function () { t.fail('Should not have been able to resolve the promise'); }).catch(function (err) { if (err.message.indexOf('Channel definition update parameter is required') >= 0) { t.pass('Successfully caught Channel config_definition parameter is required error'); } else { t.fail('Failed to catch Channel config_definition parameter is required Error: '); console.log(err.stack ? err.stack : err); } }); Promise.all([p1]) .then( function (data) { t.end(); } ).catch( function (err) { t.fail('Client buildChannelConfigUpdate() tests, Promise.all: '); console.log(err.stack ? err.stack : err); t.end(); } ); t.end(); });
ratnakar-asara/fabric-sdk-node
test/unit/chain.js
JavaScript
apache-2.0
43,574
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var getConfig, validate, isProviderRequired, draw, update; var mapInitialized = false; var mapLayers = {}; var level_groups = {}; var object_type_groups = {}; var map = null; var selected_marker = null; var markers = {}; var markerTypes = {}; var mapChartConfig = {}; var layerGroupControl = null; var initialScenario = true; var initialLayerSelected = false; var currentSelectedLevelLayer = "defaultLevel"; var useDefaultValueLabel = "Use default"; (function () { var CHART_LOCATION = '/extensions/chart-templates/'; /** * return the config to be populated in the chart configuration UI * @param schema */ getConfig = function (schema) { var chartConf = require(CHART_LOCATION + '/geo-map/config.json').config; //Adding new column which says "use default value" since there's no option available in DS for column types var columns = []; columns.push(useDefaultValueLabel); for(var j=0; j < schema.length; j++) { columns.push(schema[j]["fieldName"]); } for(var i=0; i < chartConf.length; i++) { if (chartConf[i]["fieldName"] == "level" || chartConf[i]["fieldName"] == "type" || chartConf[i]["fieldName"] == "state" || chartConf[i]["fieldName"] == "information" || chartConf[i]["fieldName"] == "speed" || chartConf[i]["fieldName"] == "heading"){ chartConf[i]["valueSet"] = columns; } } return chartConf; }; /** * validate the user inout for the chart configuration * @param chartConfig */ validate = function(chartConfig) { return true; }; /** * TO be used when provider configuration steps need to be skipped */ isProviderRequired = function () { }; /** * return the gadget content * @param chartConfig * @param schema * @param data */ draw = function (placeholder, chartConfig, _schema, data) { if (!mapInitialized) { mapInitialized = true; mapChartConfig = buildChartConfig(chartConfig); createSearchDivElements(placeholder); initLayers(); while(document.getElementById('map') == null){ setTimeout(function(){ }, 500); } initMap(data, placeholder); } else { addDataToMap(data); } }; /** * * @param data */ update = function (data) { addDataToMap(data); }; function initLayers() { //Add default map layer. mapLayers["default"] = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: config.map.maxZoom, attribution: '© <a href="http://www.openstreetmap.org/copyright" target="_blank">' + 'OpenStreetMap</a>' }); } //creating new overlay cluster level if a object comes with a different level function addNewLevelLayer(newLayerId) { level_groups[newLayerId] = new L.MarkerClusterGroup(config.markercluster); layerGroupControl.removeFrom(map); layerGroupControl = L.control.layers(level_groups, object_type_groups).addTo(map); if(!initialLayerSelected) { map.addLayer(level_groups[newLayerId]); initialLayerSelected = true; } } //creating new overlay cluster level if a object comes with a different level function addNewObjectLayer(newLayerId) { object_type_groups[newLayerId] = new L.MarkerClusterGroup(config.markercluster); layerGroupControl.removeFrom(map); layerGroupControl = L.control.layers(level_groups, object_type_groups).addTo(map); object_type_groups[newLayerId].addTo(map); } function initMap(data) { if (map != null && typeof(map) !== 'undefined') { map.remove(); } map = L.map("map", { zoom: config.map.zoom, center: config.map.center, layers: getLayers(), zoomControl: false, attributionControl: config.map.attributionControl, maxZoom: config.map.maxZoom, maxNativeZoom: config.map.maxNativeZoom }); new L.Control.Zoom({position: 'bottomright'}).addTo(map); // Add zoom controller layerGroupControl = L.control.layers(level_groups, object_type_groups).addTo(map); // Add sub marker groups for (var i in level_groups) { if (level_groups.hasOwnProperty(i)) { level_groups[i].addTo(map); } } // Zoom callbacks. map.on('zoomend', function () { if (map.getZoom() < config.markercluster.disableClusteringAtZoom) { if (selected_marker) { clearFocus(); } } }); //Marker popup open callback. map.on('popupopen', function (e) { if (selected_marker) { clearFocus(); } selected_marker = e.popup._source.feature.id; console.log("initial on marker!!" + e.popup._source.feature.id); }); // Map click callbacks. map.on('click', function (e) { if (selected_marker) { clearFocus(); console.log("cleared focus"); } }); var searchObject = L.control.search(); map.addControl(searchObject); if(data.length > 0) { map.setView([data[0].latitude, data[0].longitude]); } addDataToMap(data); map.on('overlayadd', onOverlayAdd); map.on('overlayremove', onOverlayRemove); map.on('baselayerchange', onBaseLayerChange); embedCustomMaps(); } function embedCustomMaps() { var areaArray = floorConfig; for (var i = 0; i < areaArray.length; i++) { var tempImageBounds = areaArray[i]["mapDetails"]["imageBounds"]; var imageBounds = new L.LatLngBounds([tempImageBounds.northEast.lat, tempImageBounds.northEast.long], [tempImageBounds.southWest.lat, tempImageBounds.southWest.long]); var imageUrls = areaArray[i]["mapDetails"]["urls"]; for(var j = 0; j < imageUrls.length; j++) { var layerName = imageUrls[j]["layerName"]; var markerClusterGroup; if (layerName in level_groups){ markerClusterGroup = level_groups[layerName]; } else { markerClusterGroup = new L.MarkerClusterGroup(config.markercluster); } markerClusterGroup.addLayer(L.imageOverlay(rebaseRelativeUrl(imageUrls[j]["url"]), imageBounds, {opacity: 1.0})); level_groups[layerName] = markerClusterGroup; layerGroupControl.removeFrom(map); layerGroupControl = L.control.layers(level_groups, object_type_groups).addTo(map); if(!initialLayerSelected) { map.addLayer(level_groups[layerName]); initialLayerSelected = true; currentSelectedLevelLayer = layerName; } } } } function addDataToMap(data) { for (var i = 0; i < data.length; i++) { if(initialScenario && 1 == data.length) { //if at the beginning, only single object is getting updated, it will be treated as single object and will get zoomed mapChartConfig.single_marker_mode = true; initialScenario = false; } else if (mapChartConfig.single_marker_mode && 1 < data.length) { //if several objects are getting updated, the focus will be cancelled from single object until a marker is selected mapChartConfig.single_marker_mode = false; clearFocus(); initialScenario = false; } var device = data[i]; var levelId; var objectTypeId; if (mapChartConfig.type) { device.type = mapChartConfig.type; } if (mapChartConfig.state) { device.state = mapChartConfig.state; } if (mapChartConfig.information) { device.information = mapChartConfig.information; } if (mapChartConfig.speed) { device.speed = mapChartConfig.speed; } if (mapChartConfig.heading) { device.heading = mapChartConfig.heading; } if (mapChartConfig.level) { device.level = mapChartConfig.level; } if(null == device.level){ levelId = "defaultLevel"; } else { levelId = device.level; if (!(levelId in level_groups)){ console.log("new level added"); addNewLevelLayer(levelId); } } if(null == device.type){ objectTypeId = "defaultType"; } else { objectTypeId = device.type; if (!(objectTypeId in object_type_groups)){ console.log("new object type added"); addNewObjectLayer(objectTypeId); } } processPointMessage({ "id": device.id, "levelId": levelId, "objectTypeId": objectTypeId, "type": "Feature", "properties": { "name": device.type, "state": device.state, "information": levelId + ": " + device.information, "speed": device.speed, "heading": device.heading }, "geometry": { "type": "Point", "coordinates": [device.longitude, device.latitude] } }); } } function processPointMessage(geoJson) { if (mapChartConfig.single_marker_mode) { selected_marker = geoJson.id; } if (geoJson.id in markers) { var existingObject = markers[geoJson.id]; existingObject.update(geoJson, selected_marker, mapChartConfig); } else { var receivedObject; receivedObject = new GeoMarker(geoJson, level_groups[geoJson.levelId]); receivedObject.update(geoJson, selected_marker, mapChartConfig); markers[geoJson.id] = receivedObject; markers[geoJson.id].addToLayer(); updateMarkers(geoJson.id); if(!(geoJson.objectTypeId in markerTypes)) { markerTypes[geoJson.objectTypeId] = []; } var objectTypeMarkers = markerTypes[geoJson.objectTypeId]; objectTypeMarkers.push(geoJson.id); } } //called when searched from the map focusOnSpatialObject = function (objectId){ console.log("focusing on marker!!"); var spatialObject = markers[objectId]; if (!spatialObject) { $.UIkit.notify({ message: "Spatial Object <span style='color:red'>" + objectId + "</span> not in the Map!!", status: 'warning', timeout: 2000, pos: 'top-center' }); return false; } selected_marker = objectId; clearFocus(); console.log("Selected "+objectId+ " type " + spatialObject.type); console.log(spatialObject); console.log(spatialObject.levelId); if (currentSelectedLevelLayer != spatialObject.levelId) { console.log(spatialObject.levelId); map.removeLayer(level_groups[currentSelectedLevelLayer]); map.addLayer(level_groups[spatialObject.levelId]); currentSelectedLevelLayer = spatialObject.levelId; } map.setView(spatialObject.marker.getLatLng(), 15, {animate: true}); // TODO: check the map._layersMaxZoom and set the zoom level accordingly spatialObject.marker.openPopup(); }; function clearFocus() { if (selected_marker && !mapChartConfig.single_marker_mode) { var spatialObject = markers[selected_marker]; //removes path and closes the popup spatialObject.removeFocusFromMap(); console.log("Marker focus removed"); if (!mapChartConfig.single_marker_mode) { selected_marker = null; } } } //called when the user clicks on the marker focusOnMarker = function (){ var spatialObject = markers[selected_marker]; if (!spatialObject) { console.log("marker with id : " + selected_marker + " not in map"); return false; } clearFocus(); map.setView(spatialObject.marker.getLatLng(), map.getZoom(), {animate: true}); spatialObject.marker.openPopup(); spatialObject.drawPath(); }; //getting maps layer (open maps) function getLayers() { var layers = []; for (var j in mapLayers) { if (mapLayers.hasOwnProperty(j)) { layers.push(mapLayers[j]); } } return layers; } function buildChartConfig(_chartConfig) { var conf = {}; conf.single_marker_mode = false; if (_chartConfig.type == useDefaultValueLabel) { conf.type = "defaultType"; } if (_chartConfig.state == useDefaultValueLabel) { conf.state = "normal"; } if (_chartConfig.information == useDefaultValueLabel) { conf.information = "not available"; } if (_chartConfig.speed == useDefaultValueLabel) { conf.speed = 0; } if (_chartConfig.heading == useDefaultValueLabel) { conf.heading = 400; } if (_chartConfig.level == useDefaultValueLabel) { conf.level = "defaultLevel"; } return conf; } function onOverlayAdd(e){ if (e.name in markerTypes) { var markerIds = markerTypes[e.name]; for(var i = 0; i < markerIds.length; i++){ var existingObject = markers[markerIds[i]]; existingObject.addToLayer(); } } } function onOverlayRemove(e) { if (e.name in markerTypes) { var markerIds = markerTypes[e.name]; for(var i = 0; i < markerIds.length; i++){ if(selected_marker) { clearFocus(); } var existingObject = markers[markerIds[i]]; existingObject.removeFromLayer(); } } } function onBaseLayerChange(e) { if (e.name in level_groups) { currentSelectedLevelLayer = e.name; } } function createSearchDivElements(placeholderCanvas){ var placeholder = document.getElementById(placeholderCanvas.replace("#", "")); if(!document.getElementById('container')){ //adding the container which leaflet draws the map var map = document.createElement("div"); map.setAttribute("id", "map"); map.setAttribute("style", "display: inline-block;"); var container = document.createElement("div"); container.setAttribute("id", "container"); container.appendChild(map); placeholder.appendChild(container); //adding the html for the marker popup var popupDivContainer = document.createElement("div"); popupDivContainer.setAttribute("id", "popupDivContainer"); popupDivContainer.setAttribute("style", "display: none;"); popupDivContainer.innerHTML = "<div id=\"markerPopup\" class=\"popover top\">" + "<div class=\"arrow\"></div>" + "<h3 class=\"popover-title\"><span id=\"objectName\"></span></h3>" + "<div class=\"popover-content\">" + "ID : <span id=\"objectId\"></span>" + "<hr />"+ "<h6>Information</h6>"+ "<p id=\"information\" class=\"bg-primary\" style=\"margin:0px;padding:0px;\"></p>" + "<h6>Speed<span class=\"label label-primary pull-right\"><span id=\"speed\"></span> km/h</span></h6>" + "<h6>Heading<span id=\"heading\" class=\"label label-primary pull-right\"></span></h6>" + "<button type=\"button\" class=\"btn btn-info btn-xs\" onClick=\"focusOnMarker();return false;\">History</button>" + "</div>"+ "</div>"; placeholder.appendChild(popupDivContainer); } } }());
keizer619/carbon-analytics-common
features/analytics-gadget-templates/org.wso2.carbon.analytics.gadget.chart.template.feature/src/main/charts/geo-map/api.js
JavaScript
apache-2.0
17,596
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import { PostOptions, SettingsSidebar, } from '@support/ui/component'; import {SearchResultPostScreen} from '@support/ui/screen'; class SavedMessagesScreen { testID = { savedMessagesScreen: 'saved_messages.screen', closeSettingsButton: 'close.settings.button', }; savedMessagesScreen = element(by.id(this.testID.savedMessagesScreen)); closeSettingsButton = element(by.id(this.testID.closeSettingsButton)); getSearchResultPostItem = (postId, text, postProfileOptions = {}) => { return SearchResultPostScreen.getPost(postId, text, postProfileOptions); }; toBeVisible = async () => { await expect(this.savedMessagesScreen).toBeVisible(); return this.savedMessagesScreen; }; open = async () => { // # Open saved messages screen await SettingsSidebar.savedMessagesAction.tap(); return this.toBeVisible(); }; close = async () => { await this.closeSettingsButton.tap(); await expect(this.savedMessagesScreen).not.toBeVisible(); }; openPostOptionsFor = async (postId, text) => { const {searchResultPostItem} = await this.getSearchResultPostItem(postId, text); await expect(searchResultPostItem).toBeVisible(); // # Open post options await searchResultPostItem.longPress(); await PostOptions.toBeVisible(); }; } const savedMessagesScreen = new SavedMessagesScreen(); export default savedMessagesScreen;
mattermost/mattermost-mobile
detox/e2e/support/ui/screen/saved_messages.js
JavaScript
apache-2.0
1,602
//>>built define("dojox/storage/BehaviorStorageProvider",["dojo","dijit","dojox","dojo/require!dojox/storage/Provider,dojox/storage/manager"],function(c,h,g){c.provide("dojox.storage.BehaviorStorageProvider");c.require("dojox.storage.Provider");c.require("dojox.storage.manager");c.declare("dojox.storage.BehaviorStorageProvider",[g.storage.Provider],{store:null,storeName:"__dojox_BehaviorStorage",keys:[],initialize:function(){try{this.store=this._createStore(),this.store.load(this.storeName)}catch(a){throw Error("Store is not available: "+ a);}this.keys=this.get("keys","dojoxSystemNS")||[];this.initialized=!0;g.storage.manager.loaded()},isAvailable:function(){return c.isIE&&5<=c.isIE},_createStore:function(){var a=c.create("link",{id:this.storeName+"Node",style:{display:"none"}},c.query("head")[0]);a.addBehavior("#default#userdata");return a},put:function(a,b,f,d){this._assertIsValidKey(a);d=d||this.DEFAULT_NAMESPACE;this._assertIsValidNamespace(d);var e=this.getFullKey(a,d);b=c.toJson(b);this.store.setAttribute(e,b);this.store.save(this.storeName); if(b=this.store.getAttribute(e)===b)this._addKey(e),this.store.setAttribute("__dojoxSystemNS_keys",c.toJson(this.keys)),this.store.save(this.storeName);f&&f(b?this.SUCCESS:this.FAILED,a,null,d)},get:function(a,b){this._assertIsValidKey(a);b=b||this.DEFAULT_NAMESPACE;this._assertIsValidNamespace(b);a=this.getFullKey(a,b);return c.fromJson(this.store.getAttribute(a))},getKeys:function(a){a=a||this.DEFAULT_NAMESPACE;this._assertIsValidNamespace(a);a="__"+a+"_";for(var b=[],c=0;c<this.keys.length;c++){var d= this.keys[c];this._beginsWith(d,a)&&(d=d.substring(a.length),b.push(d))}return b},clear:function(a){a=a||this.DEFAULT_NAMESPACE;this._assertIsValidNamespace(a);a="__"+a+"_";for(var b=[],f=0;f<this.keys.length;f++){var d=this.keys[f];this._beginsWith(d,a)&&b.push(d)}c.forEach(b,function(a){this.store.removeAttribute(a);this._removeKey(a)},this);this.put("keys",this.keys,null,"dojoxSystemNS");this.store.save(this.storeName)},remove:function(a,b){this._assertIsValidKey(a);b=b||this.DEFAULT_NAMESPACE; this._assertIsValidNamespace(b);a=this.getFullKey(a,b);this.store.removeAttribute(a);this._removeKey(a);this.put("keys",this.keys,null,"dojoxSystemNS");this.store.save(this.storeName)},getNamespaces:function(){var a=[this.DEFAULT_NAMESPACE],b={};b[this.DEFAULT_NAMESPACE]=!0;for(var c=/^__([^_]*)_/,d=0;d<this.keys.length;d++){var e=this.keys[d];1==c.test(e)&&(e=e.match(c)[1],"undefined"==typeof b[e]&&(b[e]=!0,a.push(e)))}return a},isPermanent:function(){return!0},getMaximumSize:function(){return 64}, hasSettingsUI:function(){return!1},isValidKey:function(a){return null===a||void 0===a?!1:/^[0-9A-Za-z_-]*$/.test(a)},isValidNamespace:function(a){return null===a||void 0===a?!1:/^[0-9A-Za-z-]*$/.test(a)},getFullKey:function(a,b){return"__"+b+"_"+a},_beginsWith:function(a,b){return b.length>a.length?!1:a.substring(0,b.length)===b},_assertIsValidNamespace:function(a){if(!1===this.isValidNamespace(a))throw Error("Invalid namespace given: "+a);},_assertIsValidKey:function(a){if(!1===this.isValidKey(a))throw Error("Invalid key given: "+ a);},_addKey:function(a){this._removeKey(a);this.keys.push(a)},_removeKey:function(a){this.keys=c.filter(this.keys,function(b){return b!==a},this)}});g.storage.manager.register("dojox.storage.BehaviorStorageProvider",new g.storage.BehaviorStorageProvider)});
wanglongbiao/webapp-tools
Highlander/ship-gis/src/main/webapp/js/arcgis_js_api/library/3.22/dojox/storage/BehaviorStorageProvider.js
JavaScript
apache-2.0
3,379
// 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. // Use `npm run webpack` to produce Webpack bundle for this library. const path = require('path'); module.exports = { entry: './index.ts', resolve: { extensions: ['.ts', '.js', '.json'], fallback: { crypto: false, child_process: false, fs: false, http2: false, buffer: 'browserify', process: false, os: false, querystring: false, path: false, stream: 'stream-browserify', url: false, util: false, zlib: false, }, }, output: { library: 'Licensing', filename: 'licensing.min.js', path: path.resolve(__dirname, 'dist'), }, module: { rules: [ { test: /node_modules[\\/]google-auth-library[\\/]src[\\/]crypto[\\/]node[\\/]crypto/, use: 'null-loader', }, { test: /node_modules[\\/]https-proxy-agent[\\/]/, use: 'null-loader', }, { test: /node_modules[\\/]gcp-metadata[\\/]/, use: 'null-loader', }, { test: /node_modules[\\/]gtoken[\\/]/, use: 'null-loader', }, { test: /node_modules[\\/]pkginfo[\\/]/, use: 'null-loader', }, { test: /node_modules[\\/]semver[\\/]/, use: 'null-loader', }, { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, mode: 'production', plugins: [], };
googleapis/google-api-nodejs-client
src/apis/licensing/webpack.config.js
JavaScript
apache-2.0
2,010
/** * Copyright 2016 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview This file is executed by Travis (configured via * .travis.yml in the root directory) and is the main driver script * for running tests. Execution herein is entirely synchronous, that * is, commands are executed on after the other (see the exec * function). Should a command fail, this script will then also fail. * This script attempts to introduce some granularity for our * presubmit checking, via the determineBuildTargets method. */ const child_process = require('child_process'); const exec = require('./exec.js').exec; const execOrDie = require('./exec.js').execOrDie; const path = require('path'); const minimist = require('minimist'); const util = require('gulp-util'); const gulp = 'node_modules/gulp/bin/gulp.js'; const fileLogPrefix = util.colors.yellow.bold('pr-check.js:'); /** * Starts a timer to measure the execution time of the given function. * @param {string} functionName * @return {DOMHighResTimeStamp} */ function startTimer(functionName) { const startTime = Date.now(); console.log( '\n' + fileLogPrefix, 'Running', util.colors.cyan(functionName), '...'); return startTime; } /** * Stops the timer for the given function and prints the execution time. * @param {string} functionName * @return {Number} */ function stopTimer(functionName, startTime) { const endTime = Date.now(); const executionTime = new Date(endTime - startTime); const mins = executionTime.getMinutes(); const secs = executionTime.getSeconds(); console.log( fileLogPrefix, 'Done running', util.colors.cyan(functionName), 'Total time:', util.colors.green(mins + 'm ' + secs + 's')); } /** * Executes the provided command, returning its stdout as an array of lines. * This will throw an exception if something goes wrong. * @param {string} cmd * @return {!Array<string>} */ function getStdout(cmd) { return child_process.execSync(cmd, {'encoding': 'utf-8'}).trim().split('\n'); } /** * Executes the provided command and times it. * @param {string} cmd */ function timedExec(cmd) { const startTime = startTimer(cmd); exec(cmd); stopTimer(cmd, startTime); } /** * Executes the provided command and times it. The program terminates in case of * failure. * @param {string} cmd */ function timedExecOrDie(cmd) { const startTime = startTimer(cmd); execOrDie(cmd); stopTimer(cmd, startTime); } /** * For a provided commit range identifiying a pull request (PR), * yields the list of files. * @param {string} travisCommitRange * @return {!Array<string>} */ function filesInPr(travisCommitRange) { return getStdout(`git diff --name-only ${travisCommitRange}`); } /** * Determines whether the given file belongs to the Validator webui, * that is, the 'VALIDATOR_WEBUI' target. * @param {string} filePath * @return {boolean} */ function isValidatorWebuiFile(filePath) { return filePath.startsWith('validator/webui'); } /** * Determines whether the given file belongs to the Validator webui, * that is, the 'BUILD_SYSTEM' target. * @param {string} filePath * @return {boolean} */ function isBuildSystemFile(filePath) { return filePath.startsWith('build-system') && // Exclude textproto from build-system since we want it to trigger // tests and type check. path.extname(filePath) != '.textproto' && // Exclude config files from build-system since we want it to trigger // the flag config check. !isFlagConfig(filePath); } /** * Determines whether the given file belongs to the validator, * that is, the 'VALIDATOR' target. This assumes (but does not * check) that the file is not part of 'VALIDATOR_WEBUI'. * @param {string} filePath * @return {boolean} */ function isValidatorFile(filePath) { if (filePath.startsWith('validator/')) return true; if (!path.dirname(filePath).endsWith('0.1') && !path.dirname(filePath).endsWith('test')) return false; const name = path.basename(filePath); return name.startsWith('validator-') && (name.endsWith('.out') || name.endsWith('.html') || name.endsWith('.protoascii')); } /** * @param {string} filePath * @return {boolean} */ function isDocFile(filePath) { return path.extname(filePath) == '.md'; } /** * Determines if the given file contains flag configurations, by comparing it * against the well-known json config filenames for prod and canary. * @param {string} filePath * @return {boolean} */ function isFlagConfig(filePath) { const filename = path.basename(filePath); return (filename == 'prod-config.json' || filename == 'canary-config.json'); } /** * Determines the targets that will be executed by the main method of * this script. The order within this function matters. * @param {!Array<string>} filePaths * @returns {!Set<string>} */ function determineBuildTargets(filePaths) { if (filePaths.length == 0) { return new Set([ 'BUILD_SYSTEM', 'VALIDATOR_WEBUI', 'VALIDATOR', 'RUNTIME', 'DOCS', 'FLAG_CONFIG']); } const targetSet = new Set(); for (p of filePaths) { if (isBuildSystemFile(p)) { targetSet.add('BUILD_SYSTEM'); } else if (isValidatorWebuiFile(p)) { targetSet.add('VALIDATOR_WEBUI'); } else if (isValidatorFile(p)) { targetSet.add('VALIDATOR'); } else if (isDocFile(p)) { targetSet.add('DOCS'); } else if (isFlagConfig(p)) { targetSet.add('FLAG_CONFIG'); } else { targetSet.add('RUNTIME'); } } return targetSet; } const command = { testBuildSystem: function() { timedExecOrDie('npm run ava'); }, testDocumentLinks: function(files) { let docFiles = files.filter(isDocFile); timedExecOrDie(`${gulp} check-links --files ${docFiles.join(',')}`); }, runPreBuildChecks: function() { timedExecOrDie(`${gulp} clean`); timedExecOrDie(`${gulp} lint`); }, buildRuntime: function() { timedExecOrDie(`${gulp} clean`); timedExecOrDie(`${gulp} build`); timedExecOrDie(`${gulp} dist --fortesting`); }, runDepAndTypeChecks: function() { timedExecOrDie(`${gulp} build --css-only`); timedExecOrDie(`${gulp} dep-check`); timedExecOrDie(`${gulp} check-types`); }, runUnitTests: function() { // Unit tests with Travis' default chromium timedExecOrDie(`${gulp} test --nobuild --compiled`); // All unit tests with an old chrome (best we can do right now to pass tests // and not start relying on new features). // Disabled because it regressed. Better to run the other saucelabs tests. // timedExecOrDie( // `${gulp} test --nobuild --saucelabs --oldchrome --compiled`); }, runIntegrationTests: function() { // Integration tests with all saucelabs browsers timedExecOrDie( `${gulp} test --nobuild --saucelabs --integration --compiled`); }, runVisualDiffTests: function() { // This must only be run for push builds, since Travis hides the encrypted // environment variables required by Percy during pull request builds. // For now, this is warning-only. timedExec(`${gulp} visual-diff`); }, presubmit: function() { timedExecOrDie(`${gulp} presubmit`); }, buildValidatorWebUI: function() { timedExecOrDie('cd validator/webui && python build.py'); }, buildValidator: function() { timedExecOrDie('cd validator && python build.py'); }, }; function runAllCommands() { // Run different sets of independent tasks in parallel to reduce build time. if (process.env.BUILD_SHARD == "pre_build_checks") { command.testBuildSystem(); command.runPreBuildChecks(); command.runDepAndTypeChecks(); // Skip testDocumentLinks() during push builds. command.buildValidatorWebUI(); command.buildValidator(); } if (process.env.BUILD_SHARD == "integration_tests") { command.buildRuntime(); command.presubmit(); // Must be run after the runtime is built. command.runVisualDiffTests(); // Only called during push builds. command.runIntegrationTests(); } if (process.env.BUILD_SHARD == "unit_tests") { // Unit tests should need a CSS-only build, but for now, we need a full dist // because some of the tests are integration tests. // TODO(rsimha-amp, 9404): Clean up unit tests and change to css-only build. command.buildRuntime(); command.runUnitTests(); } } /** * The main method for the script execution which much like a C main function * receives the command line arguments and returns an exit status. * @param {!Array<string>} argv * @returns {number} */ function main(argv) { const startTime = startTimer('pr-check.js'); console.log( fileLogPrefix, 'Running build shard', util.colors.cyan(process.env.BUILD_SHARD)); // If $TRAVIS_PULL_REQUEST_SHA is empty then it is a push build and not a PR. if (!process.env.TRAVIS_PULL_REQUEST_SHA) { console.log(fileLogPrefix, 'Running all commands on push build.'); runAllCommands(); stopTimer('pr-check.js', startTime); return 0; } const travisCommitRange = `master...${process.env.TRAVIS_PULL_REQUEST_SHA}`; const files = filesInPr(travisCommitRange); const buildTargets = determineBuildTargets(files); if (buildTargets.has('FLAG_CONFIG')) { files.forEach((file) => { if (!isFlagConfig(file)) { console.log(fileLogPrefix, util.colors.red('ERROR:'), 'PRs may not include *config.json files and non-flag-config ' + 'files. Please make the changes in separate PRs.'); console.log(fileLogPrefix, util.colors.yellow('NOTE:'), 'If you see a long list of unrelated files below, it is likely ' + 'that your private branch is significantly out of sync.'); console.log(fileLogPrefix, 'A sync to upstream/master and a push to origin should clear' + ' this error. If a normal push doesn\'t work, try a force push:'); console.log(util.colors.cyan('\t git fetch upstream master')); console.log(util.colors.cyan('\t git rebase upstream/master')); console.log(util.colors.cyan('\t git push origin --force')); console.log('\nFull list of files in this PR:'); files.forEach((file) => { console.log('\t' + file); }); stopTimer('pr-check.js', startTime); process.exit(1); } }); } //if (files.includes('package.json') ? //!files.includes('yarn.lock') : files.includes('yarn.lock')) { //console.error('pr-check.js - any update to package.json or yarn.lock ' + //'must include the other file. Please update through yarn.'); //process.exit(1); //} const sortedBuildTargets = []; for (const t of buildTargets) { sortedBuildTargets.push(t); } sortedBuildTargets.sort(); console.log( fileLogPrefix, 'Detected build targets:', util.colors.cyan(sortedBuildTargets.join(', '))); // Run different sets of independent tasks in parallel to reduce build time. if (process.env.BUILD_SHARD == "pre_build_checks") { if (buildTargets.has('BUILD_SYSTEM')) { command.testBuildSystem(); } if (buildTargets.has('DOCS')) { command.testDocumentLinks(files); } if (buildTargets.has('RUNTIME')) { command.runPreBuildChecks(); command.runDepAndTypeChecks(); } if (buildTargets.has('VALIDATOR_WEBUI')) { command.buildValidatorWebUI(); } if (buildTargets.has('VALIDATOR')) { command.buildValidator(); } } if (process.env.BUILD_SHARD == "integration_tests") { // The integration_tests shard can be skipped for PRs. console.log(fileLogPrefix, 'Skipping integration_tests for PRs'); } if (process.env.BUILD_SHARD == "unit_tests" && buildTargets.has('RUNTIME')) { // Unit tests should need a CSS-only build, but for now, we need a full dist // because some of the tests are integration tests. // TODO(rsimha-amp, 9404): Clean up unit tests and change to css-only build. command.buildRuntime(); // Presubmit needs to run after `gulp dist` as some checks run through // the dist/ folder. // Also presubmit always needs to run even for just docs to check for // copyright at the top. // TODO(rsimha-amp, 9404): Move to integration_tests once it's enabled. command.presubmit(); // Finally, run all unit tests. command.runUnitTests(); } stopTimer('pr-check.js', startTime); return 0; } process.exit(main());
kmh287/amphtml
build-system/pr-check.js
JavaScript
apache-2.0
13,048
import PinSvg from './svg/PinSvg'; export default function ActivityInfo({title, price, stars, reviews, location}) { return ( <> <div className='h2 line-height-2 mb1'> <span className='travel-results-result-text'>{title}</span> <span className='travel-results-result-subtext h3'>&bull;</span> <span className='travel-results-result-subtext h3'>$&nbsp;</span> <span className='black bold'>{price}</span> </div> <div className='h4 line-height-2'> <div className='inline-block relative mr1 h3 line-height-2'> <div className='travel-results-result-stars green'>★★★★★</div> </div> <span className='travel-results-result-subtext mr1'>{reviews} Reviews</span> <span className='travel-results-result-subtext'> <PinSvg /> {location} </span> </div> </> ); }
ampproject/ampstart
templates/travel/components/ActivityInfo.js
JavaScript
apache-2.0
887
$(function() { /* ------------ 合作伙伴信息 ------------ */ $( "#partner_id" ).combobox( { url : ksa.buildUrl( "/data/combo", "bd-partner-all" ), onSelect : function( record ) { $grid.datagrid( "load", { id : record.id } ); } } ); // 确认选择 $("#btn_ok").click( function() { var results = $("#extra_grid").datagrid("getSelected"); parent.$.close( results ); return false; }); // 添加确认 $("#btn_extra_ok").click( function() { $("#btn_extra_ok").attr("disabled", "disabled"); var extra = $("#extra").val(); if( ! extra ) { top.$.messager.warning("请输入新建的抬头信息。"); $("#btn_extra_ok").attr("disabled", null ); return false; } else { // 保存 $.ajax({ url: ksa.buildUrl( "/component/bd", "partner-alias-insert" ), data: { "partner.id" : $("#partner_id").combobox("getValue"), extra : extra }, success: function( result ) { try { if (result.status == "success") { // 添加成功 parent.$.close( extra ); return false; } else { $.messager.error( result.message ); $("#btn_extra_ok").attr("disabled", null ); } } catch (e) { $("#btn_extra_ok").attr("disabled", null ); } } }); } } ); // 添加关闭 $("#btn_extra_close").click( function() { $("#extra_window").window("close"); } ); // 单位别名 var NEW_LINE = "\n"; $.fn.datagrid.defaults.loadEmptyMsg = '<span class="label label-warning">注意</span> 没有获取到任何数据,请选择新的合作单位。'; var $grid = $('#extra_grid').datagrid({ title : '抬头信息:' + PARTNER_NAME, url: ksa.buildUrl( "/data/grid", "bd-partner-extra" ), pagination : false, queryParams : { id : $("#partner_id").combobox("getValue") }, fit : true, onDblClickRow : function( i, data ) { parent.$.close( data ); return false; }, columns:[[ { field:'dump', checkbox:true }, { field:'name', title:'抬头', width:200, formatter:function(v,data,i) { var a = data; try { while( a.indexOf( NEW_LINE ) >= 0 ) { a = a.replace( NEW_LINE, "<br/>" ); } return a; } catch(e) { return data; } } } ]], toolbar:[{ text:'添加...', cls: 'btn-primary', iconCls:'icon-plus icon-white', handler:function(){ var id = $("#partner_id").combobox("getValue"); if( !id || id == "" ) { top.$.messager.warning("请首先选择合作单位,再进行抬头信息的添加操作。"); return; } $("#extra_window").window("open"); $("#extra").val(""); try { $("#extra")[0].focus(); } catch(e){} } }, '-', { text:'删除', cls: 'btn-danger', iconCls:'icon-trash icon-white', handler:function(){ deleteExtra(); } }] }); // 删除 function deleteExtra() { var row = $grid.datagrid( "getSelected" ); if( ! row ) { top.$.messager.warning("请选择一条数据后,再进行删除操作。"); return; } $.messager.confirm( "确定删除所选抬头吗?", function( ok ){ if( ok ) { $.ajax({ url: ksa.buildUrl( "/component/bd", "partner-alias-delete" ), data: { "partner.id" : $("#partner_id").combobox("getValue"), extra : $grid.datagrid("getSelected") }, success: function( result ) { try { if (result.status == "success") { $.messager.success( result.message ); $grid.datagrid( "reload" ); } else { $.messager.error( result.message ); } } catch (e) { } } }); } } ); } });
xsocket/ksa
ksa-web-root/ksa-bd-web/src/main/resources/ui/bd/component/partner-alias-selection.js
JavaScript
apache-2.0
4,709
var a04869 = [ [ "font_sample_count", "a04869.html#af23335c4319e0c5f010380d9de8f5a6d", null ], [ "Label", "a04869.html#ad4701118c2e75f005c1f7e4c53abb35d", null ], [ "List", "a04869.html#a848ab6ee611dbc860f80a47ecef2faa7", null ], [ "SampleCount", "a04869.html#aab481329945e65c4aeee79b145e4de51", null ] ];
stweil/tesseract-ocr.github.io
4.00.00dev/a04869.js
JavaScript
apache-2.0
321
'use strict'; /** * @ngdoc overview * @name hciApp * @description * # hciApp * * Main module of the application. */ angular .module('hciApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'ui.bootstrap', 'ngMaterial' ]) .config(function ($routeProvider) { $routeProvider .when('/main', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/main/:mode', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/about', { templateUrl: 'views/about.html', controller: 'AboutCtrl' }) .when('/ideas', { templateUrl: 'views/ideas.html', controller: 'IdeasCtrl' }) .when('/details', { templateUrl: 'views/details.html', controller: 'DetailsCtrl' }) .otherwise({ redirectTo: '/main' }); });
admitriyev/hci-prototype
app/scripts/app.js
JavaScript
apache-2.0
952
const config = require('./protractor.conf').config; config.capabilities = { browserName: 'chrome', chromeOptions: { args: ['--headless', '--no-sandbox', '--disable-gpu'], }, }; exports.config = config;
bwsw/cloudstack-ui
e2e/protractor-ci.conf.js
JavaScript
apache-2.0
214
export { default as Home} from './home'; export { default as Post} from './post'; export { default as Search} from './search'; export { default as About} from './about'; export { default as Author} from './author'; export { default as Comment} from './comment'; export { default as Setting} from './setting'; export { default as Offline} from './offline'; export { default as OfflinePost} from './offlinePost';
cloudfavorites/favorites
android/source/view/index.js
JavaScript
apache-2.0
410
// // Webble World 3.0 (IntelligentPad system for the web) // // Copyright (c) 2010-2015 Micke Nicander Kuwahara, Giannis Georgalis, Yuzuru Tanaka // in Meme Media R&D Group of Hokkaido University, Japan. 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. // // Additional restrictions may apply. See the LICENSE file for more information. // 'use strict'; /** * Group management controller that drives the view groups.html * * @author Giannis Georgalis <[email protected]> */ ww3Controllers.controller('GroupsCtrl', ['$scope', '$http', 'gettext', 'authService', 'confirm', 'Users', 'UserAccounts', function ($scope, $http, gettext, authService, confirm, Users, UserAccounts) { //////////////////////////////////////////////////////////////////// // Utility functions // function gToF(g) { // Group to formatted visible value (f) if (g.readonly) { return '<i style="color: #b0b8c5;">' + g.name + '</i>'; } else return g.name; } function gToRow(g) { return [{ v: g.id, f: gToF(g) }, g.parent_id, g.description]; } function gsToData(gs) { var rows = [ ['Name', 'Parent Group', 'Tooltip'] ]; // cols gs.forEach(function(g) { rows.push(gToRow(g)); }); return rows; } //****************************************************************** function generateChartData(groupsArray, myGroupsArray) { if (myGroupsArray) { var myGroupsById = {}; for (var i = 0; i < myGroupsArray.length; ++i) myGroupsById[myGroupsArray[i].id] = myGroupsArray[i]; for (i = 0; i < groupsArray.length; ++i) { if (!myGroupsById.hasOwnProperty(groupsArray[i].id)) groupsArray[i].readonly = true; } } return gsToData(groupsArray); // Regenerate if necessary } //****************************************************************** function refreshAllGroups() { return $http.get('/api/groups').then(function(resp) { $scope.groups = resp.data; $scope.chartData = generateChartData($scope.groups, $scope.myGroups); }); } //////////////////////////////////////////////////////////////////// // Scope properties & initialization // /* $scope.users = Users.query(); $scope.userAccounts = UserAccounts.query(); */ $scope.tabs = {}; $scope.editable = $scope.user && $scope.user.role === 'adm'; $scope.groups = []; $scope.alerts = []; refreshAllGroups(); $scope.selectedGroup = null; $scope.selectedGroupEdit = false; if (!$scope.editable) { $http.get('/api/mygroups').then(function (resp) { $scope.myGroups = resp.data; if ($scope.myGroups.length > 0) { $scope.editable = true; if ($scope.groups) // Regenerate chart data if necessary $scope.chartData = generateChartData($scope.groups, $scope.myGroups); } }); } $scope.groupData = {}; // Available publication policies // $scope.availablePolicies = [ { enum: 'open', name: gettext("Open for publications"), help: gettext("Members can publish and update freely under this group") }, { enum: 'moderate_new', name: gettext("Moderate new publications"), help: gettext("Members can update freely but new publications require the group owner's approval") }, { enum: 'moderate_updates', name: gettext("Moderate all updates"), help: gettext("All new publications and updates (by members) under this group require the owner's approval") }, { enum: 'closed', name: gettext("Closed for publications"), help: gettext("All publications and updates under this group are suspended") } ]; $scope.availablePoliciesById = { open: $scope.availablePolicies[0], moderate_new: $scope.availablePolicies[1], moderate_updates: $scope.availablePolicies[2], closed: $scope.availablePolicies[3] }; //////////////////////////////////////////////////////////////////// // Public scope functions // $scope.closeAlert = function (index) { $scope.alerts.splice(index, 1); }; $scope.getUsers = function(q) { var url = $scope.user.role !== 'adm' ? '/api/users?limit=20&q=' : '/api/adm/users?limit=20&q='; return $http.get(url + encodeURIComponent(q)).then(function(resp){ return resp.data; }); }; //****************************************************************** $scope.createGroup = function() { var url = $scope.groupData.subgroup && $scope.selectedGroup && $scope.selectedGroup.id ? '/api/groups/' + $scope.selectedGroup.id : '/api/groups'; return $http.post(url, { group: $scope.groupData, owner: $scope.groupData.owner && $scope.groupData.owner.email }).then(function (resp) { var g = resp.data; $scope.groups.push(g); if ($scope.chartData) $scope.chartData.push(gToRow(g)); $scope.onGroupSelected(null); $scope.alerts.push({ type: 'success', msg: gettext("Created Group") + ": " + g.name }); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }; $scope.modifySelectedGroup = function() { return $http.put('/api/groups/' + $scope.selectedGroup.id, { group: $scope.groupData, owner: ($scope.groupData.owner && $scope.groupData.owner.email) || undefined }).then(function(resp) { var g = resp.data; for (var i = 0; i < $scope.groups.length; ++i) { if ($scope.groups[i].id == g.id) { $scope.groups[i] = g; break; } } $scope.chartData = gsToData($scope.groups); $scope.onGroupSelected(null); }, function(err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }; $scope.createOrModifyGroup = function() { return $scope.selectedGroupEdit ? $scope.modifySelectedGroup() : $scope.createGroup(); }; $scope.deleteGroup = function() { if ($scope.selectedGroup && $scope.selectedGroup.id) { confirm.show(gettext("Delete Group:") + " " + $scope.selectedGroup.name, gettext("If you confirm, any subgroups will be transfered to the parent group and the group's reference will be revoked from all its published objects"), gettext("Delete Group"), gettext("Do Not Delete Group")).then(function () { $http.delete('/api/groups/' + $scope.selectedGroup.id).then(function() { refreshAllGroups().then(function() { // Group deletion may affect other groups also $scope.onGroupSelected(null); $scope.alerts.push({ type: 'success', msg: gettext("Deleted Group") + ": " + g.name }); }); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }); } }; $scope.retrievePublishedObjects = function() { $http.get('/api/groups/' + $scope.selectedGroup.id + '/objects').then(function(resp) { $scope.publishedObjects = resp.data; }); }; $scope.deauthorizePublishedObject = function(obj, index) { confirm.show(gettext("Deauthorize Object:") + " " + obj.repr, gettext("If you confirm, the selected object will no longer be member of the group."), gettext("Deauthorize"), gettext("Do Not Deauthorize")).then(function () { $http.put('/api/groups/' + $scope.selectedGroup.id + '/objects', { obj: obj.id, remove: true }).then(function() { $scope.publishedObjects.splice(index, 1); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }); }; //****************************************************************** $scope.onGroupSelected = function(selectedItem) { $scope.publishedObjects = null; // Clear the publihsed object list in any case if (selectedItem) { for (var i = 0; i < $scope.groups.length; ++i) { if ($scope.groups[i].id == selectedItem) { $scope.selectedGroup = $scope.groups[i]; if ($scope.selectedGroup.readonly) $scope.tabs.info = true; else if ($scope.selectedGroupEdit) $scope.groupData = angular.copy($scope.selectedGroup); break; } } } else { $scope.groupData = {}; $scope.selectedGroup = null; $scope.selectedGroupEdit = false; // Jump to info tab $scope.tabs.info = true; } }; $scope.toggleSelectedGroupEdit = function() { if (!$scope.selectedGroupEdit && $scope.selectedGroup && $scope.selectedGroup.id) { $scope.groupData = angular.copy($scope.selectedGroup); $scope.selectedGroupEdit = true; } else { $scope.groupData = {}; $scope.selectedGroupEdit = false; } }; $scope.addUserToGroup = function(user, group) { if (user && user.email && group && group.id) { //console.log("FAKE ADDING USER: ", user.name.full, "TO GROUP:", group.name); $http.put('/api/groups/' + group.id + '/users', { user: user.email || user.username }) .then(function (resp) { $scope.alerts.push({ type: 'success', msg: gettext("User added to group") + ": " + group.name }); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); } }; //****************************************************************** }]);
BogusCurry/wblwrld3
app/scripts/controllers/groups.js
JavaScript
apache-2.0
9,332
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. couchTests.delayed_commits = function(debug) { var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"}); db.deleteDb(); db.createDb(); if (debug) debugger; run_on_modified_server( [{section: "couchdb", key: "delayed_commits", value: "true"}], function () { // By default, couchdb doesn't fully commit documents to disk right away, // it waits about a second to batch the full commit flush along with any // other updates. If it crashes or is restarted you may lose the most // recent commits. T(db.save({_id:"1",a:2,b:4}).ok); T(db.open("1") != null); restartServer(); T(db.open("1") == null); // lost the update. // note if we waited > 1 sec before the restart, the doc would likely // commit. // Retry the same thing but with full commits on. var db2 = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"true"}); T(db2.save({_id:"1",a:2,b:4}).ok); T(db2.open("1") != null); restartServer(); T(db2.open("1") != null); // You can update but without committing immediately, and then ensure // everything is commited in the last step. T(db.save({_id:"2",a:2,b:4}).ok); T(db.open("2") != null); T(db.ensureFullCommit().ok); restartServer(); T(db.open("2") != null); // However, it's possible even when flushed, that the server crashed between // the update and the commit, and you don't want to check to make sure // every doc you updated actually made it to disk. So record the instance // start time of the database before the updates and then check it again // after the flush (the instance start time is returned by the flush // operation). if they are the same, we know everything was updated // safely. // First try it with a crash. var instanceStartTime = db.info().instance_start_time; T(db.save({_id:"3",a:2,b:4}).ok); T(db.open("3") != null); restartServer(); var commitResult = db.ensureFullCommit(); T(commitResult.ok && commitResult.instance_start_time != instanceStartTime); // start times don't match, meaning the server lost our change T(db.open("3") == null); // yup lost it // retry with no server restart var instanceStartTime = db.info().instance_start_time; T(db.save({_id:"4",a:2,b:4}).ok); T(db.open("4") != null); var commitResult = db.ensureFullCommit(); T(commitResult.ok && commitResult.instance_start_time == instanceStartTime); // Successful commit, start times match! restartServer(); T(db.open("4") != null); }); // Now test that when we exceed the max_dbs_open, pending commits are safely // written. T(db.save({_id:"5",foo:"bar"}).ok); var max = 2; run_on_modified_server( [{section: "couchdb", key: "delayed_commits", value: "true"}, {section: "couchdb", key: "max_dbs_open", value: max.toString()}], function () { for(var i=0; i<max; i++) { var dbi = new CouchDB("test_suite_db" + i); dbi.deleteDb(); dbi.createDb(); } T(db.open("5").foo=="bar"); for(var i=0; i<max+1; i++) { var dbi = new CouchDB("test_suite_db" + i); dbi.deleteDb(); } }); };
yssk22/gaecouch
futon/script/test/delayed_commits.js
JavaScript
apache-2.0
3,920
document.addEventListener('deviceready', ondeviceready, false); function Notifi (){ cordova.plugins.notification.local.schedule({ id: 1, title: "Atento!!!!!", message: "Este evento se ha agregado a tu lista " }); }
polieduco/practicaaplicada20172
proyecto/www/js/notfica.js
JavaScript
apache-2.0
297
var a00278 = [ [ "c_blob_comparator", "a00278.html#adf90dfe481e3980859ab92739b51caa6", null ] ];
stweil/tesseract-ocr.github.io
4.00.00dev/a00278.js
JavaScript
apache-2.0
100
'use strict'; var auth = require('../middleware/auth'); var express = require('express'); var router = express.Router(); var achievements = require('../common/achievements'); var User = require('../models').users; var Action = require('../models').actions; var Log = require('../models').logs; /** * @api {get} /user/action Get user's action list * @apiGroup User Action * * @apiExample {curl} Example usage: * # Get API token via /api/user/token * export API_TOKEN=fc35e6b2f27e0f5ef... * * curl -i -X GET -H "Authorization: Bearer $API_TOKEN" \ * http://localhost:3000/api/user/action * * @apiSuccessExample {json} Success-Response: * { * "pending": {}, * "inProgress": { * "55b230d69a8c96f177154fa1": { * "_id": "55b230d69a8c96f177154fa1", * "name": "Disable standby", * "description": "Turn off and unplug standby power of TV, stereo, computer, etc.", * "effort": 2, * "impact": 2, * "category": null, * "startedDate": "2015-08-11T10:31:39.934Z" * }, * "55b230d69a8c96f177154fa2": { * "startedDate": "2015-08-11T10:43:33.485Z", * "impact": 3, * "effort": 4, * "description": "Find and seal up leaks", * "name": "Leaks", * "_id": "55b230d69a8c96f177154fa2" * } * }, * "done": {}, * "declined": {}, * "na": {} * } */ router.get('/', auth.authenticate(), function(req, res) { res.json(req.user.actions); Log.create({ userId: req.user._id, category: 'User Action', type: 'get', data: {} }); }); /** * @api {get} /user/action/suggested Get list of suggested user actions * @apiGroup User Action * @apiDescription Returns top three most recent actions that the user has not tried * * @apiExample {curl} Example usage: * # Get API token via /api/user/token * export API_TOKEN=fc35e6b2f27e0f5ef... * * curl -i -X GET -H "Authorization: Bearer $API_TOKEN" \ * http://localhost:3000/api/user/action/suggested * * @apiSuccessExample {json} Success-Response: * [ * { * "__v": 0, * "_id": "555f0163688305b57c7cef6c", * "description": "Disabling standby can save up to 10% in total electricity costs.", * "effort": 2, * "impact": 2, * "name": "Disable standby on your devices", * "ratings": [] * }, * { * ... * } * ] * * @apiVersion 1.0.0 */ router.get('/suggested', auth.authenticate(), function(req, res) { Action.getSuggested(req.user, res.successRes); Log.create({ userId: req.user._id, category: 'User Action', type: 'getSuggested', data: res.successRes }); }); /** * @api {post} /user/action/:actionId Change state for user action * @apiGroup User Action * @apiDescription Used to start/stop actions for a user. * * @apiParam {String} actionId Action's MongoId * @apiParam {String} state Can be one of: 'pending', 'inProgress', 'alreadyDoing', * 'done', 'canceled', 'declined', 'na'. * @apiParam {Date} postponed Must be provided if state is 'pending'. Specifies * at which time the user will be reminded of the action again. * * @apiExample {curl} Example usage: * # Get API token via /api/user/token * export API_TOKEN=fc35e6b2f27e0f5ef... * * curl -i -X POST -H "Authorization: Bearer $API_TOKEN" -H "Content-Type: application/json" -d \ * '{ * "state": "inProgress" * }' \ * http://localhost:3000/api/user/action/55b230d69a8c96f177154fa1 * * @apiSuccessExample {json} Success-Response: * { * "pending": {}, * "inProgress": { * "55b230d69a8c96f177154fa1": { * "_id": "55b230d69a8c96f177154fa1", * "name": "Disable standby", * "description": "Turn off and unplug standby power of TV, stereo, computer, etc.", * "effort": 2, * "impact": 2, * "category": null, * "startedDate": "2015-08-11T10:31:39.934Z" * }, * "55b230d69a8c96f177154fa2": { * "startedDate": "2015-08-11T10:43:33.485Z", * "impact": 3, * "effort": 4, * "description": "Find and seal up leaks", * "name": "Leaks", * "_id": "55b230d69a8c96f177154fa2" * } * }, * "done": {}, * "declined": {}, * "na": {} * } */ router.post('/:actionId', auth.authenticate(), function(req, res) { User.setActionState(req.user, req.params.actionId, req.body.state, req.body.postponed, function(err, user) { if (!err) { achievements.updateAchievement(req.user, 'actionsDone', function(oldVal) { // make sure we never decerase the action count return Math.max(oldVal, user.actions ? user.actions.done.length : 0); }); } res.successRes(err, user); }); Log.create({ userId: req.user._id, category: 'User Action', type: 'update', data: req.body }); }); module.exports = router;
CIVIS-project/YouPower
backend/routes/userAction.js
JavaScript
apache-2.0
4,813
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd 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. */ var dispatchStorageEvent = function(key, oldValue, newValue) { var evt = document.createEvent("CustomEvent"); evt.initCustomEvent("storage", true, true); evt.key = key; evt.oldValue = oldValue; evt.newValue = newValue; evt.storageArea = window.widget.preference; document.dispatchEvent(evt); for (var i=0; i < window.frames.length; i++) { window.frames[i].document.dispatchEvent(evt); } }; var widget_info_ = requireNative('WidgetModule'); var preference_ = widget_info_['preference']; preference_.__onChanged_WRT__ = dispatchStorageEvent; function Widget() { Object.defineProperties(this, { "author": { value: widget_info_[ "author"], writable: false }, "description": { value: widget_info_["description"], writable: false }, "name": { value: widget_info_["name"], writable: false }, "shortName": { value: widget_info_["shortName"], writable: false }, "version": { value: widget_info_["version"], writable: false }, "id": { value: widget_info_["id"], writable: false }, "authorEmail": { value: widget_info_["authorEmail"], writable: false }, "authorHref": { value: widget_info_["authorHref"], writable: false }, "height": { get: function() { return window && window.innerHeight || 0; }, configurable: false }, "width": { get: function() { return window && window.innerWidth || 0; }, configurable: false }, "preferences": { value: preference_, writable: false } }); }; Widget.prototype.toString = function() { return "[object Widget]"; }; window.widget = new Widget(); exports = Widget;
sung-su/crosswalk-tizen
extensions/internal/widget/widget_api.js
JavaScript
apache-2.0
2,433
//// [/lib/initial-buildOutput.txt] /lib/tsc --b /src/src/main /src/src/other exitCode:: ExitStatus.Success //// [/src/dist/main/a.d.ts] export {}; //// [/src/dist/main/a.js] "use strict"; exports.__esModule = true; var b_1 = require("./b"); var a = b_1.b; //// [/src/dist/main/b.d.ts] export declare const b = 0; //// [/src/dist/main/b.js] "use strict"; exports.__esModule = true; exports.b = void 0; exports.b = 0; //// [/src/dist/main/tsconfig.tsbuildinfo] { "program": { "fileInfos": { "../../../lib/lib.d.ts": { "version": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };", "signature": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };", "affectsGlobalScope": true }, "../../src/main/b.ts": { "version": "-11678562673-export const b = 0;\r\n", "signature": "-3829176033-export declare const b = 0;\r\n", "affectsGlobalScope": false }, "../../src/main/a.ts": { "version": "-17071184049-import { b } from './b';\r\nconst a = b;", "signature": "-4882119183-export {};\r\n", "affectsGlobalScope": false } }, "options": { "composite": true, "declaration": true, "rootDir": "../../src", "outDir": "..", "skipDefaultLibCheck": true, "configFilePath": "../../src/main/tsconfig.json" }, "referencedMap": { "../../src/main/a.ts": [ "../../src/main/b.ts" ] }, "exportedModulesMap": {}, "semanticDiagnosticsPerFile": [ "../../../lib/lib.d.ts", "../../src/main/a.ts", "../../src/main/b.ts" ] }, "version": "FakeTSVersion" } //// [/src/dist/other/other.d.ts] export declare const Other = 0; //// [/src/dist/other/other.js] "use strict"; exports.__esModule = true; exports.Other = void 0; exports.Other = 0; //// [/src/dist/other/tsconfig.tsbuildinfo] { "program": { "fileInfos": { "../../../lib/lib.d.ts": { "version": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };", "signature": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };", "affectsGlobalScope": true }, "../../src/other/other.ts": { "version": "-2951227185-export const Other = 0;\r\n", "signature": "-7996259489-export declare const Other = 0;\r\n", "affectsGlobalScope": false } }, "options": { "composite": true, "declaration": true, "rootDir": "../../src", "outDir": "..", "skipDefaultLibCheck": true, "configFilePath": "../../src/other/tsconfig.json" }, "referencedMap": {}, "exportedModulesMap": {}, "semanticDiagnosticsPerFile": [ "../../../lib/lib.d.ts", "../../src/other/other.ts" ] }, "version": "FakeTSVersion" }
nojvek/TypeScript
tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/builds-correctly.js
JavaScript
apache-2.0
4,380
var a00455 = [ [ "UnicharIdArrayUtils", "a02761.html", null ], [ "AmbigSpec", "a02765.html", "a02765" ], [ "UnicharAmbigs", "a02769.html", "a02769" ], [ "MAX_AMBIG_SIZE", "a00455.html#a66b35d22667233a1566433c6dd864463", null ], [ "UnicharAmbigsVector", "a00455.html#aa63fceec9a01c185fac83c0e7d04fe08", null ], [ "UnicharIdVector", "a00455.html#a3dad1b2dad5ed3069bdb4c971116b9c5", null ], [ "AmbigType", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222", [ [ "NOT_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222af40a6c3f3fbd83ba09a6607f534349dc", null ], [ "REPLACE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a4de7fc7ae32fd87a4c53e4b6bf3322de", null ], [ "DEFINITE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a36712914249ab1d96c4f395c06bc7009", null ], [ "SIMILAR_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222aba0a03f0cccfdd9e45817623613dd740", null ], [ "CASE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a29c650e9672a75e50491fc10c0f07ec5", null ], [ "AMBIG_TYPE_COUNT", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a79854db5a6d73c698dd9b003f426918f", null ] ] ], [ "ELISTIZEH", "a00455.html#aad9b817c74cee6bd76a4912e7f54ff7b", null ] ];
stweil/tesseract-ocr.github.io
4.00.00dev/a00455.js
JavaScript
apache-2.0
1,254
var robotsParser = require("robots-parser"), urlMod = require("url"); /** * This is a parse that analyzes URL with path /robots.txt. * * @return {Function} Returns the handler. */ module.exports = function (opts) { if (!opts) { opts = {}; } if (!opts.urlFilter) { opts.urlFilter = function () { return true; }; } return function (context) { var robots, urlObj; urlObj = urlMod.parse(context.url); // skip if this is not actually a robots.txt file. if (urlObj.pathname !== "/robots.txt") { return []; } robots = robotsParser(context.url, context.body.toString()); return robots.getSitemaps().map(function (sitemapHref) { return urlMod.resolve(context.url, sitemapHref); }).filter(function (sitemapUrl) { return opts.urlFilter(sitemapUrl, context.url); }); }; };
brendonboshell/supercrawler
lib/handlers/robotsParser.js
JavaScript
apache-2.0
868
import React from "react"; import { mount } from "enzyme"; import { TextArea as VanillaTextArea } from "hig-vanilla"; import TextAreaAdapter from "./TextAreaAdapter"; describe("TextAreaAdapter", () => { it("implements the hig interface", () => { expect(spiedInstance => { mount( <TextAreaAdapter higInstance={spiedInstance} value="TextArea" instructions="Type in your favorite word" placeholder="Fizz" label="Favorite word" name="favorite-word" disabled required="You really have to fill this out" onBlur={() => {}} onChange={() => {}} onFocus={() => {}} onInput={() => {}} /> ); mount( <TextAreaAdapter higInstance={spiedInstance} disabled={false} required="" /> ); }).toImplementHIGInterfaceOf(VanillaTextArea); }); });
hyoshizumi/hig
packages/react/src/adapters/FormElements/TextAreaAdapter.test.js
JavaScript
apache-2.0
941
var a02762 = [ [ "AmbigSpec", "a02762.html#aaa3a04113f5db03951771afa6423e7f4", null ], [ "~AmbigSpec", "a02762.html#a5283933a9e7267b3505f5f18cf289f3e", null ], [ "correct_fragments", "a02762.html#ad3a4b121b26cf829422700494aed91e4", null ], [ "correct_ngram_id", "a02762.html#a879c6167dbfc54980bfeb5a15b32bf73", null ], [ "type", "a02762.html#ae29644f82c6feac4df14b22368fa0873", null ], [ "wrong_ngram", "a02762.html#a9d7f07e5b038c6d61acc9bb75ba7ef1b", null ], [ "wrong_ngram_size", "a02762.html#a4cfb10d18b7c636f3afa5f223afa445e", null ] ];
stweil/tesseract-ocr.github.io
4.0.0-beta.1/a02762.js
JavaScript
apache-2.0
568
import React, {useContext} from 'react'; import {StyleSheet, ScrollView, Text, View, Platform, TouchableHighlight} from 'react-native'; import {NavigationContext} from 'navigation-react'; import {NavigationBar, RightBar, BarButton, SharedElement, useNavigated} from 'navigation-react-native'; export default ({colors, color}) => { const {stateNavigator} = useContext(NavigationContext); useNavigated(() => { if (Platform.OS === 'web') document.title = 'Color'; }); return ( <> <NavigationBar title="Color" barTintColor="#fff"> <RightBar> <BarButton systemItem="cancel" title="Cancel" show="always" accessibilityRole="link" href={stateNavigator.historyManager.getHref( stateNavigator.getNavigationBackLink(1) )} onPress={() => stateNavigator.navigateBack(1)} /> </RightBar> </NavigationBar> <ScrollView contentInsetAdjustmentBehavior="automatic"> <SharedElement name={color} data={{color}} style={styles.color}> <View style={{backgroundColor: color, flex: 1}} /> </SharedElement> <Text style={styles.text}>{color}</Text> <View style={styles.colors}> {[1,2,3].map(i => colors[(colors.indexOf(color) + i) % 15]) .map(subcolor => ( <TouchableHighlight key={subcolor} style={[styles.subcolor, {backgroundColor: subcolor}]} underlayColor={subcolor} accessibilityRole="link" href={stateNavigator.historyManager.getHref( stateNavigator.getRefreshLink({color: subcolor}) )} onPress={(e) => { if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey || e.button) return e.preventDefault() stateNavigator.refresh({color: subcolor}, 'replace'); }}> <View /> </TouchableHighlight> ) )} </View> </ScrollView> </> ); } const styles = StyleSheet.create({ back: { fontSize: 20, color: '#000', fontWeight: 'bold', paddingLeft: 20, paddingTop: 10, }, color: { height: 300, marginTop: 10, marginLeft: 15, marginRight: 15, }, text:{ fontSize: 80, color: '#000', textAlign:'center', fontWeight: 'bold', }, colors: { flexDirection: 'row', justifyContent: 'center', marginTop: 20, }, subcolor: { width: 100, height: 50, marginLeft: 4, marginRight: 4, marginBottom: 10, }, });
grahammendick/navigation
NavigationReactNativeWeb/sample/zoom/Detail.js
JavaScript
apache-2.0
2,749
const log = require('../logger').gateway; const policies = require('../policies'); const EgContextBase = require('./context'); const express = require('express'); const vhost = require('vhost'); const ConfigurationError = require('../errors').ConfigurationError; /* * A pipeline consists of an apiEndpoint and a set of policies. * To bootstrap, iterate through all pipelines and create a specific router for each. * Each router will handle requests to the apiEndpoints specified in its pipeline. * * An example of pipelines config: * pipelines: { * pipeline1: { * apiEndpoints: ['parrots'], * policies: [ * { * test: [ * { * action: { * param1: 'black_beak', * param2: 'someOtherParam' * } * }, * { * action: { * param1: 'red_beak', * param2: 'someOtherParam' * } * } * ] * } * ] * } * } * } */ module.exports.bootstrap = function ({app, config}) { if (!validateGatewayConfig(config)) { return app; } const apiEndpointToPipelineMap = {}; for (const name in config.gatewayConfig.pipelines) { log.info(`processing pipeline ${name}`); const pipeline = config.gatewayConfig.pipelines[name]; const router = configurePipeline(pipeline.policies || [], config); for (const apiName of pipeline.apiEndpoints) { apiEndpointToPipelineMap[apiName] = router; } } const apiEndpoints = processApiEndpoints(config.gatewayConfig.apiEndpoints); for (const el in apiEndpoints) { const host = el; const hostConfig = apiEndpoints[el]; const router = express.Router(); log.debug('processing vhost %s %j', host, hostConfig.routes); for (const route of hostConfig.routes) { let mountPaths = []; route.paths = route.paths || route.path; if (route.pathRegex) { mountPaths.push(RegExp(route.pathRegex)); } else if (route.paths && route.paths.length) { mountPaths = mountPaths.concat(route.paths); } else { mountPaths.push('*'); } for (const path of mountPaths) { log.debug('mounting routes for apiEndpointName %s, mount %s', route.apiEndpointName, path); const handler = (req, res, next) => { log.debug('executing pipeline for api %s, mounted at %s', route.apiEndpointName, path); req.egContext = Object.create(new EgContextBase()); req.egContext.req = req; req.egContext.res = res; req.egContext.apiEndpoint = route; req.egContext.apiEndpoint.scopes = req.egContext.apiEndpoint.scopes || []; if (!Array.isArray(req.egContext.apiEndpoint.scopes)) { req.egContext.apiEndpoint.scopes = [req.egContext.apiEndpoint.scopes]; } return apiEndpointToPipelineMap[route.apiEndpointName](req, res, next); }; if (route.methods && route.methods !== '*') { log.debug('methods specified, registering for each method individually'); const methods = Array.isArray(route.methods) ? route.methods : route.methods.split(','); for (const method of methods) { const m = method.trim().toLowerCase(); if (m) { router[m](path, handler); } } } else { log.debug('no methods specified. handle all mode.'); router.all(path, handler); } } } if (!host || host === '*') { app.use(router); } else { const virtualHost = hostConfig.isRegex ? new RegExp(host) : host; app.use(vhost(virtualHost, router)); } } return app; }; function processApiEndpoints (apiEndpoints) { const cfg = {}; log.debug('loading apiEndpoints %j', apiEndpoints); for (const el in apiEndpoints) { const apiEndpointName = el; let endpointConfigs = apiEndpoints[el]; // apiEndpoint can be array or object {host, paths, methods, ...} endpointConfigs = Array.isArray(endpointConfigs) ? endpointConfigs : [endpointConfigs]; endpointConfigs.forEach(endpointConfig => { let host = endpointConfig.hostRegex; let isRegex = true; if (!host) { host = endpointConfig.host || '*'; isRegex = false; } cfg[host] = cfg[host] || { isRegex, routes: [] }; log.debug('processing host: %s, isRegex: %s', host, cfg[host].isRegex); const route = Object.assign({ apiEndpointName }, endpointConfig); log.debug('adding route to host: %s, %j', host, route); cfg[host].routes.push(route); }); } return cfg; } function configurePipeline (pipelinePoliciesConfig, config) { const router = express.Router(); if (!Array.isArray(pipelinePoliciesConfig)) { pipelinePoliciesConfig = [ pipelinePoliciesConfig ]; } validatePipelinePolicies(pipelinePoliciesConfig, config); pipelinePoliciesConfig.forEach(policyConfig => { const policyName = Object.keys(policyConfig)[0]; let policySteps = policyConfig[policyName]; if (!policySteps) { policySteps = []; } if (!Array.isArray(policySteps)) { policySteps = [ policySteps ]; } const policy = policies.resolve(policyName).policy; if (policySteps.length === 0) { policySteps.push({}); } for (const policyStep of policySteps) { const condition = policyStep.condition; // parameters that we pass to the policy at time of execution const action = policyStep.action || {}; const policyMiddleware = policy(action, config); router.use((req, res, next) => { if (!condition || req.matchEGCondition(condition)) { log.debug('request matched condition for action', policyStep.action, 'in policy', policyName); policyMiddleware(req, res, next); } else { log.debug(`request did not matched condition for action`, policyStep.action, 'in policy', policyName); next(); } }); } }); return router; } function validateGatewayConfig (config) { if (!config || !config.gatewayConfig) { throw new ConfigurationError('No config provided'); } const gatewayConfig = config.gatewayConfig; if (!gatewayConfig.pipelines) { if (gatewayConfig.pipeline) { gatewayConfig.pipelines = Array.isArray(gatewayConfig.pipeline) ? gatewayConfig.pipeline : [ gatewayConfig.pipeline ]; } else { return false; } } if (!gatewayConfig.apiEndpoints) { if (gatewayConfig.apiEndpoint) { gatewayConfig.apiEndpoints = Array.isArray(gatewayConfig.apiEndpoint) ? gatewayConfig.apiEndpoint : [ gatewayConfig.apiEndpoint ]; } else { return false; } } for (const name in gatewayConfig.pipelines) { const pipeline = gatewayConfig.pipelines[name]; if (!pipeline.apiEndpoints) { pipeline.apiEndpoints = pipeline.apiEndpoint; } if (!Array.isArray(pipeline.apiEndpoints)) { pipeline.apiEndpoints = [ pipeline.apiEndpoints ]; } if (!pipeline.policies) { pipeline.policies = pipeline.policy; } if (!Array.isArray(pipeline.policies)) { pipeline.policies = [ pipeline.policies ]; } } return true; } function validatePipelinePolicies (policies, config) { const policiesConfig = config.gatewayConfig.policies || []; policies.forEach(policyObj => { const policyNames = Object.keys(policyObj); if (policyNames.length !== 1) { throw new ConfigurationError('there should be one and only one policy per policy-object in pipeline configuration'); } if (policiesConfig.indexOf(policyNames[0]) === -1) { throw new ConfigurationError(`${policyNames[0]} policy not declared`); } }); }
srcnix/express-gateway
lib/gateway/pipelines.js
JavaScript
apache-2.0
7,806
const OpencgaSampleBrowserConfig = { };
opencb/iva
src/conf/opencga-sample-browser.config.js
JavaScript
apache-2.0
41
(function(root, undef) { /////////////////////////////////////////////////////////////////////////////////////////////// // pg.js, part of rdflib-pg-extension.js made by Stample // see https://github.com/stample/rdflib.js /////////////////////////////////////////////////////////////////////////////////////////////// $rdf.PG = { createNewStore: function(fetcherTimeout) { var store = new $rdf.IndexedFormula(); // this makes "store.fetcher" variable available $rdf.fetcher(store, fetcherTimeout, true); return store; } } /** * Some common and useful namespaces already declared for you */ $rdf.PG.Namespaces = { LINK: $rdf.Namespace("http://www.w3.org/2007/ont/link#"), HTTP: $rdf.Namespace("http://www.w3.org/2007/ont/http#"), HTTPH: $rdf.Namespace("http://www.w3.org/2007/ont/httph#"), RDF: $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), RDFS: $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"), OWL: $rdf.Namespace("http://www.w3.org/2002/07/owl#"), RSS: $rdf.Namespace("http://purl.org/rss/1.0/"), XSD: $rdf.Namespace("http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#dt-"), IANA: $rdf.Namespace("http://www.iana.org/assignments/link-relations/#"), CERT: $rdf.Namespace("http://www.w3.org/ns/auth/cert"), WAC: $rdf.Namespace("http://www.w3.org/ns/auth/acl#"), LDP: $rdf.Namespace("http://www.w3.org/ns/ldp#"), SIOC: $rdf.Namespace("http://rdfs.org/sioc/ns#"), DC: $rdf.Namespace("http://purl.org/dc/elements/1.1/"), FOAF: $rdf.Namespace("http://xmlns.com/foaf/0.1/"), CONTACT: $rdf.Namespace("http://www.w3.org/2000/10/swap/pim/contact#"), STAT: $rdf.Namespace("http://www.w3.org/ns/posix/stat#"), GEOLOC: $rdf.Namespace("http://www.w3.org/2003/01/geo/wgs84_pos#") } /** * Permits to get metadata about a pointed graph. * Like request headers and response headers. * RDFLib put these in the store as triples and it's not always easy to know where it puts the info. * This makes it easier to find back these metadatas */ $rdf.PG.MetadataHelper = { assertSingleStatement: function(stmts,msg) { if ( !stmts || stmts.length != 1 ) { throw new Error(msg + " - Expected exactly one statement. Found: "+stmts); } }, getRequestNode: function(pg) { var fetchUriAsLit = $rdf.lit(pg.why().uri); var stmts = store.statementsMatching(undefined, $rdf.PG.Namespaces.LINK("requestedURI"), fetchUriAsLit, store.fetcher.appNode); this.assertSingleStatement(stmts,"There should be exactly one request node"); var stmt = stmts[0]; return stmt.subject; }, getResponseNode: function(requestNode) { var stmts = store.statementsMatching(requestNode, $rdf.PG.Namespaces.LINK("response"), undefined); this.assertSingleStatement(stmts,"There should be exactly one response node"); var stmt = stmts[0]; return stmt.object; }, getResponseHeaderValue: function(responseNode,headerName) { var headerSym = $rdf.PG.Namespaces.HTTPH(headerName.toLowerCase()); var stmts = store.statementsMatching(responseNode, headerSym, undefined, responseNode); if ( !stmts || stmts.length == 0 ) return undefined; var stmt = stmts[0]; return stmt.object; }, getResponseStatus: function(responseNode) { var statusSym = $rdf.PG.Namespaces.HTTP("status"); var stmts = store.statementsMatching(responseNode, statusSym, undefined, responseNode); this.assertSingleStatement(stmts,"There should be exactly one response node"); var stmt = stmts[0]; return stmt.object; }, getResponseStatusText: function(responseNode) { var statusSym = $rdf.PG.Namespaces.HTTP("statusText"); var stmts = store.statementsMatching(responseNode, statusSym, undefined, responseNode); this.assertSingleStatement(stmts,"There should be exactly one response node"); var stmt = stmts[0]; return stmt.object; }, /** * Returns an helper method that is bound to the given pointed graph and permits to get metadatas related * to the underlying document / resource / named graph * * Note that you can only use this if the underlying document of the pg was retrieved through the fetcher. * If the data was added to the store manually then the requests/responses metadatas are not present in the store * unless you have added them by yourself */ forPointedGraph: function(pg) { var self = this; var requestNode = this.getRequestNode(pg); var responseNode = this.getResponseNode(requestNode); return { getRequestNode: function() { return requestNode; }, getResponseNode: function() { return responseNode; }, getResponseStatus: function() { return self.getResponseStatus(responseNode); }, getResponseStatusText: function() { return self.getResponseStatusText(responseNode); }, getResponseHeaderValue: function(headerName) { return self.getResponseHeaderValue(responseNode,headerName); } } } } $rdf.PG.Utils = { /** * Just a little helper method to verify preconditions and fail fast. * See http://en.wikipedia.org/wiki/Precondition * See http://en.wikipedia.org/wiki/Fail-fast * @param condition * @param message */ checkArgument: function(condition, message) { if (!condition) { throw Error('IllegalArgumentException: ' + (message || 'No description')); } }, /** * remove hash from URL - this gets the document location * @param url * @returns {*} */ fragmentless: function(url) { return url.split('#')[0]; }, isFragmentless: function(url) { return url.indexOf('#') == -1; }, isFragmentlessSymbol: function(node) { return this.isSymbolNode(node) && this.isFragmentless(this.symbolNodeToUrl(node)); }, getTermType: function(node) { if ( node && node.termType ) { return node.termType } else { throw new Error("Can't get termtype on this object. Probably not an RDFlib node: "+node); } }, isLiteralNode: function(node) { return this.getTermType(node) == 'literal'; }, isSymbolNode: function(node) { return this.getTermType(node) == 'symbol'; }, isBlankNode: function(node) { return this.getTermType(node) == 'bnode'; }, literalNodeToValue: function(node) { this.checkArgument(this.isLiteralNode(node), "Node is not a literal node:"+node); return node.value; }, symbolNodeToUrl: function(node) { this.checkArgument(this.isSymbolNode(node), "Node is not a symbol node:"+node); return node.uri; }, /** * Get the nodes for a given relation symbol * @param pg * @param relSym * @returns => List[Nodes] */ getNodes: function(pg, relSym) { return _.chain( pg.rels(relSym) ) .map(function(pg) { return pg.pointer; }).value(); }, getLiteralNodes: function(pg, relSym) { return _.chain($rdf.PG.Utils.getNodes(pg,relSym)) .filter($rdf.PG.Utils.isLiteralNode) .value(); }, getSymbolNodes: function(pg, relSym) { return _.chain($rdf.PG.Utils.getNodes(pg,relSym)) .filter($rdf.PG.Utils.isSymbolNode) .value(); }, getBlankNodes: function(pg, relSym) { return _.chain($rdf.PG.Utils.getNodes(pg,relSym)) .filter($rdf.PG.Utils.isBlankNode) .value(); }, /** * * @param pgList * @returns {*} */ getLiteralValues: function(pgList) { var rels = (slice.call(arguments, 1)); var res = _.chain(pgList) .map(function (pg) { return pg.getLiteral(rels); }) .flatten() .value(); return res; } } $rdf.PG.Utils.Rx = { /** * Permits to create an RxJs observable based on a list of promises * @param promiseList the list of promise you want to convert as an RxJs Observable * @param subject the type of Rx Subject you want to use (default to ReplaySubject) * @param onError, an optional callback for handling errors * @return {*} */ promiseListToObservable: function(promiseList, subject, onError) { if ( promiseList.length == 0 ) { return Rx.Observable.empty(); } // Default to ReplaySubject var subject = subject || new Rx.ReplaySubject(); // Default to non-blocking error logging var onError = onError || function(error) { console.debug("Promise error catched in promiseListToObservable: ",error); // true means the stream won't continue. return false; }; var i = 0; promiseList.map(function(promise) { promise.then( function (promiseValue) { subject.onNext(promiseValue); i++; if ( i == promiseList.length ) { subject.onCompleted(); } }, function (error) { var doStop = onError(error); if ( doStop ) { subject.onError(error); } else { i++; if ( i == promiseList.length ) { subject.onCompleted(); } } } ) }); return subject.asObservable(); } } $rdf.PG.Filters = { isLiteralPointer: function(pg) { return pg.isLiteralPointer(); }, isBlankNodePointer: function(pg) { return pg.isBlankNodePointer(); }, isSymbolPointer: function(pg) { return pg.isSymbolPointer(); } } $rdf.PG.Transformers = { literalPointerToValue: function(pg) { return $rdf.PG.Utils.literalNodeToValue(pg.pointer); }, symbolPointerToValue: function(pg) { return $rdf.PG.Utils.symbolNodeToUrl(pg.pointer); }, tripleToSubject: function(triple) { return triple.subject; }, tripleToPredicate: function(triple) { return triple.predicate; }, tripleToObject: function(triple) { return triple.object; } } /////////////////////////////////////////////////////////////////////////////////////////////// // pointedGraph.js, part of rdflib-pg-extension.js made by Stample // see https://github.com/stample/rdflib.js /////////////////////////////////////////////////////////////////////////////////////////////// /** * A pointed graph is a pointer in a named graph. * A named graph is an http resource/document which contains an RDF graph. * A pointer is a particular node in this graph. * * This PointedGraph implementation provides methods to navigate from one node to another in the current namedGraph, * but it also permits to jump from one namedGraph to another (firing http requests) if a pointer points to a remote node. * * @param {$rdf.store} store - Quad Store * @param {$rdf.node} pointer: point in the current graph. Type: Literal, Bnode, or URI * @param {$rdf.sym} namedGraphUrl: the URL of the current RDF graph. * @return {$rdf.PointedGraph} */ $rdf.pointedGraph = function(store, pointer, namedGraphUrl) { return new $rdf.PointedGraph(store, pointer, namedGraphUrl); }; $rdf.PointedGraph = function() { $rdf.PointedGraph = function(store, pointer, namedGraphUrl) { // TODO assert the pointer is a node $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isFragmentlessSymbol(namedGraphUrl),"The namedGraphUrl should be a fragmentless symbol! -> "+namedGraphUrl); this.store = store; this.pointer = pointer; this.namedGraphUrl = namedGraphUrl; // The namedGraphFetchUrl is the namedGraphUrl that may or not be proxified. // We need this because we kind of hacked RDFLib and unfortunatly if there's a cors proxy enabled, // rdflib will only remember the proxified version of the url in the store this.namedGraphFetchUrl = store.fetcher.proxifySymbolIfNeeded(namedGraphUrl); }; $rdf.PointedGraph.prototype.constructor = $rdf.PointedGraph; // TODO this logging stuff must be moved somewhere else :( // Logs. var logLevels = $rdf.PointedGraph.logLevels = { nologs: 0, debug: 1, info: 2, warning: 3, error: 4 }; // Default is no logs. $rdf.PointedGraph.logLevel = logLevels.nologs; // To change the level of logs $rdf.PointedGraph.setLogLevel = function(level) { $rdf.PointedGraph.logLevel = (logLevels[level] == null ? logLevels.info : logLevels[level]); } var doLog = function(level, consoleLogFunction ,messageArray) { var loggingEnabled = ($rdf.PointedGraph.logLevel !== logLevels.nologs); if ( loggingEnabled ) { var shouldLog = ( (logLevels[level] || logLevels.debug) >= $rdf.PointedGraph.logLevel ); if ( shouldLog ) { // TODO maybe it may be cool to prefix the log with the current pg infos consoleLogFunction.apply(console,messageArray); } } } // Specific functions for each level of logs. var debug = function() { doLog('debug', console.debug, _.toArray(arguments)) }; var info = function() { doLog('info', console.info, _.toArray(arguments)) }; var warning = function() { doLog('warning', console.warn, _.toArray(arguments)) }; var error = function() { doLog('error', console.error, _.toArray(arguments)) }; // Utils. function sparqlPatch(uri, query) { var promise = $.ajax({ type: "PATCH", url: uri, contentType: 'application/sparql-update', dataType: 'text', processData:false, data: query }).promise(); return promise; } function sparqlPut(uri, query) { var promise = $.ajax({ type: "PUT", url: uri, contentType: 'application/sparql-update', dataType: 'text', processData:false, data: query }).promise(); return promise; } /** * From the pointer, this follows a predicate/symbol/rel and gives a list of pointer in the same graph/document. * @param {$rdf.sym} rel the relation from this node * @returns {[PointedGraph]} of PointedGraphs with the same graph name in the same store */ $rdf.PointedGraph.prototype.rel = function (rel) { $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isSymbolNode(rel) , "The argument should be a symbol:"+rel); var self = this; var resList = this.getCurrentDocumentTriplesMatching(this.pointer, rel, undefined, false); return _.map(resList, function (triple) { return new $rdf.PointedGraph(self.store, triple.object, self.namedGraphUrl, self.namedGraphFetchUrl); }); } $rdf.PointedGraph.prototype.relFirst = function(relUri) { var l = this.rel(relUri); if (l.length > 0) return l[0]; } /** * This is the reverse of "rel": this permits to know which PG in the current graph/document points to the given pointer * @param {$rdf.sym} rel the relation to this node * @returns {[PointedGraph]} of PointedGraphs with the same graph name in the same store */ $rdf.PointedGraph.prototype.rev = function (rel) { $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isSymbolNode(rel) , "The argument should be a symbol:"+rel); var self = this; var resList = this.getCurrentDocumentTriplesMatching(undefined, rel, this.pointer, false); return _.map(resList, function (triple) { return new $rdf.PointedGraph(self.store, triple.subject, self.namedGraphUrl, self.namedGraphFetchUrl); }); } $rdf.PointedGraph.prototype.revFirst = function(relUri) { var l = this.rev(relUri); if (l.length > 0) return l[0]; } /** * Same as "rel" but follow mmultiple predicates/rels * @returns {*} */ // Array[relUri] => Array[Pgs] TODO to rework $rdf.PointedGraph.prototype.rels = function() { var self = this; var pgList = _.chain(arguments) .map(function(arg) { return self.rel(arg) }) .flatten() .value() return pgList; } /** * This permits to follow a relation in the local graph and then jump asynchronously. * This produces a stream of pointed graphs in the form of an RxJs Observable * @param Observable[PointedGraph] * @param onJumpError */ $rdf.PointedGraph.prototype.jumpRelObservable = function(relUri) { var pgList = this.rel(relUri); var pgPromiseList = pgList.map(function(pg) { return pg.jumpAsync(); }); return $rdf.PG.Utils.Rx.promiseListToObservable(pgPromiseList); } /** * Just an alias for jumpRelPathObservable * @param relPath * @param onJumpErrorCallback * @return {*} */ $rdf.PointedGraph.prototype.followPath = function(relPath) { return this.jumpRelPathObservable(relPath); } /** * Permits to follow a relation/predicate path, jumping from one document to another when it's needed * @param relPath * @param onJumpErrorCallback optional callback to handle jump errors, because they are not emitted in the stream * @return {*} */ $rdf.PointedGraph.prototype.jumpRelPathObservable = function(relPath) { $rdf.PG.Utils.checkArgument(relPath && relPath.length > 0,"No relation to follow! "+relPath); var head = relPath[0]; var tail = relPath.slice(1); var headStream = this.jumpRelObservable(head); if ( _.isEmpty(tail) ) { return headStream; } else { return headStream.flatMap(function(pg) { var tailStream = pg.jumpRelPathObservable(tail); return tailStream; }) } } /** * Nearly the same as jumpAsync except it will not fetch remote document but will only use documents * that are already in the store. This means that you can't jump to a remote document that has not been previously * loaded in the store or an error will be thrown. * @returns {$rdf.PointedGraph} */ $rdf.PointedGraph.prototype.jump = function() { if ( this.isLocalPointer() ) { return this; } else { var pointerDocumentUrl = this.getSymbolPointerDocumentUrl(); var pointerDocumentFetchUrl = this.store.fetcher.proxifyIfNeeded(pointerDocumentUrl); var uriFetchState = this.store.fetcher.getState(pointerDocumentFetchUrl); if (uriFetchState == 'fetched') { return $rdf.pointedGraph(this.store, this.pointer, $rdf.sym(pointerDocumentUrl), $rdf.sym(pointerDocumentFetchUrl) ); } else { // If this error bothers you, you may need to use jumpAsync throw new Error("Can't jump because the jump requires ["+pointerDocumentUrl+"] to be already fetched." + " This resource is not in the store. State="+uriFetchState); } } } /** * This permits to jump to the pointer document if the document * This will return the current PG if the pointer is local (bnode/literal/local symbols...) * This will return a new PG if the pointer refers to another document. * * So, basically * - (documentUrl - documentUrl#hash ) will return (documentUrl - documentUrl#hash ) * - (documentUrl - documentUrl2#hash ) will return (documentUrl2 - documentUrl2#hash ) * * @returns {Promise[PointedGraph]} */ $rdf.PointedGraph.prototype.jumpAsync = function() { var originalPG = this; if ( originalPG.isLocalPointer() ) { return Q.fcall(function () { return originalPG; }) } else { return this.jumpFetchRemote(); } } /** * This permits to follow a remote symbol pointer and fetch the remote document. * This will give you a PG with the same pointer but the underlying document will be * the remote document instead of the current document. * * For exemple, let's suppose: * - current PG (documentUrl,pointer) is (url1, url1#profile) * - current document contains triple (url1#profile - foaf:knows - url2#profile) * - you follow the foaf:knows rel and get PG2 (url1, url2#profile) * - then you can jumpFetch on PG2 because url2 != url1 * - this will give you PG3 (url2, url2#profile) * - you'll have the same pointer, but the document is different * * @returns {Promise[PointedGraph]} */ $rdf.PointedGraph.prototype.jumpFetchRemote = function() { $rdf.PG.Utils.checkArgument( this.isRemotePointer(),"You are not supposed to jumpFetch if you already have all the data locally. Pointer="+this.pointer); var pointerUrl = this.getSymbolPointerUrl(); var referrerUrl = $rdf.PG.Utils.symbolNodeToUrl(this.namedGraphUrl); var force = false; return this.store.fetcher.fetch(pointerUrl, referrerUrl, force); } // relUri => List[Symbol] $rdf.PointedGraph.prototype.getSymbol = function() { var rels = _.flatten(arguments); // TODO: WTF WHY DO WE NEED TO FLATTEN!!! var pgList = this.rels.apply(this, rels); var symbolValueList = _.chain(pgList) .filter($rdf.PG.Filters.isSymbolPointer) .map($rdf.PG.Transformers.symbolPointerToValue) .value(); return symbolValueList } // relUri => List[Literal] // TODO change the name $rdf.PointedGraph.prototype.getLiteral = function () { var rels = _.flatten(arguments); // TODO: WTF WHY DO WE NEED TO FLATTEN!!! var pgList = this.rels.apply(this, rels); var literalValueList = _.chain(pgList) .filter($rdf.PG.Filters.isLiteralPointer) .map($rdf.PG.Transformers.literalPointerToValue) .value(); return literalValueList; } // Interaction with the PGs. $rdf.PointedGraph.prototype.delete = function(relUri, value) { // TODO to rework? remove hardcoded namespace value var query = 'PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n' + 'DELETE DATA \n' + '{' + "<" + this.pointer.value + ">" + relUri + ' "' + value + '"' + '. \n' + '}'; return sparqlPatch(this.pointer.value, query); } $rdf.PointedGraph.prototype.insert = function(relUri, value) { // TODO to rework? remove hardcoded namespace value? var query = 'PREFIX foaf: <http://xmlns.com/foaf/0.1/> \n' + 'INSERT DATA \n' + '{' + "<" + this.pointer.value + ">" + relUri + ' "' + value + '"' + '. \n' + '}'; return sparqlPatch(this.pointer.value, query); } $rdf.PointedGraph.prototype.update = function (relUri, newValue, oldvalue) { var query = 'DELETE DATA \n' + '{' + "<" + this.pointer.value + "> " + relUri + ' "' + oldvalue + '"' + '} ;\n' + 'INSERT DATA \n' + '{' + "<" + this.pointer.value + "> " + relUri + ' "' + newValue + '"' + '. } '; return sparqlPatch(this.pointer.value, query); } $rdf.PointedGraph.prototype.updateStore = function(relUri, newValue) { this.store.removeMany(this.pointer, relUri, undefined, this.namedGraphFetchUrl); this.store.add(this.pointer, relUri, newValue, this.namedGraphFetchUrl); } $rdf.PointedGraph.prototype.replaceStatements = function(pg) { var self = this; this.store.removeMany(undefined, undefined, undefined, pg.namedGraphFetchUrl); _.each(pg.store.statements, function(stat) { self.store.add(stat.subject, stat.predicate, stat.object, pg.namedGraphFetchUrl) }); } $rdf.PointedGraph.prototype.addRel = function(rel, object) { this.store.add( this.pointer, rel, object, this.why() ); } $rdf.PointedGraph.prototype.removeRel = function(rel, object) { this.store.removeMany( this.pointer, rel, object, this.why() ); } $rdf.PointedGraph.prototype.ajaxPut = function (baseUri, data, success, error, done) { $.ajax({ type: "PUT", url: baseUri, dataType: "text", contentType: "text/turtle", processData: false, data: data, success: function (data, status, xhr) { if (success) success(xhr) }, error: function (xhr, status, err) { if (error) error(xhr) } }) .done(function () { if (done) done() }); } $rdf.PointedGraph.prototype.print = function() { return this.printSummary() + " = { "+this.printContent() + "}" } $rdf.PointedGraph.prototype.printSummary = function() { return "PG[pointer="+this.pointer+" - NamedGraph="+this.namedGraphUrl+"]"; } $rdf.PointedGraph.prototype.printContent = function() { return $rdf.Serializer(this.store).statementsToN3(this.store.statementsMatching(undefined, undefined, undefined, this.namedGraphFetchUrl)); } $rdf.PointedGraph.prototype.toString = function() { return this.printSummary(); } /** * Return a clone of the current pointed graph in another store. * This is useful to edit a pointed graph. * Once the edit is validated it may be nice to merge the small temporary edited store * to the original big store. */ // TODO need better name $rdf.PointedGraph.prototype.deepCopyOfGraph = function() { var self = this; var triples = this.store.statementsMatching(undefined, undefined, undefined, this.namedGraphFetchUrl); var store = new $rdf.IndexedFormula(); $rdf.fetcher(store, 100000, true); // TODO; deals with timeOut _.each(triples, function(stat) { store.add(stat.subject, stat.predicate, stat.object, self.namedGraphFetchUrl) }); return new $rdf.PointedGraph(store, this.pointer, this.namedGraphUrl, this.namedGraphFetchUrl); } $rdf.PointedGraph.prototype.isSymbolPointer = function() { return $rdf.PG.Utils.isSymbolNode(this.pointer); } $rdf.PointedGraph.prototype.isLiteralPointer = function() { return $rdf.PG.Utils.isLiteralNode(this.pointer); } $rdf.PointedGraph.prototype.isBlankNodePointer = function() { return $rdf.PG.Utils.isBlankNode(this.pointer); } /** * Returns the Url of the pointer. * The url may contain a fragment. * Will fail if the pointer is not a symbol because you can't get an url for a blank node or a literal. */ $rdf.PointedGraph.prototype.getSymbolPointerUrl = function() { return $rdf.PG.Utils.symbolNodeToUrl(this.pointer); } /** * Returns the Url of the document in which points the symbol pointer. * The url is a document URL so it won't contain a fragment. * Will fail if the pointer is not a symbol because you can't get an url for a blank node or a literal. */ $rdf.PointedGraph.prototype.getSymbolPointerDocumentUrl = function() { var pointerUrl = this.getSymbolPointerUrl(); return $rdf.PG.Utils.fragmentless(pointerUrl); } /** * Returns the current document/namedGraph Url (so it has no fragment) */ $rdf.PointedGraph.prototype.getCurrentDocumentUrl = function() { return $rdf.PG.Utils.symbolNodeToUrl(this.namedGraphUrl); } /** * This permits to find triples in the current document. * This will not look in the whole store but will only check in the current document/namedGraph * @param pointer (node) * @param rel (node) * @param object (node) * @param onlyOne: set true if you only want one triple result (for perf reasons for exemple) * @returns {*} */ $rdf.PointedGraph.prototype.getCurrentDocumentTriplesMatching = function (pointer,rel,object,onlyOne) { var why = this.why(); return this.store.statementsMatching(pointer, rel, object, this.why(), onlyOne); } /** * Builds a metadata helper to get metadatas related to the underlying documment * @return {*} */ $rdf.PointedGraph.prototype.currentDocumentMetadataHelper = function() { return $rdf.PG.MetadataHelper.forPointedGraph(this); } /** * In the actual version it seems that RDFLib use the fetched url as the "why" * Maybe it's because we have modified it a little bit to work better with our cors proxy. * This is why we need to pass the namedGraphFetchUrl and not the namedGraphUrl */ $rdf.PointedGraph.prototype.why = function() { return this.namedGraphFetchUrl; } /** * This permits to find the triples that matches a given rel/predicate and object * for the current pointer in the current document. * @param rel * @param object * @param onlyOne */ $rdf.PointedGraph.prototype.getPointerTriplesMatching = function(rel,object,onlyOne) { return this.getCurrentDocumentTriplesMatching(this.pointer, rel, object, onlyOne); } /** * Permits to know if there is at least one triple in this graph that matches the pointer, predicate and object * @param rel * @param object * @param onlyOne * @return {boolean} */ $rdf.PointedGraph.prototype.hasPointerTripleMatching = function(rel,object) { return this.getPointerTriplesMatching(rel,object,true).length > 0; } /** * Returns the Url of the currently pointed document. * Most of the time it will return the current document url. * It will return a different url only for non-local symbol nodes. * * If you follow a foaf:knows, you will probably get a list of PGs where the pointer document * URL is not local because your friends will likely describe themselves in different resources. */ $rdf.PointedGraph.prototype.getPointerDocumentUrl = function() { if ( this.isSymbolPointer() ) { return this.getSymbolPointerDocumentUrl(); } else { return this.getCurrentDocumentUrl(); } } /** * Permits to know if the pointer is local to the current document. * This will be the case for blank nodes, literals and local symbol pointers. * @returns {boolean} */ $rdf.PointedGraph.prototype.isLocalPointer = function() { return this.getPointerDocumentUrl() == this.getCurrentDocumentUrl(); } $rdf.PointedGraph.prototype.isRemotePointer = function() { return !this.isLocalPointer(); } /** * Permits to "move" to another subject in the given graph * @param newPointer * @returns {$rdf.PointedGraph} */ $rdf.PointedGraph.prototype.withPointer = function(newPointer) { return new $rdf.PointedGraph(this.store, newPointer, this.namedGraphUrl, this.namedGraphFetchUrl); } /** * Permits to know if the given pointer have at least one rel that can be followed. * This means that the current pointer exists in the local graph as a subject in at least one triple. */ $rdf.PointedGraph.prototype.hasRels = function() { return this.getCurrentDocumentTriplesMatching(this.pointer, undefined, undefined, true).length > 0; } /** * Permits to know if the given pointer have at least one rev that can be followed. * This means that the current pointer exists in the local graph as an object in at least one triple. */ $rdf.PointedGraph.prototype.hasRevs = function() { return this.getCurrentDocumentTriplesMatching(undefined, undefined, this.pointer, true).length > 0; } return $rdf.PointedGraph; }(); /////////////////////////////////////////////////////////////////////////////////////////////// // fetcherWithPromise.js, part of rdflib-pg-extension.js made by Stample // see https://github.com/stample/rdflib.js /////////////////////////////////////////////////////////////////////////////////////////////// /* TODO: this proxification code is kind of duplicate of RDFLib's "crossSiteProxyTemplate" code. How can we make this code be integrated in rdflib nicely? */ /** * Permits to know in which conditions we are using a CORS proxy (if one is configured) * @param uri */ $rdf.Fetcher.prototype.requiresProxy = function(url) { var isCorsProxyConfigured = $rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate; if ( !isCorsProxyConfigured ) { return false; } else { // /!\ this may not work with the original version of RDFLib var isUriAlreadyProxified = (url.indexOf($rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate) == 0); var isHomeServerUri = (url.indexOf($rdf.Fetcher.homeServer) == 0) if ( isUriAlreadyProxified || isHomeServerUri ) { return false; } else { return true; } } } /** * permits to proxify the URI * @param uri * @returns {string} */ $rdf.Fetcher.prototype.proxify = function(uri) { if ( uri && uri.indexOf('#') != -1 ) { throw new Error("Tit is forbiden to proxify an uri with a fragment:"+uri); } if ( uri && uri.indexOf($rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate) == 0 ) { throw new Error("You are trying to proxify an URL that seems to already been proxified!"+uri); } return $rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate + encodeURIComponent(uri); }; /** * Permits to proxify an url if RDFLib is configured to be used with a CORS Proxy * @param url * @returns {String} the original url or the proxied url */ $rdf.Fetcher.prototype.proxifyIfNeeded = function(url) { if ( this.requiresProxy(url) ) { return this.proxify(url); } else { return url; } } $rdf.Fetcher.prototype.proxifySymbolIfNeeded = function(symbol) { $rdf.PG.Utils.checkArgument( $rdf.PG.Utils.isSymbolNode(symbol),"This is not a symbol!"+symbol); var url = $rdf.PG.Utils.symbolNodeToUrl(symbol); var proxifiedUrl = this.proxifyIfNeeded(url); return $rdf.sym(proxifiedUrl); } /** * Return the Promise of a pointed graph for a given url * @param {String} uri to fetch as string. The URI may contain a fragment because it results in a pointedGraph * @param {String} referringTerm the uri as string. Referring to the requested url * @param {boolean} force, force fetching of resource even if already in store * @return {Promise} of a pointedGraph */ $rdf.Fetcher.prototype.fetch = function(uri, referringTerm, force) { var self = this; var uriSym = $rdf.sym(uri); var docUri = $rdf.PG.Utils.fragmentless(uri); var docUriSym = $rdf.sym(docUri); // The doc uri to fetch is the doc uri that may have been proxyfied var docUriToFetch = self.proxifyIfNeeded(docUri); var docUriToFetchSym = $rdf.sym(docUriToFetch); // if force mode enabled -> we previously unload so that uriFetchState will be "unrequested" if ( force ) { self.unload(docUriToFetchSym); } var uriFetchState = self.getState(docUriToFetch); // if it was already fetched we return directly the pointed graph pointing if (uriFetchState == 'fetched') { return Q.fcall(function() { return $rdf.pointedGraph(self.store, uriSym, docUriSym, docUriToFetchSym) }); } // if it was already fetched and there was an error we do not try again // notice you can call "unload(symbol)" if you want a failed request to be fetched again if needed else if ( uriFetchState == 'failed') { return Q.fcall(function() { throw new Error("Previous fetch has failed for"+docUriToFetch+" -> Will try to fetch it again"); }); } // else maybe a request for this uri is already pending, or maybe we will have to fire a request // in both case we are interested in the answer else if ( uriFetchState == 'requested' || uriFetchState == 'unrequested' ) { if ( uriFetchState == 'requested') { console.debug("A request is already being done for",docUriToFetch," -> will wait for that response"); } var deferred = Q.defer(); self.addCallback('done', function fetchDoneCallback(uriFetched) { if ( docUriToFetch == uriFetched ) { deferred.resolve($rdf.pointedGraph(self.store, uriSym, docUriSym, docUriToFetchSym)); return false; // stop } return true; // continue }); self.addCallback('fail', function fetchFailureCallback(uriFetched, statusString, xhr) { if ( docUriToFetch == uriFetched ) { deferred.reject(new Error("Async fetch failure [uri="+uri+"][statusCode="+xhr.status+"][reason="+statusString+"]")); return false; // stop } return true; // continue }); if (uriFetchState == 'unrequested') { var result = self.requestURI(docUriToFetch, referringTerm, force); if (result == null) { // TODO not sure of the effect of this line. This may cause the promise to be resolved twice no? deferred.resolve($rdf.pointedGraph(self.store, uriSym, docUriSym, docUriToFetchSym)); } } return deferred.promise; } else { throw new Error("Unknown and unhandled uriFetchState="+uriFetchState+" - for URI="+uri) } }})(this);
read-write-web/react-foaf
js/lib/rdflib/rdflib-stample-pg-extension-0.1.1.js
JavaScript
apache-2.0
38,343
/** * @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'; /** * @fileoverview Ensures the contrast between foreground and background colors meets * WCAG 2 AA contrast ratio thresholds. * See base class in axe-audit.js for audit() implementation. */ const AxeAudit = require('./axe-audit'); class ColorContrast extends AxeAudit { /** * @return {LH.Audit.Meta} */ static get meta() { return { id: 'color-contrast', title: 'Background and foreground colors have a sufficient contrast ratio', failureTitle: 'Background and foreground colors do not have a ' + 'sufficient contrast ratio.', description: 'Low-contrast text is difficult or impossible for many users to read. ' + '[Learn more](https://dequeuniversity.com/rules/axe/2.2/color-contrast?application=lighthouse).', requiredArtifacts: ['Accessibility'], }; } } module.exports = ColorContrast;
mixed/lighthouse
lighthouse-core/audits/accessibility/color-contrast.js
JavaScript
apache-2.0
1,473
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ testVerifyIfTestLoaded : { test:function(cmp){ var children = (cmp.getElements()[0]).childNodes; $A.test.assertEquals(4, children.length); $A.test.assertEquals("It is not true.It is literally not false.", $A.test.getText(children[0])); $A.test.assertEquals("It wishes it was true.It is not true.", $A.test.getText(children[1])); $A.test.assertEquals("It wishes it was true.It is not true.", $A.test.getText(children[2])); $A.test.assertEquals("It is not true.It is literally not false.", $A.test.getText(children[3])); } } })
lhong375/aura
aura-impl/src/test/components/iterationTest/iterationWJSProviderOnlyList/iterationWJSProviderOnlyListTest.js
JavaScript
apache-2.0
1,218
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Headline } from '@folio/stripes/components'; import css from './ProxyViewList.css'; const ProxyViewList = ({ records, name, label, itemComponent, stripes }) => { const ComponentToRender = itemComponent; const items = records.map((record, index) => ( <ComponentToRender key={`item-${index}`} record={record} stripes={stripes} /> )); const noSponsorsFound = <FormattedMessage id="ui-users.permissions.noSponsorsFound" />; const noProxiesFound = <FormattedMessage id="ui-users.permissions.noProxiesFound" />; const noneFoundMsg = name === 'sponsors' ? noSponsorsFound : noProxiesFound; return ( <div className={css.list} data-test={name}> <Headline tag="h4" size="small" margin="small">{label}</Headline> {items.length ? items : <p className={css.isEmptyMessage}>{noneFoundMsg}</p>} </div> ); }; ProxyViewList.propTypes = { records: PropTypes.arrayOf(PropTypes.object), itemComponent: PropTypes.func.isRequired, name: PropTypes.string.isRequired, label: PropTypes.node.isRequired, stripes: PropTypes.object.isRequired, }; export default ProxyViewList;
folio-org/ui-users
src/components/ProxyGroup/ProxyViewList/ProxyViewList.js
JavaScript
apache-2.0
1,222
import { useEffect, useState, useMemo } from "react" import useCommons from "../../../lib/hooks/useCommons" import { Link } from "react-router-dom" import StaticTags from "../StaticTags" import useL7Policy from "../../../lib/hooks/useL7Policy" import CopyPastePopover from "../shared/CopyPastePopover" import useListener from "../../../lib/hooks/useListener" import { addNotice, addError } from "lib/flashes" import { ErrorsList } from "lib/elektra-form/components/errors_list" import CachedInfoPopover from "../shared/CachedInforPopover" import CachedInfoPopoverContent from "./CachedInfoPopoverContent" import { policy } from "policy" import { scope } from "ajax_helper" import SmartLink from "../shared/SmartLink" import Log from "../shared/logger" import DropDownMenu from "../shared/DropdownMenu" import useStatus from "../../../lib/hooks/useStatus" import usePolling from "../../../lib/hooks/usePolling" const L7PolicyListItem = ({ props, l7Policy, searchTerm, listenerID, disabled, shouldPoll, }) => { const { MyHighlighter, matchParams, errorMessage, searchParamsToString } = useCommons() const { actionRedirect, deleteL7Policy, persistL7Policy, onSelectL7Policy, reset, } = useL7Policy() const [loadbalancerID, setLoadbalancerID] = useState(null) const { persistListener } = useListener() const { entityStatus } = useStatus( l7Policy.operating_status, l7Policy.provisioning_status ) useEffect(() => { const params = matchParams(props) setLoadbalancerID(params.loadbalancerID) }, []) const pollingCallback = () => { return persistL7Policy(loadbalancerID, listenerID, l7Policy.id) } usePolling({ delay: l7Policy.provisioning_status.includes("PENDING") ? 20000 : 60000, callback: pollingCallback, active: shouldPoll || l7Policy?.provisioning_status?.includes("PENDING"), }) const onL7PolicyClick = (e) => { if (e) { e.stopPropagation() e.preventDefault() } onSelectL7Policy(props, l7Policy.id) } const canEdit = useMemo( () => policy.isAllowed("lbaas2:l7policy_update", { target: { scoped_domain_name: scope.domain }, }), [scope.domain] ) const canDelete = useMemo( () => policy.isAllowed("lbaas2:l7policy_delete", { target: { scoped_domain_name: scope.domain }, }), [scope.domain] ) const canShowJSON = useMemo( () => policy.isAllowed("lbaas2:l7policy_get", { target: { scoped_domain_name: scope.domain }, }), [scope.domain] ) const handleDelete = (e) => { if (e) { e.stopPropagation() e.preventDefault() } const l7policyID = l7Policy.id const l7policyName = l7Policy.name return deleteL7Policy(loadbalancerID, listenerID, l7policyID, l7policyName) .then((response) => { addNotice( <React.Fragment> L7 Policy <b>{l7policyName}</b> ({l7policyID}) is being deleted. </React.Fragment> ) // fetch the listener again containing the new policy so it gets updated fast persistListener(loadbalancerID, listenerID) .then(() => {}) .catch((error) => {}) }) .catch((error) => { addError( React.createElement(ErrorsList, { errors: errorMessage(error.response), }) ) }) } const displayName = () => { const name = l7Policy.name || l7Policy.id if (disabled) { return ( <span className="info-text"> <CopyPastePopover text={name} size={20} sliceType="MIDDLE" shouldPopover={false} shouldCopy={false} bsClass="cp copy-paste-ids" /> </span> ) } else { return ( <Link to="#" onClick={onL7PolicyClick}> <CopyPastePopover text={name} size={20} sliceType="MIDDLE" shouldPopover={false} shouldCopy={false} searchTerm={searchTerm} /> </Link> ) } } const displayID = () => { if (l7Policy.name) { if (disabled) { return ( <div className="info-text"> <CopyPastePopover text={l7Policy.id} size={12} sliceType="MIDDLE" bsClass="cp copy-paste-ids" shouldPopover={false} /> </div> ) } else { return ( <CopyPastePopover text={l7Policy.id} size={12} sliceType="MIDDLE" bsClass="cp copy-paste-ids" searchTerm={searchTerm} /> ) } } } const l7RuleIDs = l7Policy.rules.map((l7rule) => l7rule.id) Log.debug("RENDER L7 Policy Item") return ( <tr> <td className="snug-nowrap"> {displayName()} {displayID()} <CopyPastePopover text={l7Policy.description} size={20} shouldCopy={false} shouldPopover={true} searchTerm={searchTerm} /> </td> <td>{entityStatus}</td> <td> <StaticTags tags={l7Policy.tags} /> </td> <td>{l7Policy.position}</td> <td> <MyHighlighter search={searchTerm}>{l7Policy.action}</MyHighlighter> {actionRedirect(l7Policy.action).map((redirect, index) => ( <span className="display-flex" key={index}> <br /> <b>{redirect.label}: </b> {redirect.value === "redirect_prefix" || redirect.value === "redirect_url" ? ( <CopyPastePopover text={l7Policy[redirect.value]} size={20} bsClass="cp label-right" /> ) : ( <span className="label-right">{l7Policy[redirect.value]}</span> )} </span> ))} </td> <td> {disabled ? ( <span className="info-text">{l7Policy.rules.length}</span> ) : ( <CachedInfoPopover popoverId={"l7rules-popover-" + l7Policy.id} buttonName={l7RuleIDs.length} title={ <React.Fragment> L7 Rules <Link to="#" onClick={onL7PolicyClick} style={{ float: "right" }} > Show all </Link> </React.Fragment> } content={ <CachedInfoPopoverContent props={props} lbID={loadbalancerID} listenerID={listenerID} l7PolicyID={l7Policy.id} l7RuleIDs={l7RuleIDs} cachedl7RuleIDs={l7Policy.cached_rules} /> } /> )} </td> <td> <DropDownMenu buttonIcon={<span className="fa fa-cog" />}> <li> <SmartLink to={`/loadbalancers/${loadbalancerID}/listeners/${listenerID}/l7policies/${ l7Policy.id }/edit?${searchParamsToString(props)}`} isAllowed={canEdit} notAllowedText="Not allowed to edit. Please check with your administrator." > Edit </SmartLink> </li> <li> <SmartLink onClick={handleDelete} isAllowed={canDelete} notAllowedText="Not allowed to delete. Please check with your administrator." > Delete </SmartLink> </li> <li> <SmartLink to={`/loadbalancers/${loadbalancerID}/listeners/${listenerID}/l7policies/${ l7Policy.id }/json?${searchParamsToString(props)}`} isAllowed={canShowJSON} notAllowedText="Not allowed to get JSOn. Please check with your administrator." > JSON </SmartLink> </li> </DropDownMenu> </td> </tr> ) } export default L7PolicyListItem
sapcc/elektra
plugins/lbaas2/app/javascript/app/components/l7policies/L7PolicyListItem.js
JavaScript
apache-2.0
8,173
'use strict'; import gulp from 'gulp'; import webpack from 'webpack'; import path from 'path'; import sync from 'run-sequence'; import rename from 'gulp-rename'; import template from 'gulp-template'; import fs from 'fs'; import yargs from 'yargs'; import lodash from 'lodash'; import gutil from 'gulp-util'; import serve from 'browser-sync'; import del from 'del'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import colorsSupported from 'supports-color'; import historyApiFallback from 'connect-history-api-fallback'; let root = 'client'; // helper method for resolving paths let resolveToApp = (glob = '') => { return path.join(root, 'app', glob); // app/{glob} }; let resolveToComponents = (glob = '') => { return path.join(root, 'app/components', glob); // app/components/{glob} }; // map of all paths let paths = { js: resolveToComponents('**/*!(.spec.js).js'), // exclude spec files styl: resolveToApp('**/*.scss'), // stylesheets html: [ resolveToApp('**/*.html'), path.join(root, 'index.html') ], entry: [ 'babel-polyfill', path.join(__dirname, root, 'app/app.js') ], output: root, blankTemplates: path.join(__dirname, 'generator', 'component/**/*.**'), dest: path.join(__dirname, 'dist') }; // use webpack.config.js to build modules gulp.task('webpack', ['clean'], (cb) => { const config = require('./webpack.dist.config'); config.entry.app = paths.entry; webpack(config, (err, stats) => { if(err) { throw new gutil.PluginError("webpack", err); } gutil.log("[webpack]", stats.toString({ colors: colorsSupported, chunks: false, errorDetails: true })); cb(); }); }); gulp.task('serve', () => { const config = require('./webpack.dev.config'); config.entry.app = [ // this modules required to make HRM working // it responsible for all this webpack magic 'webpack-hot-middleware/client?reload=true', // application entry point ].concat(paths.entry); var compiler = webpack(config); serve({ port: process.env.PORT || 3000, open: false, server: {baseDir: root}, middleware: [ historyApiFallback(), webpackDevMiddleware(compiler, { stats: { colors: colorsSupported, chunks: false, modules: false }, publicPath: config.output.publicPath }), webpackHotMiddleware(compiler) ] }); }); gulp.task('watch', ['serve']); gulp.task('component', () => { const cap = (val) => { return val.charAt(0).toUpperCase() + val.slice(1); }; const name = yargs.argv.name; const parentPath = yargs.argv.parent || ''; const destPath = path.join(resolveToComponents(), parentPath, name); return gulp.src(paths.blankTemplates) .pipe(template({ name: name, upCaseName: cap(name) })) .pipe(rename((path) => { path.basename = path.basename.replace('temp', name); })) .pipe(gulp.dest(destPath)); }); gulp.task('clean', (cb) => { del([paths.dest]).then(function (paths) { gutil.log("[clean]", paths); cb(); }) }); gulp.task('default', ['watch']);
mazurevich/test
gulpfile.babel.js
JavaScript
apache-2.0
3,235
// @Bind #menu1.#menuItem2.onClick !function() { dorado.MessageBox.alert("Dorado7.0 快速入门"); }; // @Bind #tree1.onDataRowClick !function(self) { // 定义Tab变量 var tab = {}; // self 代表事件所属的控件,此处指 Tree对象 // self.get("currentNode")表示获取当前被点击的节点。 with (self.get("currentNode")) { // 制定当前的tab为IFrameTab tab.$type = "IFrame"; // 定义新Tab的标签 tab.caption = get("label"); // 定义Tab的Path // get("userData")表示获取当前节点的UserData属性, // 也就是刚才设定的 sample.chapter01.HelloWorld.d tab.path = get("userData"); tab.name = get("label"); tab.closeable = true; } // 如果当前节点有指定的Path则打开新的tab if (tab.path) { with (view.get("#tabControl")) { // 根据name查找是否已经打开过当前的Tab。 // 如果没有打开过,则需要添加一个新的Tab var currentTab = getTab(tab.name); if (currentTab) { tab = currentTab; } else { // 获取ID为tabControl的对象,并添加一个新的Tab // 设定ID为tabControl的对象的当前Tab为新创建的Tab tab = addTab(tab); } // 设定当前的Tab为制定的tab set("currentTab", tab); } } };
leifchen/hello-dorado
src/demo/chapter02/Main.js
JavaScript
apache-2.0
1,297
var GPSClient = {}; GPSClient.send = function(exeurl, latitude,longitude,actionname,username) { var client = Titanium.Network.createHTTPClient({timeout : 100000}); var paramater = '&intaliouser=' + username + '&parameter=latitude:' + longitude + ','; //var paramater = '&username=' + username + '&parameter=latitude:' + longitude + ','; var paramater1 = 'longitude:' + latitude + ','; var paramater2 = 'timestamp:timestamp,'; var paramater3 = 'actionname:' + actionname + ','; var paramater4 = 'name:' + username + ','; var url = exeurl + paramater + paramater1 + paramater2 + paramater3 + paramater4; client.open(GET_REC, url); client.onload = function() { try { var resData = eval("("+this.responseText+")"); if (resData[0].error == 'Yes') { var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_yes_title"); dialog.message = resData[0].contents; dialog.show(); return; } else { return; } } catch (e) { Titanium.API.error(e); var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_catch_title"); dialog.message = Titanium.Locale.getString("gps_catch_message"); dialog.show(); return; } }; client.onerror = function() { if (client.status == 401) { var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_connect_title"); dialog.message = Titanium.Locale.getString("gps_connect_message"); dialog.show(); return; } var dialog = Titanium.UI.createAlertDialog({}); dialog.title = Titanium.Locale.getString("gps_network_title"); dialog.message = Titanium.Locale.getString("gps_network_message"); dialog.show(); return; }; client.send(); };
DaisukeSugai/salesreport
Resources/gps.js
JavaScript
apache-2.0
1,761
'use strict'; /** * 블럭 모델 * * @class Block * * @exception {Error} Messages.CONSTRUCT_ERROR * 아래 문서의 1.3 Models Folder의 항목 참조 * @link https://github.com/Gaia3D/F4DConverter/blob/master/doc/F4D_SpecificationV1.pdf */ var Block = function() { if (!(this instanceof Block)) { throw new Error(Messages.CONSTRUCT_ERROR); } /** * This class is the container which holds the VBO Cache Keys. * @type {VBOVertexIdxCacheKeysContainer} */ this.vBOVertexIdxCacheKeysContainer = new VBOVertexIdxCacheKeysContainer(); /** * @deprecated * @type {number} * @default -1 */ this.mIFCEntityType = -1; /** * small object flag. * if bbox.getMaxLength() < 0.5, isSmallObj = true * * @type {Boolean} * @default false */ this.isSmallObj = false; /** * block radius * 일반적으로 bbox.getMaxLength() / 2.0 로 선언됨. * * @type {Boolean} * @default 10 */ this.radius = 10; /** * only for test.delete this. * @deprecated */ this.vertexCount = 0; /** * 각각의 사물중 복잡한 모델이 있을 경우 Lego로 처리 * 현재는 사용하지 않으나 추후에 필요할 수 있어서 그대로 둠. * legoBlock. * @type {Lego} */ this.lego; }; /** * block 초기화. gl에서 해당 block 및 lego 삭제 * * @param {WebGLRenderingContext} gl * @param {VboManager} vboMemManager */ Block.prototype.deleteObjects = function(gl, vboMemManager) { this.vBOVertexIdxCacheKeysContainer.deleteGlObjects(gl, vboMemManager); this.vBOVertexIdxCacheKeysContainer = undefined; this.mIFCEntityType = undefined; this.isSmallObj = undefined; this.radius = undefined; // only for test. delete this. this.vertexCount = undefined; if (this.lego) { this.lego.deleteGlObjects(gl); } this.lego = undefined; }; /** * render할 준비가 됬는지 체크 * * @param {NeoReference} neoReference magoManager의 objectSelected와 비교 하기 위한 neoReference 객체 * @param {MagoManager} magoManager * @param {Number} maxSizeToRender block의 radius와 비교하기 위한 ref number. * @returns {Boolean} block의 radius가 maxSizeToRender보다 크고, block의 radius가 magoManager의 보다 크고, 카메라가 움직이고 있지 않고, magoManager의 objectSelected와 neoReference가 같을 경우 true 반환 */ Block.prototype.isReadyToRender = function(neoReference, magoManager, maxSizeToRender) { if (maxSizeToRender && (this.radius < maxSizeToRender)) { return false; } if (magoManager.isCameraMoving && this.radius < magoManager.smallObjectSize && magoManager.objectSelected !== neoReference) { return false; } return true; };
Gaia3D/mago3djs
src/mago3d/f4d/Block.js
JavaScript
apache-2.0
2,674
// 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":33}],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":36}],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":41}],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":44}],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":47}],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'; // 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' ); // MAIN // var CTORS = [ [ Float64Array, 'Float64Array' ], [ Float32Array, 'Float32Array' ], [ Int32Array, 'Int32Array' ], [ Uint32Array, 'Uint32Array' ], [ Int16Array, 'Int16Array' ], [ Uint16Array, 'Uint16Array' ], [ Int8Array, 'Int8Array' ], [ Uint8Array, 'Uint8Array' ], [ Uint8ClampedArray, 'Uint8ClampedArray' ] ]; // EXPORTS // module.exports = CTORS; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],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'; /** * Return a JSON representation of a typed array. * * @module @stdlib/array/to-json * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var toJSON = require( '@stdlib/array/to-json' ); * * var arr = new Float64Array( [ 5.0, 3.0 ] ); * var json = toJSON( arr ); * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } */ // MODULES // var toJSON = require( './to_json.js' ); // EXPORTS // module.exports = toJSON; },{"./to_json.js":18}],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'; // MODULES // var isTypedArray = require( '@stdlib/assert/is-typed-array' ); var typeName = require( './type.js' ); // MAIN // /** * Returns a JSON representation of a typed array. * * ## Notes * * - We build a JSON object representing a typed array similar to how Node.js `Buffer` objects are represented. See [Buffer][1]. * * [1]: https://nodejs.org/api/buffer.html#buffer_buf_tojson * * @param {TypedArray} arr - typed array to serialize * @throws {TypeError} first argument must be a typed array * @returns {Object} JSON representation * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var arr = new Float64Array( [ 5.0, 3.0 ] ); * var json = toJSON( arr ); * // returns { 'type': 'Float64Array', 'data': [ 5.0, 3.0 ] } */ function toJSON( arr ) { var out; var i; if ( !isTypedArray( arr ) ) { throw new TypeError( 'invalid argument. Must provide a typed array. Value: `' + arr + '`.' ); } out = {}; out.type = typeName( arr ); out.data = []; for ( i = 0; i < arr.length; i++ ) { out.data.push( arr[ i ] ); } return out; } // EXPORTS // module.exports = toJSON; },{"./type.js":19,"@stdlib/assert/is-typed-array":165}],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'; // MODULES // var instanceOf = require( '@stdlib/assert/instance-of' ); var ctorName = require( '@stdlib/utils/constructor-name' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var CTORS = require( './ctors.js' ); // MAIN // /** * Returns the typed array type. * * @private * @param {TypedArray} arr - typed array * @returns {(string|void)} typed array type * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var arr = new Float64Array( 5 ); * var str = typeName( arr ); * // returns 'Float64Array' */ function typeName( arr ) { var v; var i; // Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)... for ( i = 0; i < CTORS.length; i++ ) { if ( instanceOf( arr, CTORS[ i ][ 0 ] ) ) { return CTORS[ i ][ 1 ]; } } // Walk the prototype tree until we find an object having a desired native class... while ( arr ) { v = ctorName( arr ); for ( i = 0; i < CTORS.length; i++ ) { if ( v === CTORS[ i ][ 1 ] ) { return CTORS[ i ][ 1 ]; } } arr = getPrototypeOf( arr ); } } // EXPORTS // module.exports = typeName; },{"./ctors.js":16,"@stdlib/assert/instance-of":71,"@stdlib/utils/constructor-name":366,"@stdlib/utils/get-prototype-of":389}],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'; /** * 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":21,"./uint16array.js":22,"@stdlib/assert/has-uint16array-support":59}],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'; // 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; },{}],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'; // MAIN // var ctor = ( typeof Uint16Array === 'function' ) ? Uint16Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; /** * 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":24,"./uint32array.js":25,"@stdlib/assert/has-uint32array-support":62}],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'; // 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; },{}],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'; // MAIN // var ctor = ( typeof Uint32Array === 'function' ) ? Uint32Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; /** * 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":27,"./uint8array.js":28,"@stdlib/assert/has-uint8array-support":65}],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'; // 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; },{}],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 ctor = ( typeof Uint8Array === 'function' ) ? Uint8Array : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; /** * 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":30,"./uint8clampedarray.js":31,"@stdlib/assert/has-uint8clampedarray-support":68}],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'; // 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; },{}],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 ctor = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : void 0; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{}],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'; // MAIN // var main = ( typeof Float32Array === 'function' ) ? Float32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * 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":34}],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'; // 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":32,"@stdlib/assert/is-float32array":98,"@stdlib/constants/float64/pinf":246}],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 Float64Array === 'function' ) ? Float64Array : 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'; /** * 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":37}],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'; // 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":35,"@stdlib/assert/is-float64array":100}],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'; /** * Dummy function. * * @private */ function foo() { // No-op... } // EXPORTS // module.exports = foo; },{}],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'; /** * Test for native function `name` support. * * @module @stdlib/assert/has-function-name-support * * @example * var hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' ); * * var bool = hasFunctionNameSupport(); * // returns <boolean> */ // MODULES // var hasFunctionNameSupport = require( './main.js' ); // EXPORTS // module.exports = hasFunctionNameSupport; },{"./main.js":40}],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'; // MODULES // var foo = require( './foo.js' ); // MAIN // /** * Tests for native function `name` support. * * @returns {boolean} boolean indicating if an environment has function `name` support * * @example * var bool = hasFunctionNameSupport(); * // returns <boolean> */ function hasFunctionNameSupport() { return ( foo.name === 'foo' ); } // EXPORTS // module.exports = hasFunctionNameSupport; },{"./foo.js":38}],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'; /** * 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":43}],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'; // MAIN // var main = ( typeof Int16Array === 'function' ) ? Int16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],43:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":42,"@stdlib/assert/is-int16array":104,"@stdlib/constants/int16/max":248,"@stdlib/constants/int16/min":249}],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 `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":46}],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'; // MAIN // var main = ( typeof Int32Array === 'function' ) ? Int32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; // 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":45,"@stdlib/assert/is-int32array":106,"@stdlib/constants/int32/max":250,"@stdlib/constants/int32/min":251}],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'; /** * 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":49}],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'; // MAIN // var main = ( typeof Int8Array === 'function' ) ? Int8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; // 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":48,"@stdlib/assert/is-int8array":108,"@stdlib/constants/int8/max":252,"@stdlib/constants/int8/min":253}],50:[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":456}],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'; /** * 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":52}],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'; // 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":50,"@stdlib/assert/is-buffer":88}],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'; /** * 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":54}],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'; // 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; },{}],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 `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":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'; // 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; },{}],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'; /** * 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":58}],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'; // 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":55}],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'; /** * 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":60}],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'; // 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":61,"@stdlib/assert/is-uint16array":168,"@stdlib/constants/uint16/max":254}],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'; // MAIN // var main = ( typeof Uint16Array === 'function' ) ? Uint16Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * 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":63}],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'; // 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":64,"@stdlib/assert/is-uint32array":170,"@stdlib/constants/uint32/max":255}],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'; // MAIN // var main = ( typeof Uint32Array === 'function' ) ? Uint32Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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 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":66}],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 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":67,"@stdlib/assert/is-uint8array":172,"@stdlib/constants/uint8/max":256}],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'; // MAIN // var main = ( typeof Uint8Array === 'function' ) ? Uint8Array : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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 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":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 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":70,"@stdlib/assert/is-uint8clampedarray":174}],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'; // MAIN // var main = ( typeof Uint8ClampedArray === 'function' ) ? Uint8ClampedArray : null; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = main; },{}],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'; /** * Test whether a value has in its prototype chain a specified constructor as a prototype property. * * @module @stdlib/assert/instance-of * * @example * var instanceOf = require( '@stdlib/assert/instance-of' ); * * var bool = instanceOf( [], Array ); * // returns true * * bool = instanceOf( {}, Object ); // exception * // returns true * * bool = instanceOf( 'beep', String ); * // returns false * * bool = instanceOf( null, Object ); * // returns false * * bool = instanceOf( 5, Object ); * // returns false */ // MODULES // var instanceOf = require( './main.js' ); // EXPORTS // module.exports = instanceOf; },{"./main.js":72}],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'; // MAIN // /** * Tests whether a value has in its prototype chain a specified constructor as a prototype property. * * @param {*} value - value to test * @param {Function} constructor - constructor to test against * @throws {TypeError} constructor must be callable * @returns {boolean} boolean indicating whether a value is an instance of a provided constructor * * @example * var bool = instanceOf( [], Array ); * // returns true * * @example * var bool = instanceOf( {}, Object ); // exception * // returns true * * @example * var bool = instanceOf( 'beep', String ); * // returns false * * @example * var bool = instanceOf( null, Object ); * // returns false * * @example * var bool = instanceOf( 5, Object ); * // returns false */ function instanceOf( value, constructor ) { // TODO: replace with `isCallable` check if ( typeof constructor !== 'function' ) { throw new TypeError( 'invalid argument. `constructor` argument must be callable. Value: `'+constructor+'`.' ); } return ( value instanceof constructor ); } // EXPORTS // module.exports = instanceOf; },{}],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 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":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'; /** * 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":73,"./main.js":75,"./polyfill.js":76}],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'; // 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":423}],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'; // 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":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-enumerable-property":93,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/assert/is-integer":261}],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'; /** * 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":78}],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'; // 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":235,"@stdlib/math/base/assert/is-integer":261}],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 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":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 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":423}],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 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":82,"./object.js":83,"./primitive.js":84,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":83,"./primitive.js":84}],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 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":86,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":423}],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'; /** * 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; },{}],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'; // eslint-disable-next-line stdlib/no-redeclare var toString = Boolean.prototype.toString; // non-generic // EXPORTS // module.exports = toString; },{}],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'; // 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":85}],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'; // EXPORTS // module.exports = true; },{}],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'; /** * 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":89}],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'; // 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":143}],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'; /** * 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":91}],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'; // 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":236,"@stdlib/math/base/assert/is-integer":261}],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 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":95}],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 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":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 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":92,"./native.js":95,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],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'; // 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; },{}],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'; /** * 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":97}],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'; // 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":389,"@stdlib/utils/native-class":423}],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'; /** * 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":99}],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'; // 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":423}],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'; /** * 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":101}],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'; // 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":423}],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'; /** * 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":103}],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 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":450}],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'; /** * 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":105}],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 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":423}],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'; /** * 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":107}],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'; // 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":423}],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'; /** * 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":109}],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'; // 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":423}],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'; /** * 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":112,"./object.js":113,"./primitive.js":114,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-integer":261}],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 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":113,"./primitive.js":114}],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'; // 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":111,"@stdlib/assert/is-number":137}],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'; // 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":111,"@stdlib/assert/is-number":137}],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'; // 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":20,"@stdlib/array/uint8":26}],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. */ '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":117}],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'; // 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":115}],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 `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":119,"./object.js":120,"./primitive.js":121,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 `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":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 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":137,"@stdlib/math/base/assert/is-nan":263}],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 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":137,"@stdlib/math/base/assert/is-nan":263}],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 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":123}],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'; // 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; },{}],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'; /** * 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":125}],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. */ /* 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":122}],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 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":127,"@stdlib/assert/tools/array-like-function":179,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; /** * 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":128,"./object.js":129,"./primitive.js":130,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":129,"./primitive.js":130}],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 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":110}],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 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":110}],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'; /** * 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":132,"./object.js":133,"./primitive.js":134,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":133,"./primitive.js":134}],133:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":137}],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'; // 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":137}],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'; /** * 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":136}],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'; /** * 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; },{}],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'; /** * 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":138,"./object.js":139,"./primitive.js":140,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":139,"./primitive.js":140}],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 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":142,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/number/ctor":292,"@stdlib/utils/native-class":423}],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'; /** * 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; },{}],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 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":292}],142:[function(require,module,exports){ arguments[4][86][0].apply(exports,arguments) },{"./tostring.js":141,"dup":86}],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'; /** * 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":144,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; /** * 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; },{}],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 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":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 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":79}],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'; /** * 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":148}],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'; // 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":53,"@stdlib/assert/is-function":102,"@stdlib/assert/is-object":145,"@stdlib/utils/get-prototype-of":389,"@stdlib/utils/native-class":423}],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 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":150,"./object.js":151,"./primitive.js":152,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":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 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":110}],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'; // 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":110}],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'; var exec = RegExp.prototype.exec; // non-generic // EXPORTS // module.exports = exec; },{}],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'; /** * 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":155}],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'; // 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":156,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":423}],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 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":153}],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 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":158,"@stdlib/assert/tools/array-function":177,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; /** * 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":159,"./object.js":160,"./primitive.js":161,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":160,"./primitive.js":161}],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 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":162,"@stdlib/assert/has-tostringtag-support":57,"@stdlib/utils/native-class":423}],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'; /** * 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; },{}],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 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":163}],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'; // eslint-disable-next-line stdlib/no-redeclare var valueOf = String.prototype.valueOf; // non-generic // EXPORTS // module.exports = valueOf; },{}],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'; // 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' ); // MAIN // var CTORS = [ Float64Array, Float32Array, Int32Array, Uint32Array, Int16Array, Uint16Array, Int8Array, Uint8Array, Uint8ClampedArray ]; // EXPORTS // module.exports = CTORS; },{"@stdlib/array/float32":2,"@stdlib/array/float64":5,"@stdlib/array/int16":7,"@stdlib/array/int32":10,"@stdlib/array/int8":13,"@stdlib/array/uint16":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],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'; /** * Test if a value is a typed array. * * @module @stdlib/assert/is-typed-array * * @example * var Int8Array = require( '@stdlib/array/int8' ); * var isTypedArray = require( '@stdlib/assert/is-typed-array' ); * * var bool = isTypedArray( new Int8Array( 10 ) ); * // returns true */ // MODULES // var isTypedArray = require( './main.js' ); // EXPORTS // module.exports = isTypedArray; },{"./main.js":166}],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'; // MODULES // var ctorName = require( '@stdlib/utils/constructor-name' ); var fcnName = require( '@stdlib/utils/function-name' ); var getPrototypeOf = require( '@stdlib/utils/get-prototype-of' ); var hasFloat64ArraySupport = require( '@stdlib/assert/has-float64array-support' ); var Float64Array = require( '@stdlib/array/float64' ); var CTORS = require( './ctors.js' ); var NAMES = require( './names.json' ); // VARIABLES // // Abstract `TypedArray` class: var TypedArray = ( hasFloat64ArraySupport() ) ? getPrototypeOf( Float64Array ) : Dummy; // eslint-disable-line max-len // Ensure abstract typed array class has expected name: TypedArray = ( fcnName( TypedArray ) === 'TypedArray' ) ? TypedArray : Dummy; // FUNCTIONS // /** * Dummy constructor. * * @private */ function Dummy() {} // eslint-disable-line no-empty-function // MAIN // /** * Tests if a value is a typed array. * * @param {*} value - value to test * @returns {boolean} boolean indicating if a value is a typed array * * @example * var Int8Array = require( '@stdlib/array/int8' ); * * var bool = isTypedArray( new Int8Array( 10 ) ); * // returns true */ function isTypedArray( value ) { var v; var i; if ( typeof value !== 'object' || value === null ) { return false; } // Check for the abstract class... if ( value instanceof TypedArray ) { return true; } // Check for typed array objects from the same realm (same Node.js `vm` or same `Window` object)... for ( i = 0; i < CTORS.length; i++ ) { if ( value instanceof CTORS[ i ] ) { return true; } } // Walk the prototype tree until we find an object having a desired class... while ( value ) { v = ctorName( value ); for ( i = 0; i < NAMES.length; i++ ) { if ( NAMES[ i ] === v ) { return true; } } value = getPrototypeOf( value ); } return false; } // EXPORTS // module.exports = isTypedArray; },{"./ctors.js":164,"./names.json":167,"@stdlib/array/float64":5,"@stdlib/assert/has-float64array-support":36,"@stdlib/utils/constructor-name":366,"@stdlib/utils/function-name":386,"@stdlib/utils/get-prototype-of":389}],167:[function(require,module,exports){ module.exports=[ "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array" ] },{}],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'; /** * 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":169}],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'; // 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":423}],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'; /** * 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":171}],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'; // 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":423}],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'; /** * 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":173}],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'; // 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":423}],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'; /** * 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":175}],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'; // 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":423}],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'; // 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":79}],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'; /** * 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":176}],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'; // 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":77}],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'; /** * 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":178}],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'; // 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":202,"./harness":203,"@stdlib/assert/is-function":102,"@stdlib/streams/node/transform":348,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":53}],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'; // EXPORTS // module.exports = clearTimeout; },{}],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 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":327,"@stdlib/string/replace":354,"@stdlib/string/trim":356}],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'; // 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; },{}],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'; // 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":222}],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 // /** * 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; },{}],187:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],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'; // 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; },{}],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'; // 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; },{}],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 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":181,"./comment.js":183,"./deep_equal.js":184,"./end.js":185,"./ended.js":186,"./equal.js":187,"./exit.js":188,"./fail.js":189,"./not_deep_equal.js":191,"./not_equal.js":192,"./not_ok.js":193,"./ok.js":194,"./pass.js":195,"./run.js":196,"./skip.js":198,"./todo.js":199,"@stdlib/time/tic":358,"@stdlib/time/toc":362,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-property":381,"@stdlib/utils/inherit":402,"events":455}],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'; // 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; },{}],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'; // 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; },{}],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'; // 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; },{}],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'; // 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; },{}],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'; // 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; },{}],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 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":182,"./set_timeout.js":197}],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'; // EXPORTS // module.exports = setTimeout; },{}],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 // /** * 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; },{}],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 // /** * 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; },{}],200:[function(require,module,exports){ module.exports={ "skip": false, "iterations": null, "repeats": 3, "timeout": 300000 } },{}],201:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":203,"./log":209,"./utils/can_emit_exit.js":220,"./utils/process.js":223,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-node-writable-stream-like":124,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/noop":430,"@stdlib/utils/omit":432,"@stdlib/utils/pick":434}],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'; // 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":201,"./utils/can_emit_exit.js":220}],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'; // 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":190,"./../defaults.json":200,"./../runner":217,"./../utils/next_tick.js":222,"./init.js":204,"./validate.js":207,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":370,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 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":205,"./pretest.js":206}],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. */ '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":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":370}],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'; // 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":190,"@stdlib/assert/is-string":158,"@stdlib/utils/copy":370}],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 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":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-null":135,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149}],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'; /** * 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":180}],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'; // 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":210,"@stdlib/streams/node/transform":348,"@stdlib/string/from-code-point":352}],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'; // 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; },{}],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'; // MAIN // /** * Removes any pending benchmarks. * * @private */ function clear() { /* eslint-disable no-invalid-this */ this._benchmarks.length = 0; } // EXPORTS // module.exports = clear; },{}],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 // /** * 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; },{}],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. */ /* 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":222,"@stdlib/assert/is-string":158,"@stdlib/streams/node/transform":348}],214:[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":53,"@stdlib/regexp/eol":327,"@stdlib/string/replace":354}],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'; // 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; },{}],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'; // 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; },{}],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 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":211,"./close.js":212,"./create_stream.js":213,"./exit.js":216,"./push.js":218,"./run.js":219,"@stdlib/streams/node/transform":348,"@stdlib/utils/define-property":381,"@stdlib/utils/inherit":402,"events":455}],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. */ /* 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":214,"./encode_result.js":215,"@stdlib/assert/is-string":158}],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'; // MAIN // /** * Runs pending benchmarks. * * @private */ function run() { /* eslint-disable no-invalid-this */ this.emit( '_run' ); } // EXPORTS // module.exports = run; },{}],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'; // 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":221,"@stdlib/assert/is-browser":87}],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'; // MODULES // var proc = require( './process.js' ); // MAIN // var bool = ( proc && typeof proc.exit === 'function' ); // EXPORTS // module.exports = bool; },{"./process.js":223}],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'; // 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; },{}],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'; // MODULES // var proc = require( 'process' ); // EXPORTS // module.exports = proc; },{"process":466}],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'; /** * 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":208}],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'; /** * BLAS level 1 routine to copy values from `x` into `y`. * * @module @stdlib/blas/base/gcopy * * @example * var gcopy = require( '@stdlib/blas/base/gcopy' ); * * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, y, 1 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] * * @example * var gcopy = require( '@stdlib/blas/base/gcopy' ); * * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy.ndarray( x.length, x, 1, 0, y, 1, 0 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var gcopy = require( './main.js' ); var ndarray = require( './ndarray.js' ); // MAIN // setReadOnly( gcopy, 'ndarray', ndarray ); // EXPORTS // module.exports = gcopy; },{"./main.js":226,"./ndarray.js":227,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // VARIABLES // var M = 8; // MAIN // /** * Copies values from `x` into `y`. * * @param {PositiveInteger} N - number of values to copy * @param {NumericArray} x - input array * @param {integer} strideX - `x` stride length * @param {NumericArray} y - destination array * @param {integer} strideY - `y` stride length * @returns {NumericArray} `y` * * @example * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, y, 1 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ function gcopy( N, x, strideX, y, strideY ) { var ix; var iy; var m; var i; if ( N <= 0 ) { return y; } // Use unrolled loops if both strides are equal to `1`... if ( strideX === 1 && strideY === 1 ) { m = N % M; // If we have a remainder, run a clean-up loop... if ( m > 0 ) { for ( i = 0; i < m; i++ ) { y[ i ] = x[ i ]; } } if ( N < M ) { return y; } for ( i = m; i < N; i += M ) { y[ i ] = x[ i ]; y[ i+1 ] = x[ i+1 ]; y[ i+2 ] = x[ i+2 ]; y[ i+3 ] = x[ i+3 ]; y[ i+4 ] = x[ i+4 ]; y[ i+5 ] = x[ i+5 ]; y[ i+6 ] = x[ i+6 ]; y[ i+7 ] = x[ i+7 ]; } return y; } if ( strideX < 0 ) { ix = (1-N) * strideX; } else { ix = 0; } if ( strideY < 0 ) { iy = (1-N) * strideY; } else { iy = 0; } for ( i = 0; i < N; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } return y; } // EXPORTS // module.exports = gcopy; },{}],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'; // VARIABLES // var M = 8; // MAIN // /** * Copies values from `x` into `y`. * * @param {PositiveInteger} N - number of values to copy * @param {NumericArray} x - input array * @param {integer} strideX - `x` stride length * @param {NonNegativeInteger} offsetX - starting `x` index * @param {NumericArray} y - destination array * @param {integer} strideY - `y` stride length * @param {NonNegativeInteger} offsetY - starting `y` index * @returns {NumericArray} `y` * * @example * var x = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; * var y = [ 6.0, 7.0, 8.0, 9.0, 10.0 ]; * * gcopy( x.length, x, 1, 0, y, 1, 0 ); * // y => [ 1.0, 2.0, 3.0, 4.0, 5.0 ] */ function gcopy( N, x, strideX, offsetX, y, strideY, offsetY ) { var ix; var iy; var m; var i; if ( N <= 0 ) { return y; } ix = offsetX; iy = offsetY; // Use unrolled loops if both strides are equal to `1`... if ( strideX === 1 && strideY === 1 ) { m = N % M; // If we have a remainder, run a clean-up loop... if ( m > 0 ) { for ( i = 0; i < m; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } } if ( N < M ) { return y; } for ( i = m; i < N; i += M ) { y[ iy ] = x[ ix ]; y[ iy+1 ] = x[ ix+1 ]; y[ iy+2 ] = x[ ix+2 ]; y[ iy+3 ] = x[ ix+3 ]; y[ iy+4 ] = x[ ix+4 ]; y[ iy+5 ] = x[ ix+5 ]; y[ iy+6 ] = x[ ix+6 ]; y[ iy+7 ] = x[ ix+7 ]; ix += M; iy += M; } return y; } for ( i = 0; i < N; i++ ) { y[ iy ] = x[ ix ]; ix += strideX; iy += strideY; } return y; } // EXPORTS // module.exports = gcopy; },{}],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'; // MAIN // var ctor = require( 'buffer' ).Buffer; // eslint-disable-line stdlib/require-globals // EXPORTS // module.exports = ctor; },{"buffer":456}],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'; /** * 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":228,"./polyfill.js":230,"@stdlib/assert/has-node-buffer-support":51}],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'; // TODO: write (browser) polyfill // MAIN // /** * Buffer constructor. * * @throws {Error} not implemented */ function polyfill() { throw new Error( 'not implemented' ); } // EXPORTS // module.exports = polyfill; },{}],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'; // 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":102,"@stdlib/buffer/ctor":229}],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'; /** * 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":231,"./main.js":233,"./polyfill.js":234}],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'; // 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":88,"@stdlib/buffer/ctor":229}],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'; // 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":88,"@stdlib/buffer/ctor":229}],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 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; },{}],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 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; },{}],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'; /** * Difference between one and the smallest value greater than one that can be represented as a double-precision floating-point number. * * @module @stdlib/constants/float64/eps * @type {number} * * @example * var FLOAT64_EPSILON = require( '@stdlib/constants/float64/eps' ); * // returns 2.220446049250313e-16 */ // MAIN // /** * Difference between one and the smallest value greater than one that can be represented as a double-precision floating-point number. * * ## Notes * * The difference is * * ```tex * \frac{1}{2^{52}} * ``` * * @constant * @type {number} * @default 2.220446049250313e-16 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} * @see [Machine Epsilon]{@link https://en.wikipedia.org/wiki/Machine_epsilon} */ var FLOAT64_EPSILON = 2.2204460492503130808472633361816E-16; // EXPORTS // module.exports = FLOAT64_EPSILON; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * The maximum biased base 2 exponent for a subnormal double-precision floating-point number. * * @module @stdlib/constants/float64/max-base2-exponent-subnormal * @type {integer32} * * @example * var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' ); * // returns -1023 */ // MAIN // /** * The maximum biased base 2 exponent for a subnormal double-precision floating-point number. * * ```text * 00000000000 => 0 - BIAS = -1023 * ``` * * where `BIAS = 1023`. * * @constant * @type {integer32} * @default -1023 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL = -1023|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_MAX_BASE2_EXPONENT_SUBNORMAL; },{}],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'; /** * The maximum biased base 2 exponent for a double-precision floating-point number. * * @module @stdlib/constants/float64/max-base2-exponent * @type {integer32} * * @example * var FLOAT64_MAX_BASE2_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' ); * // returns 1023 */ // MAIN // /** * The maximum biased base 2 exponent for a double-precision floating-point number. * * ```text * 11111111110 => 2046 - BIAS = 1023 * ``` * * where `BIAS = 1023`. * * @constant * @type {integer32} * @default 1023 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX_BASE2_EXPONENT = 1023|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_MAX_BASE2_EXPONENT; },{}],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'; /** * Maximum safe double-precision floating-point integer. * * @module @stdlib/constants/float64/max-safe-integer * @type {number} * * @example * var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); * // returns 9007199254740991 */ // MAIN // /** * Maximum safe double-precision floating-point integer. * * ## Notes * * The integer has the value * * ```tex * 2^{53} - 1 * ``` * * @constant * @type {number} * @default 9007199254740991 * @see [Safe Integers]{@link http://www.2ality.com/2013/10/safe-integers.html} * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MAX_SAFE_INTEGER = 9007199254740991; // EXPORTS // module.exports = FLOAT64_MAX_SAFE_INTEGER; },{}],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'; /** * The minimum biased base 2 exponent for a subnormal double-precision floating-point number. * * @module @stdlib/constants/float64/min-base2-exponent-subnormal * @type {integer32} * * @example * var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' ); * // returns -1074 */ // MAIN // /** * The minimum biased base 2 exponent for a subnormal double-precision floating-point number. * * ```text * -(BIAS+(52-1)) = -(1023+51) = -1074 * ``` * * where `BIAS = 1023` and `52` is the number of digits in the significand. * * @constant * @type {integer32} * @default -1074 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL = -1074|0; // asm type annotation // EXPORTS // module.exports = FLOAT64_MIN_BASE2_EXPONENT_SUBNORMAL; },{}],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'; /** * 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":292}],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'; /** * 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; },{}],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'; /** * Smallest positive double-precision floating-point normal number. * * @module @stdlib/constants/float64/smallest-normal * @type {number} * * @example * var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' ); * // returns 2.2250738585072014e-308 */ // MAIN // /** * The smallest positive double-precision floating-point normal number. * * ## Notes * * The number has the value * * ```tex * \frac{1}{2^{1023-1}} * ``` * * which corresponds to the bit sequence * * ```binarystring * 0 00000000001 00000000000000000000 00000000000000000000000000000000 * ``` * * @constant * @type {number} * @default 2.2250738585072014e-308 * @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985} */ var FLOAT64_SMALLEST_NORMAL = 2.2250738585072014e-308; // EXPORTS // module.exports = FLOAT64_SMALLEST_NORMAL; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],254:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],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'; /** * 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; },{}],258:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],259:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 infinite. * * @module @stdlib/math/base/assert/is-infinite * * @example * var isInfinite = require( '@stdlib/math/base/assert/is-infinite' ); * * var bool = isInfinite( Infinity ); * // returns true * * bool = isInfinite( -Infinity ); * // returns true * * bool = isInfinite( 5.0 ); * // returns false * * bool = isInfinite( NaN ); * // returns false */ // MODULES // var isInfinite = require( './main.js' ); // EXPORTS // module.exports = isInfinite; },{"./main.js":260}],260:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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' ); // MAIN // /** * Tests if a double-precision floating-point numeric value is infinite. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is infinite * * @example * var bool = isInfinite( Infinity ); * // returns true * * @example * var bool = isInfinite( -Infinity ); * // returns true * * @example * var bool = isInfinite( 5.0 ); * // returns false * * @example * var bool = isInfinite( NaN ); * // returns false */ function isInfinite( x ) { return (x === PINF || x === NINF); } // EXPORTS // module.exports = isInfinite; },{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246}],261:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":262}],262:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":277}],263:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":264}],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'; // 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; },{}],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'; /** * Test if a double-precision floating-point numeric value is positive zero. * * @module @stdlib/math/base/assert/is-positive-zero * * @example * var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' ); * * var bool = isPositiveZero( 0.0 ); * // returns true * * bool = isPositiveZero( -0.0 ); * // returns false */ // MODULES // var isPositiveZero = require( './main.js' ); // EXPORTS // module.exports = isPositiveZero; },{"./main.js":266}],266:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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' ); // MAIN // /** * Tests if a double-precision floating-point numeric value is positive zero. * * @param {number} x - value to test * @returns {boolean} boolean indicating whether the value is positive zero * * @example * var bool = isPositiveZero( 0.0 ); * // returns true * * @example * var bool = isPositiveZero( -0.0 ); * // returns false */ function isPositiveZero( x ) { return (x === 0.0 && 1.0/x === PINF); } // EXPORTS // module.exports = isPositiveZero; },{"@stdlib/constants/float64/pinf":246}],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'; /** * Compute an absolute value of a double-precision floating-point number. * * @module @stdlib/math/base/special/abs * * @example * var abs = require( '@stdlib/math/base/special/abs' ); * * var v = abs( -1.0 ); * // returns 1.0 * * v = abs( 2.0 ); * // returns 2.0 * * v = abs( 0.0 ); * // returns 0.0 * * v = abs( -0.0 ); * // returns 0.0 * * v = abs( NaN ); * // returns NaN */ // MODULES // var abs = require( './main.js' ); // EXPORTS // module.exports = abs; },{"./main.js":268}],268:[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 // /** * Computes the absolute value of a double-precision floating-point number `x`. * * @param {number} x - input value * @returns {number} absolute value * * @example * var v = abs( -1.0 ); * // returns 1.0 * * @example * var v = abs( 2.0 ); * // returns 2.0 * * @example * var v = abs( 0.0 ); * // returns 0.0 * * @example * var v = abs( -0.0 ); * // returns 0.0 * * @example * var v = abs( NaN ); * // returns NaN */ function abs( x ) { return Math.abs( x ); // eslint-disable-line stdlib/no-builtin-math } // EXPORTS // module.exports = abs; },{}],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'; /** * Round a double-precision floating-point number toward positive infinity. * * @module @stdlib/math/base/special/ceil * * @example * var ceil = require( '@stdlib/math/base/special/ceil' ); * * var v = ceil( -4.2 ); * // returns -4.0 * * v = ceil( 9.99999 ); * // returns 10.0 * * v = ceil( 0.0 ); * // returns 0.0 * * v = ceil( NaN ); * // returns NaN */ // MODULES // var ceil = require( './main.js' ); // EXPORTS // module.exports = ceil; },{"./main.js":270}],270:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 positive infinity. * * @param {number} x - input value * @returns {number} rounded value * * @example * var v = ceil( -4.2 ); * // returns -4.0 * * @example * var v = ceil( 9.99999 ); * // returns 10.0 * * @example * var v = ceil( 0.0 ); * // returns 0.0 * * @example * var v = ceil( NaN ); * // returns NaN */ var ceil = Math.ceil; // eslint-disable-line stdlib/no-builtin-math // EXPORTS // module.exports = ceil; },{}],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 toWords = require( '@stdlib/number/float64/base/to-words' ); var getHighWord = require( '@stdlib/number/float64/base/get-high-word' ); var fromWords = require( '@stdlib/number/float64/base/from-words' ); // VARIABLES // // 10000000000000000000000000000000 => 2147483648 => 0x80000000 var SIGN_MASK = 0x80000000>>>0; // asm type annotation // 01111111111111111111111111111111 => 2147483647 => 0x7fffffff var MAGNITUDE_MASK = 0x7fffffff|0; // asm type annotation // High/low words workspace: var WORDS = [ 0, 0 ]; // WARNING: not thread safe // MAIN // /** * Returns a double-precision floating-point number with the magnitude of `x` and the sign of `y`. * * @param {number} x - number from which to derive a magnitude * @param {number} y - number from which to derive a sign * @returns {number} a double-precision floating-point number * * @example * var z = copysign( -3.14, 10.0 ); * // returns 3.14 * * @example * var z = copysign( 3.14, -1.0 ); * // returns -3.14 * * @example * var z = copysign( 1.0, -0.0 ); * // returns -1.0 * * @example * var z = copysign( -3.14, -0.0 ); * // returns -3.14 * * @example * var z = copysign( -0.0, 1.0 ); * // returns 0.0 */ function copysign( x, y ) { var hx; var hy; // Split `x` into higher and lower order words: toWords( WORDS, x ); hx = WORDS[ 0 ]; // Turn off the sign bit of `x`: hx &= MAGNITUDE_MASK; // Extract the higher order word from `y`: hy = getHighWord( y ); // Leave only the sign bit of `y` turned on: hy &= SIGN_MASK; // Copy the sign bit of `y` to `x`: hx |= hy; // Return a new value having the same magnitude as `x`, but with the sign of `y`: return fromWords( hx, WORDS[ 1 ] ); } // EXPORTS // module.exports = copysign; },{"@stdlib/number/float64/base/from-words":296,"@stdlib/number/float64/base/get-high-word":300,"@stdlib/number/float64/base/to-words":305}],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'; /** * Return a double-precision floating-point number with the magnitude of `x` and the sign of `y`. * * @module @stdlib/math/base/special/copysign * * @example * var copysign = require( '@stdlib/math/base/special/copysign' ); * * var z = copysign( -3.14, 10.0 ); * // returns 3.14 * * z = copysign( 3.14, -1.0 ); * // returns -3.14 * * z = copysign( 1.0, -0.0 ); * // returns -1.0 * * z = copysign( -3.14, -0.0 ); * // returns -3.14 * * z = copysign( -0.0, 1.0 ); * // returns 0.0 */ // MODULES // var copysign = require( './copysign.js' ); // EXPORTS // module.exports = copysign; },{"./copysign.js":271}],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. * * * ## Notice * * The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c}. The implementation follows the original, but has been modified for JavaScript. * * ```text * Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ``` */ 'use strict'; // MODULES // var isnan = require( '@stdlib/math/base/assert/is-nan' ); var trunc = require( '@stdlib/math/base/special/trunc' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var expmulti = require( './expmulti.js' ); // VARIABLES // var LN2_HI = 6.93147180369123816490e-01; var LN2_LO = 1.90821492927058770002e-10; var LOG2_E = 1.44269504088896338700e+00; var OVERFLOW = 7.09782712893383973096e+02; var UNDERFLOW = -7.45133219101941108420e+02; var NEARZERO = 1.0 / (1 << 28); // 2^-28; var NEG_NEARZERO = -NEARZERO; // MAIN // /** * Evaluates the natural exponential function. * * ## Method * * 1. We reduce \\( x \\) to an \\( r \\) so that \\( |r| \leq 0.5 \cdot \ln(2) \approx 0.34658 \\). Given \\( x \\), we find an \\( r \\) and integer \\( k \\) such that * * ```tex * \begin{align*} * x &= k \cdot \ln(2) + r \\ * |r| &\leq 0.5 \cdot \ln(2) * \end{align*} * ``` * * <!-- <note> --> * * \\( r \\) can be represented as \\( r = \mathrm{hi} - \mathrm{lo} \\) for better accuracy. * * <!-- </note> --> * * 2. We approximate of \\( e^{r} \\) by a special rational function on the interval \\(\[0,0.34658]\\): * * ```tex * \begin{align*} * R\left(r^2\right) &= r \cdot \frac{ e^{r}+1 }{ e^{r}-1 } \\ * &= 2 + \frac{r^2}{6} - \frac{r^4}{360} + \ldots * \end{align*} * ``` * * We use a special Remes algorithm on \\(\[0,0.34658]\\) to generate a polynomial of degree \\(5\\) to approximate \\(R\\). The maximum error of this polynomial approximation is bounded by \\(2^{-59}\\). In other words, * * ```tex * R(z) \sim 2 + P_1 z + P_2 z^2 + P_3 z^3 + P_4 z^4 + P_5 z^5 * ``` * * where \\( z = r^2 \\) and * * ```tex * \left| 2 + P_1 z + \ldots + P_5 z^5 - R(z) \right| \leq 2^{-59} * ``` * * <!-- <note> --> * * The values of \\( P_1 \\) to \\( P_5 \\) are listed in the source code. * * <!-- </note> --> * * The computation of \\( e^{r} \\) thus becomes * * ```tex * \begin{align*} * e^{r} &= 1 + \frac{2r}{R-r} \\ * &= 1 + r + \frac{r \cdot R_1(r)}{2 - R_1(r)}\ \text{for better accuracy} * \end{align*} * ``` * * where * * ```tex * R_1(r) = r - P_1\ r^2 + P_2\ r^4 + \ldots + P_5\ r^{10} * ``` * * 3. We scale back to obtain \\( e^{x} \\). From step 1, we have * * ```tex * e^{x} = 2^k e^{r} * ``` * * * ## Special Cases * * ```tex * \begin{align*} * e^\infty &= \infty \\ * e^{-\infty} &= 0 \\ * e^{\mathrm{NaN}} &= \mathrm{NaN} \\ * e^0 &= 1\ \mathrm{is\ exact\ for\ finite\ argument\ only} * \end{align*} * ``` * * ## Notes * * - According to an error analysis, the error is always less than \\(1\\) ulp (unit in the last place). * * - For an IEEE double, * * - if \\(x > 7.09782712893383973096\mbox{e+}02\\), then \\(e^{x}\\) overflows * - if \\(x < -7.45133219101941108420\mbox{e+}02\\), then \\(e^{x}\\) underflows * * - The hexadecimal values included in the source code are the intended ones for the used constants. Decimal values may be used, provided that the compiler will convert from decimal to binary accurately enough to produce the intended hexadecimal values. * * * @param {number} x - input value * @returns {number} function value * * @example * var v = exp( 4.0 ); * // returns ~54.5982 * * @example * var v = exp( -9.0 ); * // returns ~1.234e-4 * * @example * var v = exp( 0.0 ); * // returns 1.0 * * @example * var v = exp( NaN ); * // returns NaN */ function exp( x ) { var hi; var lo; var k; if ( isnan( x ) || x === PINF ) { return x; } if ( x === NINF ) { return 0.0; } if ( x > OVERFLOW ) { return PINF; } if ( x < UNDERFLOW ) { return 0.0; } if ( x > NEG_NEARZERO && x < NEARZERO ) { return 1.0 + x; } // Reduce and compute `r = hi - lo` for extra precision. if ( x < 0.0 ) { k = trunc( (LOG2_E*x) - 0.5 ); } else { k = trunc( (LOG2_E*x) + 0.5 ); } hi = x - (k*LN2_HI); lo = k * LN2_LO; return expmulti( hi, lo, k ); } // EXPORTS // module.exports = exp; },{"./expmulti.js":274,"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/trunc":288}],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. * * * ## Notice * * The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c}. The implementation follows the original, but has been modified for JavaScript. * * ```text * Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ``` */ 'use strict'; // MODULES // var ldexp = require( '@stdlib/math/base/special/ldexp' ); var polyvalP = require( './polyval_p.js' ); // MAIN // /** * Computes \\(e^{r} 2^k\\) where \\(r = \mathrm{hi} - \mathrm{lo}\\) and \\(|r| \leq \ln(2)/2\\). * * @private * @param {number} hi - upper bound * @param {number} lo - lower bound * @param {integer} k - power of 2 * @returns {number} function value */ function expmulti( hi, lo, k ) { var r; var t; var c; var y; r = hi - lo; t = r * r; c = r - ( t*polyvalP( t ) ); y = 1.0 - ( lo - ( (r*c)/(2.0-c) ) - hi); return ldexp( y, k ); } // EXPORTS // module.exports = expmulti; },{"./polyval_p.js":276,"@stdlib/math/base/special/ldexp":279}],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'; /** * Evaluate the natural exponential function. * * @module @stdlib/math/base/special/exp * * @example * var exp = require( '@stdlib/math/base/special/exp' ); * * var v = exp( 4.0 ); * // returns ~54.5982 * * v = exp( -9.0 ); * // returns ~1.234e-4 * * v = exp( 0.0 ); * // returns 1.0 * * v = exp( NaN ); * // returns NaN */ // MODULES // var exp = require( './exp.js' ); // EXPORTS // module.exports = exp; },{"./exp.js":273}],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. */ /* This is a generated file. Do not edit directly. */ 'use strict'; // MAIN // /** * Evaluates a polynomial. * * ## Notes * * - The implementation uses [Horner's rule][horners-method] for efficient computation. * * [horners-method]: https://en.wikipedia.org/wiki/Horner%27s_method * * * @private * @param {number} x - value at which to evaluate the polynomial * @returns {number} evaluated polynomial */ function evalpoly( x ) { if ( x === 0.0 ) { return 0.16666666666666602; } return 0.16666666666666602 + (x * (-0.0027777777777015593 + (x * (0.00006613756321437934 + (x * (-0.0000016533902205465252 + (x * 4.1381367970572385e-8))))))); // eslint-disable-line max-len } // EXPORTS // module.exports = evalpoly; },{}],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'; /** * 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":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'; // 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; },{}],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'; /** * Multiply a double-precision floating-point number by an integer power of two. * * @module @stdlib/math/base/special/ldexp * * @example * var ldexp = require( '@stdlib/math/base/special/ldexp' ); * * var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8 * // returns 4.0 * * x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4) * // returns 1.0 * * x = ldexp( 0.0, 20 ); * // returns 0.0 * * x = ldexp( -0.0, 39 ); * // returns -0.0 * * x = ldexp( NaN, -101 ); * // returns NaN * * x = ldexp( Infinity, 11 ); * // returns Infinity * * x = ldexp( -Infinity, -118 ); * // returns -Infinity */ // MODULES // var ldexp = require( './ldexp.js' ); // EXPORTS // module.exports = ldexp; },{"./ldexp.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'; // NOTES // /* * => ldexp: load exponent (see [The Open Group]{@link http://pubs.opengroup.org/onlinepubs/9699919799/functions/ldexp.html} and [cppreference]{@link http://en.cppreference.com/w/c/numeric/math/ldexp}). */ // MODULES // var PINF = require( '@stdlib/constants/float64/pinf' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var BIAS = require( '@stdlib/constants/float64/exponent-bias' ); var MAX_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent' ); var MAX_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/max-base2-exponent-subnormal' ); var MIN_SUBNORMAL_EXPONENT = require( '@stdlib/constants/float64/min-base2-exponent-subnormal' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var isInfinite = require( '@stdlib/math/base/assert/is-infinite' ); var copysign = require( '@stdlib/math/base/special/copysign' ); var normalize = require( '@stdlib/number/float64/base/normalize' ); var floatExp = require( '@stdlib/number/float64/base/exponent' ); var toWords = require( '@stdlib/number/float64/base/to-words' ); var fromWords = require( '@stdlib/number/float64/base/from-words' ); // VARIABLES // // 1/(1<<52) = 1/(2**52) = 1/4503599627370496 var TWO52_INV = 2.220446049250313e-16; // Exponent all 0s: 1 00000000000 11111111111111111111 => 2148532223 var CLEAR_EXP_MASK = 0x800fffff>>>0; // asm type annotation // Normalization workspace: var FRAC = [ 0.0, 0.0 ]; // WARNING: not thread safe // High/low words workspace: var WORDS = [ 0, 0 ]; // WARNING: not thread safe // MAIN // /** * Multiplies a double-precision floating-point number by an integer power of two. * * @param {number} frac - fraction * @param {integer} exp - exponent * @returns {number} double-precision floating-point number * * @example * var x = ldexp( 0.5, 3 ); // => 0.5 * 2^3 = 0.5 * 8 * // returns 4.0 * * @example * var x = ldexp( 4.0, -2 ); // => 4 * 2^(-2) = 4 * (1/4) * // returns 1.0 * * @example * var x = ldexp( 0.0, 20 ); * // returns 0.0 * * @example * var x = ldexp( -0.0, 39 ); * // returns -0.0 * * @example * var x = ldexp( NaN, -101 ); * // returns NaN * * @example * var x = ldexp( Infinity, 11 ); * // returns Infinity * * @example * var x = ldexp( -Infinity, -118 ); * // returns -Infinity */ function ldexp( frac, exp ) { var high; var m; if ( frac === 0.0 || // handles +-0 isnan( frac ) || isInfinite( frac ) ) { return frac; } // Normalize the input fraction: normalize( FRAC, frac ); frac = FRAC[ 0 ]; exp += FRAC[ 1 ]; // Extract the exponent from `frac` and add it to `exp`: exp += floatExp( frac ); // Check for underflow/overflow... if ( exp < MIN_SUBNORMAL_EXPONENT ) { return copysign( 0.0, frac ); } if ( exp > MAX_EXPONENT ) { if ( frac < 0.0 ) { return NINF; } return PINF; } // Check for a subnormal and scale accordingly to retain precision... if ( exp <= MAX_SUBNORMAL_EXPONENT ) { exp += 52; m = TWO52_INV; } else { m = 1.0; } // Split the fraction into higher and lower order words: toWords( WORDS, frac ); high = WORDS[ 0 ]; // Clear the exponent bits within the higher order word: high &= CLEAR_EXP_MASK; // Set the exponent bits to the new exponent: high |= ((exp+BIAS) << 20); // Create a new floating-point number: return m * fromWords( high, WORDS[ 1 ] ); } // EXPORTS // module.exports = ldexp; },{"@stdlib/constants/float64/exponent-bias":238,"@stdlib/constants/float64/max-base2-exponent":242,"@stdlib/constants/float64/max-base2-exponent-subnormal":241,"@stdlib/constants/float64/min-base2-exponent-subnormal":244,"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-infinite":259,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/copysign":272,"@stdlib/number/float64/base/exponent":294,"@stdlib/number/float64/base/from-words":296,"@stdlib/number/float64/base/normalize":302,"@stdlib/number/float64/base/to-words":305}],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'; /** * Return the maximum value. * * @module @stdlib/math/base/special/max * * @example * var max = require( '@stdlib/math/base/special/max' ); * * var v = max( 3.14, 4.2 ); * // returns 4.2 * * v = max( 5.9, 3.14, 4.2 ); * // returns 5.9 * * v = max( 3.14, NaN ); * // returns NaN * * v = max( +0.0, -0.0 ); * // returns +0.0 */ // MODULES // var max = require( './max.js' ); // EXPORTS // module.exports = max; },{"./max.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 isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Returns the maximum value. * * @param {number} [x] - first number * @param {number} [y] - second number * @param {...number} [args] - numbers * @returns {number} maximum value * * @example * var v = max( 3.14, 4.2 ); * // returns 4.2 * * @example * var v = max( 5.9, 3.14, 4.2 ); * // returns 5.9 * * @example * var v = max( 3.14, NaN ); * // returns NaN * * @example * var v = max( +0.0, -0.0 ); * // returns +0.0 */ function max( x, y ) { var len; var m; var v; var i; len = arguments.length; if ( len === 2 ) { if ( isnan( x ) || isnan( y ) ) { return NaN; } if ( x === PINF || y === PINF ) { return PINF; } if ( x === y && x === 0.0 ) { if ( isPositiveZero( x ) ) { return x; } return y; } if ( x > y ) { return x; } return y; } m = NINF; for ( i = 0; i < len; i++ ) { v = arguments[ i ]; if ( isnan( v ) || v === PINF ) { return v; } if ( v > m ) { m = v; } else if ( v === m && v === 0.0 && isPositiveZero( v ) ) { m = v; } } return m; } // EXPORTS // module.exports = max; },{"@stdlib/constants/float64/ninf":245,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/assert/is-positive-zero":265}],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'; /** * 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":284}],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 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":285}],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 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":238,"@stdlib/constants/float64/high-word-exponent-mask":239,"@stdlib/constants/float64/high-word-significand-mask":240,"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/number/float64/base/from-words":296,"@stdlib/number/float64/base/to-words":305}],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'; // 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":287}],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'; // 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; },{}],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'; /** * Round a double-precision floating-point number toward zero. * * @module @stdlib/math/base/special/trunc * * @example * var trunc = require( '@stdlib/math/base/special/trunc' ); * * var v = trunc( -4.2 ); * // returns -4.0 * * v = trunc( 9.99999 ); * // returns 9.0 * * v = trunc( 0.0 ); * // returns 0.0 * * v = trunc( -0.0 ); * // returns -0.0 * * v = trunc( NaN ); * // returns NaN * * v = trunc( Infinity ); * // returns Infinity * * v = trunc( -Infinity ); * // returns -Infinity */ // MODULES // var trunc = require( './main.js' ); // EXPORTS // module.exports = trunc; },{"./main.js":289}],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'; // MODULES // var floor = require( '@stdlib/math/base/special/floor' ); var ceil = require( '@stdlib/math/base/special/ceil' ); // MAIN // /** * Rounds a double-precision floating-point number toward zero. * * @param {number} x - input value * @returns {number} rounded value * * @example * var v = trunc( -4.2 ); * // returns -4.0 * * @example * var v = trunc( 9.99999 ); * // returns 9.0 * * @example * var v = trunc( 0.0 ); * // returns 0.0 * * @example * var v = trunc( -0.0 ); * // returns -0.0 * * @example * var v = trunc( NaN ); * // returns NaN * * @example * var v = trunc( Infinity ); * // returns Infinity * * @example * var v = trunc( -Infinity ); * // returns -Infinity */ function trunc( x ) { if ( x < 0.0 ) { return ceil( x ); } return floor( x ); } // EXPORTS // module.exports = trunc; },{"@stdlib/math/base/special/ceil":269,"@stdlib/math/base/special/floor":277}],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'; /** * Perform C-like multiplication of two unsigned 32-bit integers. * * @module @stdlib/math/base/special/uimul * * @example * var uimul = require( '@stdlib/math/base/special/uimul' ); * * var v = uimul( 10>>>0, 4>>>0 ); * // returns 40 */ // MODULES // var uimul = require( './main.js' ); // EXPORTS // module.exports = uimul; },{"./main.js":291}],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'; // VARIABLES // // Define a mask for the least significant 16 bits (low word): 65535 => 0x0000ffff => 00000000000000001111111111111111 var LOW_WORD_MASK = 0x0000ffff>>>0; // asm type annotation // MAIN // /** * Performs C-like multiplication of two unsigned 32-bit integers. * * ## Method * * - To emulate C-like multiplication without the aid of 64-bit integers, we recognize that a 32-bit integer can be split into two 16-bit words * * ```tex * a = w_h*2^{16} + w_l * ``` * * where \\( w_h \\) is the most significant 16 bits and \\( w_l \\) is the least significant 16 bits. For example, consider the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) * * ```binarystring * 11111111111111111111111111111111 * ``` * * The 16-bit high word is then * * ```binarystring * 1111111111111111 * ``` * * and the 16-bit low word * * ```binarystring * 1111111111111111 * ``` * * If we cast the high word to 32-bit precision and multiply by \\( 2^{16} \\) (equivalent to a 16-bit left shift), then the bit sequence is * * ```binarystring * 11111111111111110000000000000000 * ``` * * Similarly, upon casting the low word to 32-bit precision, the bit sequence is * * ```binarystring * 00000000000000001111111111111111 * ``` * * From the rules of binary addition, we recognize that adding the two 32-bit values for the high and low words will return our original value \\( 2^{32}-1 \\). * * - Accordingly, the multiplication of two 32-bit integers can be expressed * * ```tex * \begin{align*} * a \cdot b &= ( a_h \cdot 2^{16} + a_l) \cdot ( b_h \cdot 2^{16} + b_l) \\ * &= a_l \cdot b_l + a_h \cdot b_l \cdot 2^{16} + a_l \cdot b_h \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} \\ * &= a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) \cdot 2^{16} + (a_h \cdot b_h) \cdot 2^{32} * \end{align*} * ``` * * - We note that multiplying (dividing) an integer by \\( 2^n \\) is equivalent to performing a left (right) shift of \\( n \\) bits. * * - Further, as we want to return an integer of the same precision, for a 32-bit integer, the return value will be modulo \\( 2^{32} \\). Stated another way, we only care about the low word of a 64-bit result. * * - Accordingly, the last term, being evenly divisible by \\( 2^{32} \\), drops from the equation leaving the remaining two terms as the remainder. * * ```tex * a \cdot b = a_l \cdot b_l + (a_h \cdot b_l + a_l \cdot b_h) << 16 * ``` * * - Lastly, the second term in the above equation contributes to the middle bits and may cause the product to "overflow". However, we can disregard (`>>>0`) overflow bits due modulo arithmetic, as discussed earlier with regard to the term involving the partial product of high words. * * * @param {uinteger32} a - integer * @param {uinteger32} b - integer * @returns {uinteger32} product * * @example * var v = uimul( 10>>>0, 4>>>0 ); * // returns 40 */ function uimul( a, b ) { var lbits; var mbits; var ha; var hb; var la; var lb; a >>>= 0; // asm type annotation b >>>= 0; // asm type annotation // Isolate the most significant 16-bits: ha = ( a>>>16 )>>>0; // asm type annotation hb = ( b>>>16 )>>>0; // asm type annotation // Isolate the least significant 16-bits: la = ( a&LOW_WORD_MASK )>>>0; // asm type annotation lb = ( b&LOW_WORD_MASK )>>>0; // asm type annotation // Compute partial sums: lbits = ( la*lb )>>>0; // asm type annotation; no integer overflow possible mbits = ( ((ha*lb) + (la*hb))<<16 )>>>0; // asm type annotation; possible integer overflow // The final `>>>0` converts the intermediate sum to an unsigned integer (possible integer overflow during sum): return ( lbits + mbits )>>>0; // asm type annotation } // EXPORTS // module.exports = uimul; },{}],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'; /** * 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":293}],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'; // EXPORTS // module.exports = Number; // eslint-disable-line stdlib/require-globals },{}],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'; /** * Return an integer corresponding to the unbiased exponent of a double-precision floating-point number. * * @module @stdlib/number/float64/base/exponent * * @example * var exponent = require( '@stdlib/number/float64/base/exponent' ); * * var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307 * // returns -1019 * * exp = exponent( -3.14 ); * // returns 1 * * exp = exponent( 0.0 ); * // returns -1023 * * exp = exponent( NaN ); * // returns 1024 */ // MODULES // var exponent = require( './main.js' ); // EXPORTS // module.exports = exponent; },{"./main.js":295}],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'; // MODULES // var getHighWord = require( '@stdlib/number/float64/base/get-high-word' ); var EXP_MASK = require( '@stdlib/constants/float64/high-word-exponent-mask' ); var BIAS = require( '@stdlib/constants/float64/exponent-bias' ); // MAIN // /** * Returns an integer corresponding to the unbiased exponent of a double-precision floating-point number. * * @param {number} x - input value * @returns {integer32} unbiased exponent * * @example * var exp = exponent( 3.14e-307 ); // => 2**-1019 ~ 1e-307 * // returns -1019 * * @example * var exp = exponent( -3.14 ); * // returns 1 * * @example * var exp = exponent( 0.0 ); * // returns -1023 * * @example * var exp = exponent( NaN ); * // returns 1024 */ function exponent( x ) { // Extract from the input value a higher order word (unsigned 32-bit integer) which contains the exponent: var high = getHighWord( x ); // Apply a mask to isolate only the exponent bits and then shift off all bits which are part of the fraction: high = ( high & EXP_MASK ) >>> 20; // Remove the bias and return: return (high - BIAS)|0; // asm type annotation } // EXPORTS // module.exports = exponent; },{"@stdlib/constants/float64/exponent-bias":238,"@stdlib/constants/float64/high-word-exponent-mask":239,"@stdlib/number/float64/base/get-high-word":300}],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'; /** * 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":298}],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'; // 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":116}],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 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":297,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],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'; // MODULES // var isLittleEndian = require( '@stdlib/assert/is-little-endian' ); // MAIN // var HIGH; if ( isLittleEndian === true ) { HIGH = 1; // second index } else { HIGH = 0; // first index } // EXPORTS // module.exports = HIGH; },{"@stdlib/assert/is-little-endian":116}],300:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number. * * @module @stdlib/number/float64/base/get-high-word * * @example * var getHighWord = require( '@stdlib/number/float64/base/get-high-word' ); * * var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011 * // returns 1774486211 */ // MODULES // var getHighWord = require( './main.js' ); // EXPORTS // module.exports = getHighWord; },{"./main.js":301}],301:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 HIGH = require( './high.js' ); // VARIABLES // var FLOAT64_VIEW = new Float64Array( 1 ); var UINT32_VIEW = new Uint32Array( FLOAT64_VIEW.buffer ); // MAIN // /** * Returns an unsigned 32-bit integer corresponding to the more significant 32 bits of a double-precision floating-point number. * * ## 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 * * @param {number} x - input value * @returns {uinteger32} higher order word * * @example * var w = getHighWord( 3.14e201 ); // => 01101001110001001000001011000011 * // returns 1774486211 */ function getHighWord( x ) { FLOAT64_VIEW[ 0 ] = x; return UINT32_VIEW[ HIGH ]; } // EXPORTS // module.exports = getHighWord; },{"./high.js":299,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],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'; /** * Return a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). * * @module @stdlib/number/float64/base/normalize * * @example * var normalize = require( '@stdlib/number/float64/base/normalize' ); * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = normalize( 3.14e-319 ); * // returns [ 1.4141234400356668e-303, -52 ] * * var y = out[ 0 ]; * var exp = out[ 1 ]; * * var bool = ( y*pow(2.0,exp) === 3.14e-319 ); * // returns true * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var normalize = require( '@stdlib/number/float64/base/normalize' ); * * var out = new Float64Array( 2 ); * * var v = normalize( out, 3.14e-319 ); * // returns <Float64Array>[ 1.4141234400356668e-303, -52 ] * * var bool = ( v === out ); * // returns true */ // MODULES // var normalize = require( './main.js' ); // EXPORTS // module.exports = normalize; },{"./main.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. */ 'use strict'; // MODULES // var fcn = require( './normalize.js' ); // MAIN // /** * Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). * * @param {(Array|TypedArray|Object)} [out] - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = normalize( [ 0.0, 0 ], 3.14e-319 ); * // returns [ 1.4141234400356668e-303, -52 ] * * var y = out[ 0 ]; * var exp = out[ 1 ]; * * var bool = ( y*pow(2.0,exp) === 3.14e-319 ); * // returns true * * @example * var Float64Array = require( '@stdlib/array/float64' ); * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = new Float64Array( 2 ); * * var v = normalize( out, 3.14e-319 ); * // returns <Float64Array>[ 1.4141234400356668e-303, -52 ] * * var bool = ( v === out ); * // returns true * * @example * var out = normalize( [ 0.0, 0 ], 0.0 ); * // returns [ 0.0, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], Infinity ); * // returns [ Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], -Infinity ); * // returns [ -Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], NaN ); * // returns [ NaN, 0 ] */ function normalize( out, x ) { if ( arguments.length === 1 ) { return fcn( [ 0.0, 0 ], out ); } return fcn( out, x ); } // EXPORTS // module.exports = normalize; },{"./normalize.js":304}],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'; // MODULES // var FLOAT64_SMALLEST_NORMAL = require( '@stdlib/constants/float64/smallest-normal' ); var isInfinite = require( '@stdlib/math/base/assert/is-infinite' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var abs = require( '@stdlib/math/base/special/abs' ); // VARIABLES // // (1<<52) var SCALAR = 4503599627370496; // MAIN // /** * Returns a normal number `y` and exponent `exp` satisfying \\(x = y \cdot 2^\mathrm{exp}\\). * * @private * @param {(Array|TypedArray|Object)} out - output array * @param {number} x - input value * @returns {(Array|TypedArray|Object)} output array * * @example * var pow = require( '@stdlib/math/base/special/pow' ); * * var out = normalize( [ 0.0, 0 ], 3.14e-319 ); * // returns [ 1.4141234400356668e-303, -52 ] * * var y = out[ 0 ]; * var exp = out[ 1 ]; * * var bool = ( y*pow(2.0,exp) === 3.14e-319 ); * // returns true * * @example * var out = normalize( [ 0.0, 0 ], 0.0 ); * // returns [ 0.0, 0 ]; * * @example * var out = normalize( [ 0.0, 0 ], Infinity ); * // returns [ Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], -Infinity ); * // returns [ -Infinity, 0 ] * * @example * var out = normalize( [ 0.0, 0 ], NaN ); * // returns [ NaN, 0 ] */ function normalize( out, x ) { if ( isnan( x ) || isInfinite( x ) ) { out[ 0 ] = x; out[ 1 ] = 0; return out; } if ( x !== 0.0 && abs( x ) < FLOAT64_SMALLEST_NORMAL ) { out[ 0 ] = x * SCALAR; out[ 1 ] = -52; return out; } out[ 0 ] = x; out[ 1 ] = 0; return out; } // EXPORTS // module.exports = normalize; },{"@stdlib/constants/float64/smallest-normal":247,"@stdlib/math/base/assert/is-infinite":259,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/abs":267}],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'; /** * 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":307}],306:[function(require,module,exports){ arguments[4][297][0].apply(exports,arguments) },{"@stdlib/assert/is-little-endian":116,"dup":297}],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 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":308}],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'; // 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":306,"@stdlib/array/float64":5,"@stdlib/array/uint32":23}],309:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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' ); // VARIABLES // var NUM_WARMUPS = 8; // MAIN // /** * Initializes a shuffle table. * * @private * @param {PRNG} rand - pseudorandom number generator * @param {Int32Array} table - table * @param {PositiveInteger} N - table size * @throws {Error} PRNG returned `NaN` * @returns {NumberArray} shuffle table */ function createTable( rand, table, N ) { var v; var i; // "warm-up" the PRNG... for ( i = 0; i < NUM_WARMUPS; i++ ) { v = rand(); // Prevent the above loop from being discarded by the compiler... if ( isnan( v ) ) { throw new Error( 'unexpected error. PRNG returned `NaN`.' ); } } // Initialize the shuffle table... for ( i = N-1; i >= 0; i-- ) { table[ i ] = rand(); } return table; } // EXPORTS // module.exports = createTable; },{"@stdlib/math/base/assert/is-nan":263}],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. */ /* eslint-disable max-len */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isInt32Array = require( '@stdlib/assert/is-int32array' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var floor = require( '@stdlib/math/base/special/floor' ); var Int32Array = require( '@stdlib/array/int32' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var typedarray2json = require( '@stdlib/array/to-json' ); var createTable = require( './create_table.js' ); var randint32 = require( './rand_int32.js' ); // VARIABLES // var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation var A = 16807|0; // asm type annotation // Define the number of elements in the shuffle table: var TABLE_LENGTH = 32; // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 3; // table, other, seed // Define the index offset of the "table" section in the state array: var TABLE_SECTION_OFFSET = 2; // | version | num_sections | table_length | ...table | other_length | shuffle_state | prng_state | seed_length | ...seed | // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = TABLE_LENGTH + 3; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = TABLE_LENGTH + 6; // | version | num_sections | table_length | ...table | state_length | shuffle_state | prng_state | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = TABLE_LENGTH + 7; // 1 (version) + 1 (num_sections) + 1 (table_length) + TABLE_LENGTH (table) + 1 (state_length) + 1 (shuffle_state) + 1 (prng_state) + 1 (seed_length) // Define the indices for the shuffle table and PRNG states: var SHUFFLE_STATE = STATE_SECTION_OFFSET + 1; var PRNG_STATE = STATE_SECTION_OFFSET + 2; // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Int32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "table" section must equal `TABLE_LENGTH`... if ( state[ TABLE_SECTION_OFFSET ] !== TABLE_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible table length. Expected: '+TABLE_LENGTH+'. Actual: '+state[ TABLE_SECTION_OFFSET ]+'.' ); } // The length of the "state" section must equal `2`... if ( state[ STATE_SECTION_OFFSET ] !== 2 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(2).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } // MAIN // /** * Returns a linear congruential pseudorandom number generator (LCG) whose output is shuffled. * * @param {Options} [options] - options * @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer * @throws {TypeError} state must be an `Int32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} shuffled LCG PRNG * * @example * var minstd = factory(); * * var v = minstd(); * // returns <number> * * @example * // Return a seeded LCG: * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 1421600654 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isInt32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Int32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } seed |= 0; // asm type annotation } else if ( isCollection( seed ) && seed.length > 0 ) { slen = seed.length; STATE = new Int32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH; STATE[ STATE_SECTION_OFFSET ] = 2; STATE[ PRNG_STATE ] = seed[ 0 ]; STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state = createTable( minstd, state, TABLE_LENGTH ); STATE[ SHUFFLE_STATE ] = state[ 0 ]; } else { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } } else { seed = randint32()|0; // asm type annotation } } } else { seed = randint32()|0; // asm type annotation } if ( state === void 0 ) { STATE = new Int32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ TABLE_SECTION_OFFSET ] = TABLE_LENGTH; STATE[ STATE_SECTION_OFFSET ] = 2; STATE[ PRNG_STATE ] = seed; STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state = createTable( minstd, state, TABLE_LENGTH ); STATE[ SHUFFLE_STATE ] = state[ 0 ]; } setReadOnly( minstdShuffle, 'NAME', 'minstd-shuffle' ); setReadOnlyAccessor( minstdShuffle, 'seed', getSeed ); setReadOnlyAccessor( minstdShuffle, 'seedLength', getSeedLength ); setReadWriteAccessor( minstdShuffle, 'state', getState, setState ); setReadOnlyAccessor( minstdShuffle, 'stateLength', getStateLength ); setReadOnlyAccessor( minstdShuffle, 'byteLength', getStateSize ); setReadOnly( minstdShuffle, 'toJSON', toJSON ); setReadOnly( minstdShuffle, 'MIN', 1 ); setReadOnly( minstdShuffle, 'MAX', INT32_MAX-1 ); setReadOnly( minstdShuffle, 'normalized', normalized ); setReadOnly( normalized, 'NAME', minstdShuffle.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', (minstdShuffle.MIN-1.0) / NORMALIZATION_CONSTANT ); setReadOnly( normalized, 'MAX', (minstdShuffle.MAX-1.0) / NORMALIZATION_CONSTANT ); return minstdShuffle; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMINSTD} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Int32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `3` sections: * * 0. preamble (version + number of sections) * 1. shuffle table * 2. internal PRNG state * 3. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMINSTD} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Int32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMINSTD} s - generator state * @throws {TypeError} must provide an `Int32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isInt32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Int32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state (table) "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((TABLE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), TABLE_LENGTH ); // Create a new seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = minstdShuffle.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer */ function minstd() { var s = STATE[ PRNG_STATE ]|0; // asm type annotation s = ( (A*s)%INT32_MAX )|0; // asm type annotation STATE[ PRNG_STATE ] = s; return s|0; // asm type annotation } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ function minstdShuffle() { var s; var i; s = STATE[ SHUFFLE_STATE ]; i = floor( TABLE_LENGTH * (s/INT32_MAX) ); // Pull a state from the table: s = state[ i ]; // Update the PRNG state: STATE[ SHUFFLE_STATE ] = s; // Replace the pulled state: state[ i ] = minstd(); return s; } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number * * @example * var v = normalized(); * // returns <number> */ function normalized() { return (minstdShuffle()-1) / NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./create_table.js":309,"./rand_int32.js":313,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],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'; /** * A linear congruential pseudorandom number generator (LCG) whose output is shuffled. * * @module @stdlib/random/base/minstd-shuffle * * @example * var minstd = require( '@stdlib/random/base/minstd-shuffle' ); * * var v = minstd(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/minstd-shuffle' ).factory; * * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 1421600654 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var minstd = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( minstd, 'factory', factory ); // EXPORTS // module.exports = minstd; },{"./factory.js":310,"./main.js":312,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // MODULES // var factory = require( './factory.js' ); var randint32 = require( './rand_int32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * ## Method * * Linear congruential generators (LCGs) use the recurrence relation * * ```tex * X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m) * ``` * * where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\). * * <!-- <note> --> * * For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\). * * <!-- </note> --> * * In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values * * ```tex * \begin{align*} * a &= 7^5 = 16807 \\ * c &= 0 \\ * m &= 2^{31} - 1 = 2147483647 * \end{align*} * ``` * * <!-- <note> --> * * The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)). * * <!-- </note> --> * * <!-- <note> --> * * The constant \\( a \\) is a primitive root (modulo \\(31\\)). * * <!-- </note> --> * * Accordingly, the maximum possible product is * * ```tex * 16807 \cdot (m - 1) \approx 2^{46} * ``` * * The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_. * * This implementation subsequently shuffles the output of a linear congruential pseudorandom number generator (LCG) using a shuffle table in accordance with the Bays-Durham algorithm. * * * ## Notes * * - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279). * * * ## References * * - Bays, Carter, and S. D. Durham. 1976. "Improving a Poor Random Number Generator." _ACM Transactions on Mathematical Software_ 2 (1). New York, NY, USA: ACM: 59–64. doi:[10.1145/355666.355670](http://dx.doi.org/10.1145/355666.355670). * - Herzog, T.N., and G. Lord. 2002. _Applications of Monte Carlo Methods to Finance and Insurance_. ACTEX Publications. [https://books.google.com/books?id=vC7I\\\_gdX-A0C](https://books.google.com/books?id=vC7I\_gdX-A0C). * - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press. * * * @function minstd * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ var minstd = factory({ 'seed': randint32() }); // EXPORTS // module.exports = minstd; },{"./factory.js":310,"./rand_int32.js":313}],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'; // MODULES // var INT32_MAX = require( '@stdlib/constants/int32/max' ); var floor = require( '@stdlib/math/base/special/floor' ); // VARIABLES // var MAX = INT32_MAX - 1; // MAIN // /** * Returns a pseudorandom integer on the interval \\([1, 2^{31}-1)\\). * * @private * @returns {PositiveInteger} pseudorandom integer * * @example * var v = randint32(); * // returns <number> */ function randint32() { var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math return v|0; // asm type annotation } // EXPORTS // module.exports = randint32; },{"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277}],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. */ /* eslint-disable max-len */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isCollection = require( '@stdlib/assert/is-collection' ); var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var isInt32Array = require( '@stdlib/assert/is-int32array' ); var INT32_MAX = require( '@stdlib/constants/int32/max' ); var Int32Array = require( '@stdlib/array/int32' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var typedarray2json = require( '@stdlib/array/to-json' ); var randint32 = require( './rand_int32.js' ); // VARIABLES // var NORMALIZATION_CONSTANT = (INT32_MAX - 1)|0; // asm type annotation var MAX_SEED = (INT32_MAX - 1)|0; // asm type annotation var A = 16807|0; // asm type annotation // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 2; // state, seed // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = 4; // | version | num_sections | state_length | ...state | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = 5; // 1 (version) + 1 (num_sections) + 1 (state_length) + 1 (state) + 1 (seed_length) // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Int32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "state" section must equal `1`... if ( state[ STATE_SECTION_OFFSET ] !== 1 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+(1).toString()+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } // MAIN // /** * Returns a linear congruential pseudorandom number generator (LCG) based on Park and Miller. * * @param {Options} [options] - options * @param {PRNGSeedMINSTD} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMINSTD} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integers less than the maximum signed 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than the maximum signed 32-bit integer * @throws {TypeError} state must be an `Int32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} LCG PRNG * * @example * var minstd = factory(); * * var v = minstd(); * // returns <number> * * @example * // Return a seeded LCG: * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 20739838 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isInt32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be an Int32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Int32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } seed |= 0; // asm type annotation } else if ( isCollection( seed ) && seed.length > 0 ) { slen = seed.length; STATE = new Int32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state[ 0 ] = seed[ 0 ]; } else { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than the maximum signed 32-bit integer or an array-like object containing integer values less than the maximum signed 32-bit integer. Option: `' + seed + '`.' ); } } else { seed = randint32()|0; // asm type annotation } } } else { seed = randint32()|0; // asm type annotation } if ( state === void 0 ) { STATE = new Int32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state[ 0 ] = seed[ 0 ]; } setReadOnly( minstd, 'NAME', 'minstd' ); setReadOnlyAccessor( minstd, 'seed', getSeed ); setReadOnlyAccessor( minstd, 'seedLength', getSeedLength ); setReadWriteAccessor( minstd, 'state', getState, setState ); setReadOnlyAccessor( minstd, 'stateLength', getStateLength ); setReadOnlyAccessor( minstd, 'byteLength', getStateSize ); setReadOnly( minstd, 'toJSON', toJSON ); setReadOnly( minstd, 'MIN', 1 ); setReadOnly( minstd, 'MAX', INT32_MAX-1 ); setReadOnly( minstd, 'normalized', normalized ); setReadOnly( normalized, 'NAME', minstd.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', (minstd.MIN-1.0) / NORMALIZATION_CONSTANT ); setReadOnly( normalized, 'MAX', (minstd.MAX-1.0) / NORMALIZATION_CONSTANT ); return minstd; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMINSTD} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Int32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `2` sections: * * 0. preamble (version + number of sections) * 1. internal PRNG state * 2. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `2`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMINSTD} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Int32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMINSTD} s - generator state * @throws {TypeError} must provide an `Int32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isInt32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide an Int32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Int32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state "view": state = new Int32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Create a new seed "view": seed = new Int32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = minstd.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * @private * @returns {integer32} pseudorandom integer */ function minstd() { var s = state[ 0 ]|0; // asm type annotation s = ( (A*s)%INT32_MAX )|0; // asm type annotation state[ 0 ] = s; return s|0; // asm type annotation } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number */ function normalized() { return (minstd()-1) / NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./rand_int32.js":317,"@stdlib/array/int32":10,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-int32array":106,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/int32/max":250,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],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'; /** * A linear congruential pseudorandom number generator (LCG) based on Park and Miller. * * @module @stdlib/random/base/minstd * * @example * var minstd = require( '@stdlib/random/base/minstd' ); * * var v = minstd(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/minstd' ).factory; * * var minstd = factory({ * 'seed': 1234 * }); * * var v = minstd(); * // returns 20739838 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var minstd = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( minstd, 'factory', factory ); // EXPORTS // module.exports = minstd; },{"./factory.js":314,"./main.js":316,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // MODULES // var factory = require( './factory.js' ); var randint32 = require( './rand_int32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{31}-1) \\). * * ## Method * * Linear congruential generators (LCGs) use the recurrence relation * * ```tex * X_{n+1} = ( a \cdot X_n + c ) \operatorname{mod}(m) * ``` * * where the modulus \\( m \\) is a prime number or power of a prime number and \\( a \\) is a primitive root modulo \\( m \\). * * <!-- <note> --> * * For an LCG to be a Lehmer RNG, the seed \\( X_0 \\) must be coprime to \\( m \\). * * <!-- </note> --> * * In this implementation, the constants \\( a \\), \\( c \\), and \\( m \\) have the values * * ```tex * \begin{align*} * a &= 7^5 = 16807 \\ * c &= 0 \\ * m &= 2^{31} - 1 = 2147483647 * \end{align*} * ``` * * <!-- <note> --> * * The constant \\( m \\) is a Mersenne prime (modulo \\(31\\)). * * <!-- </note> --> * * <!-- <note> --> * * The constant \\( a \\) is a primitive root (modulo \\(31\\)). * * <!-- </note> --> * * Accordingly, the maximum possible product is * * ```tex * 16807 \cdot (m - 1) \approx 2^{46} * ``` * * The values for \\( a \\), \\( c \\), and \\( m \\) are taken from Park and Miller, "Random Number Generators: Good Ones Are Hard To Find". Park's and Miller's article is also the basis for a recipe in the second edition of _Numerical Recipes in C_. * * * ## Notes * * - The generator has a period of approximately \\(2.1\mbox{e}9\\) (see [Numerical Recipes in C, 2nd Edition](#references), p. 279). * * * ## References * * - Park, S. K., and K. W. Miller. 1988. "Random Number Generators: Good Ones Are Hard to Find." _Communications of the ACM_ 31 (10). New York, NY, USA: ACM: 1192–1201. doi:[10.1145/63039.63042](http://dx.doi.org/10.1145/63039.63042). * - Press, William H., Brian P. Flannery, Saul A. Teukolsky, and William T. Vetterling. 1992. _Numerical Recipes in C: The Art of Scientific Computing, Second Edition_. Cambridge University Press. * * * @function minstd * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = minstd(); * // returns <number> */ var minstd = factory({ 'seed': randint32() }); // EXPORTS // module.exports = minstd; },{"./factory.js":314,"./rand_int32.js":317}],317:[function(require,module,exports){ arguments[4][313][0].apply(exports,arguments) },{"@stdlib/constants/int32/max":250,"@stdlib/math/base/special/floor":277,"dup":313}],318:[function(require,module,exports){ /* eslint-disable max-lines, max-len */ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * ## Notice * * The original C code and copyright notice are from the [source implementation]{@link http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c}. The implementation has been modified for JavaScript. * * ```text * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ``` */ 'use strict'; // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isCollection = require( '@stdlib/assert/is-collection' ); var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; var FLOAT64_MAX_SAFE_INTEGER = require( '@stdlib/constants/float64/max-safe-integer' ); var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var Uint32Array = require( '@stdlib/array/uint32' ); var max = require( '@stdlib/math/base/special/max' ); var uimul = require( '@stdlib/math/base/special/uimul' ); var gcopy = require( '@stdlib/blas/base/gcopy' ); var typedarray2json = require( '@stdlib/array/to-json' ); var randuint32 = require( './rand_uint32.js' ); // VARIABLES // // Define the size of the state array (see refs): var N = 624; // Define a (magic) constant used for indexing into the state array: var M = 397; // Define the maximum seed: 11111111111111111111111111111111 var MAX_SEED = UINT32_MAX >>> 0; // asm type annotation // For seed arrays, define an initial state (magic) constant: 19650218 => 00000001001010111101011010101010 var SEED_ARRAY_INIT_STATE = 19650218 >>> 0; // asm type annotation // Define a mask for the most significant `w-r` bits, where `w` is the word size (32 bits) and `r` is the separation point of one word (see refs): 2147483648 => 0x80000000 => 10000000000000000000000000000000 var UPPER_MASK = 0x80000000 >>> 0; // asm type annotation // Define a mask for the least significant `r` bits (see refs): 2147483647 => 0x7fffffff => 01111111111111111111111111111111 var LOWER_MASK = 0x7fffffff >>> 0; // asm type annotation // Define a multiplier (see Knuth TAOCP Vol2. 3rd Ed. P.106): 1812433253 => 01101100000001111000100101100101 var KNUTH_MULTIPLIER = 1812433253 >>> 0; // asm type annotation // Define a (magic) multiplier: 1664525 => 00000000000110010110011000001101 var MAGIC_MULTIPLIER_1 = 1664525 >>> 0; // asm type annotation // Define a (magic) multiplier: 1566083941 => 01011101010110001000101101100101 var MAGIC_MULTIPLIER_2 = 1566083941 >>> 0; // asm type annotation // Define a tempering coefficient: 2636928640 => 0x9d2c5680 => 10011101001011000101011010000000 var TEMPERING_COEFFICIENT_1 = 0x9d2c5680 >>> 0; // asm type annotation // Define a tempering coefficient: 4022730752 => 0xefc60000 => 11101111110001100000000000000000 var TEMPERING_COEFFICIENT_2 = 0xefc60000 >>> 0; // asm type annotation // Define a constant vector `a` (see refs): 2567483615 => 0x9908b0df => 10011001000010001011000011011111 var MATRIX_A = 0x9908b0df >>> 0; // asm type annotation // MAG01[x] = x * MATRIX_A; for x = {0,1} var MAG01 = [ 0x0 >>> 0, MATRIX_A >>> 0 ]; // asm type annotation // Define a normalization constant when generating double-precision floating-point numbers: 2^53 => 9007199254740992 var FLOAT64_NORMALIZATION_CONSTANT = 1.0 / ( FLOAT64_MAX_SAFE_INTEGER+1.0 ); // eslint-disable-line id-length // 2^26: 67108864 var TWO_26 = 67108864 >>> 0; // asm type annotation // 2^32: 2147483648 => 0x80000000 => 10000000000000000000000000000000 var TWO_32 = 0x80000000 >>> 0; // asm type annotation // 1 (as a 32-bit unsigned integer): 1 => 0x1 => 00000000000000000000000000000001 var ONE = 0x1 >>> 0; // asm type annotation // Define the maximum normalized pseudorandom double-precision floating-point number: ( (((2^32-1)>>>5)*2^26)+( (2^32-1)>>>6) ) / 2^53 var MAX_NORMALIZED = FLOAT64_MAX_SAFE_INTEGER * FLOAT64_NORMALIZATION_CONSTANT; // Define the state array schema version: var STATE_ARRAY_VERSION = 1; // NOTE: anytime the state array schema changes, this value should be incremented!!! // Define the number of sections in the state array: var NUM_STATE_SECTIONS = 3; // state, other, seed // Define the index offset of the "state" section in the state array: var STATE_SECTION_OFFSET = 2; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the index offset of the "other" section in the state array: var OTHER_SECTION_OFFSET = N + 3; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the index offset of the seed section in the state array: var SEED_SECTION_OFFSET = N + 5; // | version | num_sections | state_length | ...state | other_length | state_index | seed_length | ...seed | // Define the length of the "fixed" length portion of the state array: var STATE_FIXED_LENGTH = N + 6; // 1 (version) + 1 (num_sections) + 1 (state_length) + N (state) + 1 (other_length) + 1 (state_index) + 1 (seed_length) // FUNCTIONS // /** * Verifies state array integrity. * * @private * @param {Uint32Array} state - state array * @param {boolean} FLG - flag indicating whether the state array was provided as an option (true) or an argument (false) * @returns {(Error|null)} an error or `null` */ function verifyState( state, FLG ) { var s1; if ( FLG ) { s1 = 'option'; } else { s1 = 'argument'; } // The state array must have a minimum length... if ( state.length < STATE_FIXED_LENGTH+1 ) { return new RangeError( 'invalid '+s1+'. `state` array has insufficient length.' ); } // The first element of the state array must equal the supported state array schema version... if ( state[ 0 ] !== STATE_ARRAY_VERSION ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible schema version. Expected: '+STATE_ARRAY_VERSION+'. Actual: '+state[ 0 ]+'.' ); } // The second element of the state array must contain the number of sections... if ( state[ 1 ] !== NUM_STATE_SECTIONS ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible number of sections. Expected: '+NUM_STATE_SECTIONS+'. Actual: '+state[ 1 ]+'.' ); } // The length of the "state" section must equal `N`... if ( state[ STATE_SECTION_OFFSET ] !== N ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible state length. Expected: '+N+'. Actual: '+state[ STATE_SECTION_OFFSET ]+'.' ); } // The length of the "other" section must equal `1`... if ( state[ OTHER_SECTION_OFFSET ] !== 1 ) { return new RangeError( 'invalid '+s1+'. `state` array has an incompatible section length. Expected: '+(1).toString()+'. Actual: '+state[ OTHER_SECTION_OFFSET ]+'.' ); } // The length of the "seed" section much match the empirical length... if ( state[ SEED_SECTION_OFFSET ] !== state.length-STATE_FIXED_LENGTH ) { return new RangeError( 'invalid '+s1+'. `state` array length is incompatible with seed section length. Expected: '+(state.length-STATE_FIXED_LENGTH)+'. Actual: '+state[ SEED_SECTION_OFFSET ]+'.' ); } return null; } /** * Returns an initial PRNG state. * * @private * @param {Uint32Array} state - state array * @param {PositiveInteger} N - state size * @param {uinteger32} s - seed * @returns {Uint32Array} state array */ function createState( state, N, s ) { var i; // Set the first element of the state array to the provided seed: state[ 0 ] = s >>> 0; // equivalent to `s & 0xffffffffUL` in original C implementation // Initialize the remaining state array elements: for ( i = 1; i < N; i++ ) { /* * In the original C implementation (see `init_genrand()`), * * ```c * mt[i] = (KNUTH_MULTIPLIER * (mt[i-1] ^ (mt[i-1] >> 30)) + i) * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation state[ i ] = ( uimul( s, KNUTH_MULTIPLIER ) + i )>>>0; // asm type annotation } return state; } /** * Initializes a PRNG state array according to a seed array. * * @private * @param {Uint32Array} state - state array * @param {NonNegativeInteger} N - state array length * @param {Collection} seed - seed array * @param {NonNegativeInteger} M - seed array length * @returns {Uint32Array} state array */ function initState( state, N, seed, M ) { var s; var i; var j; var k; i = 1; j = 0; for ( k = max( N, M ); k > 0; k-- ) { /* * In the original C implementation (see `init_by_array()`), * * ```c * mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1664525UL)) + seed[j] + j; * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation s = ( uimul( s, MAGIC_MULTIPLIER_1 ) )>>>0; // asm type annotation state[ i ] = ( ((state[i]>>>0)^s) + seed[j] + j )>>>0; /* non-linear */ // asm type annotation i += 1; j += 1; if ( i >= N ) { state[ 0 ] = state[ N-1 ]; i = 1; } if ( j >= M ) { j = 0; } } for ( k = N-1; k > 0; k-- ) { /* * In the original C implementation (see `init_by_array()`), * * ```c * mt[i] = (mt[i]^((mt[i-1]^(mt[i-1]>>30))*1566083941UL)) - i; * ``` * * In order to replicate this in JavaScript, we must emulate C-like multiplication of unsigned 32-bit integers. */ s = state[ i-1 ]>>>0; // asm type annotation s = ( s^(s>>>30) )>>>0; // asm type annotation s = ( uimul( s, MAGIC_MULTIPLIER_2 ) )>>>0; // asm type annotation state[ i ] = ( ((state[i]>>>0)^s) - i )>>>0; /* non-linear */ // asm type annotation i += 1; if ( i >= N ) { state[ 0 ] = state[ N-1 ]; i = 1; } } // Ensure a non-zero initial state array: state[ 0 ] = TWO_32; // MSB (most significant bit) is 1 return state; } /** * Updates a PRNG's internal state by generating the next `N` words. * * @private * @param {Uint32Array} state - state array * @returns {Uint32Array} state array */ function twist( state ) { var w; var i; var j; var k; k = N - M; for ( i = 0; i < k; i++ ) { w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK ); state[ i ] = state[ i+M ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; } j = N - 1; for ( ; i < j; i++ ) { w = ( state[i]&UPPER_MASK ) | ( state[i+1]&LOWER_MASK ); state[ i ] = state[ i-k ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; } w = ( state[j]&UPPER_MASK ) | ( state[0]&LOWER_MASK ); state[ j ] = state[ M-1 ] ^ ( w>>>1 ) ^ MAG01[ w&ONE ]; return state; } // MAIN // /** * Returns a 32-bit Mersenne Twister pseudorandom number generator. * * ## Notes * * - In contrast to the original C implementation, array seeds of length `1` are considered integer seeds. This ensures that the seed `[ 1234 ]` generates the same output as the seed `1234`. In the original C implementation, the two seeds would yield different output, which is **not** obvious from a user perspective. * * @param {Options} [options] - options * @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed * @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} options argument must be an object * @throws {TypeError} a seed must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integers less than or equal to the maximum unsigned 32-bit integer * @throws {RangeError} a numeric seed must be a positive integer less than or equal to the maximum unsigned 32-bit integer * @throws {TypeError} state must be a `Uint32Array` * @throws {Error} must provide a valid state * @throws {TypeError} `copy` option must be a boolean * @returns {PRNG} Mersenne Twister PRNG * * @example * var mt19937 = factory(); * * var v = mt19937(); * // returns <number> * * @example * // Return a seeded Mersenne Twister PRNG: * var mt19937 = factory({ * 'seed': 1234 * }); * * var v = mt19937(); * // returns 822569775 */ function factory( options ) { var STATE; var state; var opts; var seed; var slen; var err; opts = {}; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Options argument must be an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( options.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + options.copy + '`.' ); } } if ( hasOwnProp( options, 'state' ) ) { state = options.state; opts.state = true; if ( !isUint32Array( state ) ) { throw new TypeError( 'invalid option. `state` option must be a Uint32Array. Option: `' + state + '`.' ); } err = verifyState( state, true ); if ( err ) { throw err; } if ( opts.copy === false ) { STATE = state; } else { STATE = new Uint32Array( state.length ); gcopy( state.length, state, 1, STATE, 1 ); } // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), state[ SEED_SECTION_OFFSET ] ); } // If provided a PRNG state, we ignore the `seed` option... if ( seed === void 0 ) { if ( hasOwnProp( options, 'seed' ) ) { seed = options.seed; opts.seed = true; if ( isPositiveInteger( seed ) ) { if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be a positive integer less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } seed >>>= 0; // asm type annotation } else if ( isCollection( seed ) === false || seed.length < 1 ) { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } else if ( seed.length === 1 ) { seed = seed[ 0 ]; if ( !isPositiveInteger( seed ) ) { throw new TypeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } if ( seed > MAX_SEED ) { throw new RangeError( 'invalid option. `seed` option must be either a positive integer less than or equal to the maximum unsigned 32-bit integer or an array-like object containing integer values less than or equal to the maximum unsigned 32-bit integer. Option: `' + seed + '`.' ); } seed >>>= 0; // asm type annotation } else { slen = seed.length; STATE = new Uint32Array( STATE_FIXED_LENGTH+slen ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = N; STATE[ OTHER_SECTION_OFFSET ] = 1; STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index STATE[ SEED_SECTION_OFFSET ] = slen; // Copy the provided seed array to prevent external mutation, as mutation would lead to an inability to reproduce PRNG values according to the PRNG's stated seed: gcopy.ndarray( slen, seed, 1, 0, STATE, 1, SEED_SECTION_OFFSET+1 ); // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), slen ); // Initialize the internal PRNG state: state = createState( state, N, SEED_ARRAY_INIT_STATE ); state = initState( state, N, seed, slen ); } } else { seed = randuint32() >>> 0; // asm type annotation } } } else { seed = randuint32() >>> 0; // asm type annotation } if ( state === void 0 ) { STATE = new Uint32Array( STATE_FIXED_LENGTH+1 ); // Initialize sections: STATE[ 0 ] = STATE_ARRAY_VERSION; STATE[ 1 ] = NUM_STATE_SECTIONS; STATE[ STATE_SECTION_OFFSET ] = N; STATE[ OTHER_SECTION_OFFSET ] = 1; STATE[ OTHER_SECTION_OFFSET+1 ] = N; // state index STATE[ SEED_SECTION_OFFSET ] = 1; STATE[ SEED_SECTION_OFFSET+1 ] = seed; // Create a state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), 1 ); // Initialize the internal PRNG state: state = createState( state, N, seed ); } // Note: property order matters in order to maintain consistency of PRNG "shape" (hidden classes). setReadOnly( mt19937, 'NAME', 'mt19937' ); setReadOnlyAccessor( mt19937, 'seed', getSeed ); setReadOnlyAccessor( mt19937, 'seedLength', getSeedLength ); setReadWriteAccessor( mt19937, 'state', getState, setState ); setReadOnlyAccessor( mt19937, 'stateLength', getStateLength ); setReadOnlyAccessor( mt19937, 'byteLength', getStateSize ); setReadOnly( mt19937, 'toJSON', toJSON ); setReadOnly( mt19937, 'MIN', 1 ); setReadOnly( mt19937, 'MAX', UINT32_MAX ); setReadOnly( mt19937, 'normalized', normalized ); setReadOnly( normalized, 'NAME', mt19937.NAME ); setReadOnlyAccessor( normalized, 'seed', getSeed ); setReadOnlyAccessor( normalized, 'seedLength', getSeedLength ); setReadWriteAccessor( normalized, 'state', getState, setState ); setReadOnlyAccessor( normalized, 'stateLength', getStateLength ); setReadOnlyAccessor( normalized, 'byteLength', getStateSize ); setReadOnly( normalized, 'toJSON', toJSON ); setReadOnly( normalized, 'MIN', 0.0 ); setReadOnly( normalized, 'MAX', MAX_NORMALIZED ); return mt19937; /** * Returns the PRNG seed. * * @private * @returns {PRNGSeedMT19937} seed */ function getSeed() { var len = STATE[ SEED_SECTION_OFFSET ]; return gcopy( len, seed, 1, new Uint32Array( len ), 1 ); } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return STATE[ SEED_SECTION_OFFSET ]; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return STATE.length; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return STATE.byteLength; } /** * Returns the current PRNG state. * * ## Notes * * - The PRNG state array is comprised of a preamble followed by `3` sections: * * 0. preamble (version + number of sections) * 1. internal PRNG state * 2. auxiliary state information * 3. PRNG seed * * - The first element of the PRNG state array preamble is the state array schema version. * * - The second element of the PRNG state array preamble is the number of state array sections (i.e., `3`). * * - The first element of each section following the preamble specifies the section length. The remaining section elements comprise the section contents. * * @private * @returns {PRNGStateMT19937} current state */ function getState() { var len = STATE.length; return gcopy( len, STATE, 1, new Uint32Array( len ), 1 ); } /** * Sets the PRNG state. * * ## Notes * * - If PRNG state is "shared" (meaning a state array was provided during PRNG creation and **not** copied) and one sets the generator state to a state array having a different length, the PRNG does **not** update the existing shared state and, instead, points to the newly provided state array. In order to synchronize PRNG output according to the new shared state array, the state array for **each** relevant PRNG must be **explicitly** set. * - If PRNG state is "shared" and one sets the generator state to a state array of the same length, the PRNG state is updated (along with the state of all other PRNGs sharing the PRNG's state array). * * @private * @param {PRNGStateMT19937} s - generator state * @throws {TypeError} must provide a `Uint32Array` * @throws {Error} must provide a valid state */ function setState( s ) { var err; if ( !isUint32Array( s ) ) { throw new TypeError( 'invalid argument. Must provide a Uint32Array. Value: `' + s + '`.' ); } err = verifyState( s, false ); if ( err ) { throw err; } if ( opts.copy === false ) { if ( opts.state && s.length === STATE.length ) { gcopy( s.length, s, 1, STATE, 1 ); // update current shared state } else { STATE = s; // point to new shared state opts.state = true; // setting this flag allows updating a shared state even if a state array was not provided at PRNG creation } } else { // Check if we can reuse allocated memory... if ( s.length !== STATE.length ) { STATE = new Uint32Array( s.length ); // reallocate } gcopy( s.length, s, 1, STATE, 1 ); } // Create a new state "view": state = new Uint32Array( STATE.buffer, STATE.byteOffset+((STATE_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), N ); // Create a new seed "view": seed = new Uint32Array( STATE.buffer, STATE.byteOffset+((SEED_SECTION_OFFSET+1)*STATE.BYTES_PER_ELEMENT), STATE[ SEED_SECTION_OFFSET ] ); } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = mt19937.NAME; out.state = typedarray2json( STATE ); out.params = []; return out; } /** * Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\). * * @private * @returns {uinteger32} pseudorandom integer * * @example * var r = mt19937(); * // returns <number> */ function mt19937() { var r; var i; // Retrieve the current state index: i = STATE[ OTHER_SECTION_OFFSET+1 ]; // Determine whether we need to update the PRNG state: if ( i >= N ) { state = twist( state ); i = 0; } // Get the next word of "raw"/untempered state: r = state[ i ]; // Update the state index: STATE[ OTHER_SECTION_OFFSET+1 ] = i + 1; // Tempering transform to compensate for the reduced dimensionality of equidistribution: r ^= r >>> 11; r ^= ( r << 7 ) & TEMPERING_COEFFICIENT_1; r ^= ( r << 15 ) & TEMPERING_COEFFICIENT_2; r ^= r >>> 18; return r >>> 0; } /** * Generates a pseudorandom number on the interval \\( [0,1) \\). * * ## Notes * * - The original C implementation credits Isaku Wada for this algorithm (2002/01/09). * * @private * @returns {number} pseudorandom number * * @example * var r = normalized(); * // returns <number> */ function normalized() { var x = mt19937() >>> 5; var y = mt19937() >>> 6; return ( (x*TWO_26)+y ) * FLOAT64_NORMALIZATION_CONSTANT; } } // EXPORTS // module.exports = factory; },{"./rand_uint32.js":321,"@stdlib/array/to-json":17,"@stdlib/array/uint32":23,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-collection":90,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-positive-integer":149,"@stdlib/assert/is-uint32array":170,"@stdlib/blas/base/gcopy":225,"@stdlib/constants/float64/max-safe-integer":243,"@stdlib/constants/uint32/max":255,"@stdlib/math/base/special/max":281,"@stdlib/math/base/special/uimul":290,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],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'; /** * A 32-bit Mersenne Twister pseudorandom number generator. * * @module @stdlib/random/base/mt19937 * * @example * var mt19937 = require( '@stdlib/random/base/mt19937' ); * * var v = mt19937(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/mt19937' ).factory; * * var mt19937 = factory({ * 'seed': 1234 * }); * * var v = mt19937(); * // returns 822569775 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var mt19937 = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( mt19937, 'factory', factory ); // EXPORTS // module.exports = mt19937; },{"./factory.js":318,"./main.js":320,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // MODULES // var factory = require( './factory.js' ); var randuint32 = require( './rand_uint32.js' ); // MAIN // /** * Generates a pseudorandom integer on the interval \\( [1,2^{32}-1) \\). * * ## Method * * - When generating normalized double-precision floating-point numbers, we first generate two pseudorandom integers \\( x \\) and \\( y \\) on the interval \\( [1,2^{32}-1) \\) for a combined \\( 64 \\) random bits. * * - We would like \\( 53 \\) random bits to generate a 53-bit precision integer and, thus, want to discard \\( 11 \\) of the generated bits. * * - We do so by discarding \\( 5 \\) bits from \\( x \\) and \\( 6 \\) bits from \\( y \\). * * - Accordingly, \\( x \\) contains \\( 27 \\) random bits, which are subsequently shifted left \\( 26 \\) bits (multiplied by \\( 2^{26} \\), and \\( y \\) contains \\( 26 \\) random bits to fill in the lower \\( 26 \\) bits. When summed, they combine to comprise \\( 53 \\) random bits of a double-precision floating-point integer. * * - As an example, suppose, for the sake of argument, the 32-bit PRNG generates the maximum unsigned 32-bit integer \\( 2^{32}-1 \\) twice in a row. Then, * * ```javascript * x = 4294967295 >>> 5; // 00000111111111111111111111111111 * y = 4294967295 >>> 6; // 00000011111111111111111111111111 * ``` * * Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 9007199187632128 \\), which, in binary, is * * ```binarystring * 0 10000110011 11111111111111111111 11111100000000000000000000000000 * ``` * * Adding \\( y \\) yields \\( 9007199254740991 \\) (the maximum "safe" double-precision floating-point integer value), which, in binary, is * * ```binarystring * 0 10000110011 11111111111111111111 11111111111111111111111111111111 * ``` * * - Similarly, suppose the 32-bit PRNG generates the following values * * ```javascript * x = 1 >>> 5; // 0 => 00000000000000000000000000000000 * y = 64 >>> 6; // 1 => 00000000000000000000000000000001 * ``` * * Multiplying \\( x \\) by \\( 2^{26} \\) returns \\( 0 \\), which, in binary, is * * ```binarystring * 0 00000000000 00000000000000000000 00000000000000000000000000000000 * ``` * * Adding \\( y \\) yields \\( 1 \\), which, in binary, is * * ```binarystring * 0 01111111111 00000000000000000000 00000000000000000000000000000000 * ``` * * - As different combinations of \\( x \\) and \\( y \\) are generated, different combinations of double-precision floating-point exponent and significand bits will be toggled, thus generating pseudorandom double-precision floating-point numbers. * * * ## References * * - Matsumoto, Makoto, and Takuji Nishimura. 1998. "Mersenne Twister: A 623-dimensionally Equidistributed Uniform Pseudo-random Number Generator." _ACM Transactions on Modeling and Computer Simulation_ 8 (1). New York, NY, USA: ACM: 3–30. doi:[10.1145/272991.272995][@matsumoto:1998a]. * - Harase, Shin. 2017. "Conversion of Mersenne Twister to double-precision floating-point numbers." _ArXiv_ abs/1708.06018 (September). <https://arxiv.org/abs/1708.06018>. * * [@matsumoto:1998a]: https://doi.org/10.1145/272991.272995 * * * @function mt19937 * @type {PRNG} * @returns {PositiveInteger} pseudorandom integer * * @example * var v = mt19937(); * // returns <number> */ var mt19937 = factory({ 'seed': randuint32() }); // EXPORTS // module.exports = mt19937; },{"./factory.js":318,"./rand_uint32.js":321}],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'; // MODULES // var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var floor = require( '@stdlib/math/base/special/floor' ); // VARIABLES // var MAX = UINT32_MAX - 1; // MAIN // /** * Returns a pseudorandom integer on the interval \\([1, 2^{32}-1)\\). * * @private * @returns {PositiveInteger} pseudorandom integer * * @example * var v = randuint32(); * // returns <number> */ function randuint32() { var v = floor( 1.0 + (MAX*Math.random()) ); // eslint-disable-line stdlib/no-builtin-math return v >>> 0; // asm type annotation } // EXPORTS // module.exports = randuint32; },{"@stdlib/constants/uint32/max":255,"@stdlib/math/base/special/floor":277}],322:[function(require,module,exports){ module.exports={ "name": "mt19937", "copy": true } },{}],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 setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' ); var setReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); var isObject = require( '@stdlib/assert/is-plain-object' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var hasOwnProp = require( '@stdlib/assert/has-own-property' ); var typedarray2json = require( '@stdlib/array/to-json' ); var defaults = require( './defaults.json' ); var PRNGS = require( './prngs.js' ); // MAIN // /** * Returns a pseudorandom number generator for generating uniformly distributed random numbers on the interval \\( [0,1) \\). * * @param {Options} [options] - function options * @param {string} [options.name='mt19937'] - name of pseudorandom number generator * @param {*} [options.seed] - pseudorandom number generator seed * @param {*} [options.state] - pseudorandom number generator state * @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state * @throws {TypeError} must provide an object * @throws {TypeError} must provide valid options * @throws {Error} must provide the name of a supported pseudorandom number generator * @returns {PRNG} pseudorandom number generator * * @example * var uniform = factory(); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'name': 'minstd' * }); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'seed': 12345 * }); * var v = uniform(); * // returns <number> * * @example * var uniform = factory({ * 'name': 'minstd', * 'seed': 12345 * }); * var v = uniform(); * // returns <number> */ function factory( options ) { var opts; var rand; var prng; opts = { 'name': defaults.name, 'copy': defaults.copy }; if ( arguments.length ) { if ( !isObject( options ) ) { throw new TypeError( 'invalid argument. Must provide an object. Value: `' + options + '`.' ); } if ( hasOwnProp( options, 'name' ) ) { opts.name = options.name; } if ( hasOwnProp( options, 'state' ) ) { opts.state = options.state; if ( opts.state === void 0 ) { throw new TypeError( 'invalid option. `state` option cannot be undefined. Option: `' + opts.state + '`.' ); } } else if ( hasOwnProp( options, 'seed' ) ) { opts.seed = options.seed; if ( opts.seed === void 0 ) { throw new TypeError( 'invalid option. `seed` option cannot be undefined. Option: `' + opts.seed + '`.' ); } } if ( hasOwnProp( options, 'copy' ) ) { opts.copy = options.copy; if ( !isBoolean( opts.copy ) ) { throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' ); } } } prng = PRNGS[ opts.name ]; if ( prng === void 0 ) { throw new Error( 'invalid option. Unrecognized/unsupported PRNG. Option: `' + opts.name + '`.' ); } if ( opts.state === void 0 ) { if ( opts.seed === void 0 ) { rand = prng.factory(); } else { rand = prng.factory({ 'seed': opts.seed }); } } else { rand = prng.factory({ 'state': opts.state, 'copy': opts.copy }); } setReadOnly( uniform, 'NAME', 'randu' ); setReadOnlyAccessor( uniform, 'seed', getSeed ); setReadOnlyAccessor( uniform, 'seedLength', getSeedLength ); setReadWriteAccessor( uniform, 'state', getState, setState ); setReadOnlyAccessor( uniform, 'stateLength', getStateLength ); setReadOnlyAccessor( uniform, 'byteLength', getStateSize ); setReadOnly( uniform, 'toJSON', toJSON ); setReadOnly( uniform, 'PRNG', rand ); setReadOnly( uniform, 'MIN', rand.normalized.MIN ); setReadOnly( uniform, 'MAX', rand.normalized.MAX ); return uniform; /** * Returns the PRNG seed. * * @private * @returns {*} seed */ function getSeed() { return rand.seed; } /** * Returns the PRNG seed length. * * @private * @returns {PositiveInteger} seed length */ function getSeedLength() { return rand.seedLength; } /** * Returns the PRNG state length. * * @private * @returns {PositiveInteger} state length */ function getStateLength() { return rand.stateLength; } /** * Returns the PRNG state size (in bytes). * * @private * @returns {PositiveInteger} state size (in bytes) */ function getStateSize() { return rand.byteLength; } /** * Returns the current pseudorandom number generator state. * * @private * @returns {*} current state */ function getState() { return rand.state; } /** * Sets the pseudorandom number generator state. * * @private * @param {*} s - generator state * @throws {Error} must provide a valid state */ function setState( s ) { rand.state = s; } /** * Serializes the pseudorandom number generator as a JSON object. * * ## Notes * * - `JSON.stringify()` implicitly calls this method when stringifying a PRNG. * * @private * @returns {Object} JSON representation */ function toJSON() { var out = {}; out.type = 'PRNG'; out.name = uniform.NAME + '-' + rand.NAME; out.state = typedarray2json( rand.state ); out.params = []; return out; } /** * Returns a uniformly distributed pseudorandom number on the interval \\( [0,1) \\). * * @private * @returns {number} pseudorandom number * * @example * var v = uniform(); * // returns <number> */ function uniform() { return rand.normalized(); } } // EXPORTS // module.exports = factory; },{"./defaults.json":322,"./prngs.js":326,"@stdlib/array/to-json":17,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/define-nonenumerable-read-only-accessor":372,"@stdlib/utils/define-nonenumerable-read-only-property":374,"@stdlib/utils/define-nonenumerable-read-write-accessor":376}],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'; /** * Uniformly distributed pseudorandom numbers on the interval \\( [0,1) \\). * * @module @stdlib/random/base/randu * * @example * var randu = require( '@stdlib/random/base/randu' ); * * var v = randu(); * // returns <number> * * @example * var factory = require( '@stdlib/random/base/randu' ).factory; * * var randu = factory({ * 'name': 'minstd', * 'seed': 12345 * }); * * var v = randu(); * // returns <number> */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var randu = require( './main.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( randu, 'factory', factory ); // EXPORTS // module.exports = randu; },{"./factory.js":323,"./main.js":325,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // MODULES // var factory = require( './factory.js' ); // MAIN // /** * Returns a uniformly distributed random number on the interval \\( [0,1) \\). * * @name randu * @type {PRNG} * @returns {number} pseudorandom number * * @example * var v = randu(); * // returns <number> */ var randu = factory(); // EXPORTS // module.exports = randu; },{"./factory.js":323}],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'; // MAIN // var prngs = {}; prngs[ 'minstd' ] = require( '@stdlib/random/base/minstd' ); prngs[ 'minstd-shuffle' ] = require( '@stdlib/random/base/minstd-shuffle' ); prngs[ 'mt19937' ] = require( '@stdlib/random/base/mt19937' ); // EXPORTS // module.exports = prngs; },{"@stdlib/random/base/minstd":315,"@stdlib/random/base/minstd-shuffle":311,"@stdlib/random/base/mt19937":319}],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'; /** * 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":328,"./regexp.js":329,"./regexp_capture.js":330,"@stdlib/utils/define-nonenumerable-read-only-property":374}],328:[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":331}],329:[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":328}],330:[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":328}],331:[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":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],332:[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":333,"./regexp.js":334,"@stdlib/utils/define-nonenumerable-read-only-property":374}],333:[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; },{}],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 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":333}],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'; /** * 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":336,"./regexp.js":337,"@stdlib/utils/define-nonenumerable-read-only-property":374}],336:[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; },{}],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 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":336}],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'; // MODULES // var bench = require( '@stdlib/bench' ); var randu = require( '@stdlib/random/base/randu' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var EPS = require( '@stdlib/constants/float64/eps' ); var pkg = require( './../package.json' ).name; var pdf = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var lambda; var x; var y; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { x = ( randu()*100.0 ); lambda = ( randu()*100.0 ) + EPS; y = pdf( x, lambda ); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+':factory', function benchmark( b ) { var lambda; var mypdf; var x; var y; var i; lambda = 10.0; mypdf = pdf.factory( lambda ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { x = ( randu()*100.0 ) + EPS; y = mypdf( x ); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); }); },{"./../lib":340,"./../package.json":342,"@stdlib/bench":224,"@stdlib/constants/float64/eps":237,"@stdlib/math/base/assert/is-nan":263,"@stdlib/random/base/randu":324}],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'; // MODULES // var constantFunction = require( '@stdlib/utils/constant-function' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var exp = require( '@stdlib/math/base/special/exp' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Returns a function for evaluating the probability density function (PDF) for an exponential distribution with parameter `lambda`. * * @param {PositiveNumber} lambda - rate parameter * @returns {Function} probability density function (PDF) * * @example * var pdf = factory( 0.5 ); * var y = pdf( 3.0 ); * // returns ~0.112 * * y = pdf( 1.0 ); * // returns ~0.303 */ function factory( lambda ) { var scale; if ( isnan( lambda ) || lambda < 0.0 || lambda === PINF ) { return constantFunction( NaN ); } scale = 1.0 / lambda; return pdf; /** * Evaluates the probability density function (PDF) for an exponential distribution. * * @private * @param {number} x - input value * @returns {number} evaluated PDF * * @example * var y = pdf( 2.3 ); * // returns <number> */ function pdf( x ) { if ( isnan( x ) ) { return NaN; } if ( x < 0.0 ) { return 0.0; } return exp( -x / scale ) / scale; } } // EXPORTS // module.exports = factory; },{"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/exp":275,"@stdlib/utils/constant-function":365}],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'; /** * Exponential distribution probability density function (PDF). * * @module @stdlib/stats/base/dists/exponential/pdf * * @example * var pdf = require( '@stdlib/stats/base/dists/exponential/pdf' ); * * var y = pdf( 0.3, 4.0 ); * // returns ~1.205 * * var myPDF = pdf.factory( 0.5 ); * * y = myPDF( 3.0 ); * // returns ~0.112 * * y = myPDF( 1.0 ); * // returns ~0.303 */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' ); var pdf = require( './pdf.js' ); var factory = require( './factory.js' ); // MAIN // setReadOnly( pdf, 'factory', factory ); // EXPORTS // module.exports = pdf; },{"./factory.js":339,"./pdf.js":341,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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 isnan = require( '@stdlib/math/base/assert/is-nan' ); var exp = require( '@stdlib/math/base/special/exp' ); var PINF = require( '@stdlib/constants/float64/pinf' ); // MAIN // /** * Evaluates the probability density function (PDF) for an exponential distribution with rate parameter `lambda` at a value `x`. * * @param {number} x - input value * @param {PositiveNumber} lambda - rate parameter * @returns {number} evaluated PDF * * @example * var y = pdf( 0.3, 4.0 ); * // returns ~1.205 * * @example * var y = pdf( 2.0, 0.7 ); * // returns ~0.173 * * @example * var y = pdf( -1.0, 0.5 ); * // returns 0.0 * * @example * var y = pdf( 0, NaN ); * // returns NaN * * @example * var y = pdf( NaN, 2.0 ); * // returns NaN * * @example * // Negative rate: * var y = pdf( 2.0, -1.0 ); * // returns NaN */ function pdf( x, lambda ) { var scale; if ( isnan( x ) || isnan( lambda ) || lambda < 0.0 || lambda === PINF ) { return NaN; } if ( x < 0.0 ) { return 0.0; } scale = 1.0 / lambda; return exp( -x / scale ) / scale; } // EXPORTS // module.exports = pdf; },{"@stdlib/constants/float64/pinf":246,"@stdlib/math/base/assert/is-nan":263,"@stdlib/math/base/special/exp":275}],342:[function(require,module,exports){ module.exports={ "name": "@stdlib/stats/base/dists/exponential/pdf", "version": "0.0.0", "description": "Exponential distribution probability density function (PDF).", "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", "stdmath", "statistics", "stats", "distribution", "dist", "probability", "continuous", "pdf", "life-time", "memoryless property", "arrival time", "exponential", "univariate" ] } },{}],343:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":458}],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 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":343,"./defaults.json":345,"./destroy.js":346,"./validate.js":351,"@stdlib/utils/copy":370,"@stdlib/utils/inherit":402,"debug":458,"readable-stream":475}],345:[function(require,module,exports){ module.exports={ "objectMode": false, "encoding": null, "allowHalfOpen": false, "decodeStrings": true } },{}],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'; // 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":428,"debug":458}],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 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":349,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":370}],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'; /** * 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":344,"./factory.js":347,"./main.js":349,"./object_mode.js":350,"@stdlib/utils/define-nonenumerable-read-only-property":374}],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'; // 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":343,"./defaults.json":345,"./destroy.js":346,"./validate.js":351,"@stdlib/utils/copy":370,"@stdlib/utils/inherit":402,"debug":458,"readable-stream":475}],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'; // 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":349,"@stdlib/assert/is-plain-object":147,"@stdlib/utils/copy":370}],351:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":53,"@stdlib/assert/is-boolean":81,"@stdlib/assert/is-function":102,"@stdlib/assert/is-nonnegative-number":131,"@stdlib/assert/is-plain-object":147,"@stdlib/assert/is-string":158}],352:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":353}],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'; // 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":90,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/unicode/max":258,"@stdlib/constants/unicode/max-bmp":257}],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'; /** * 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":355}],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'; // 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":102,"@stdlib/assert/is-regexp":154,"@stdlib/assert/is-string":158,"@stdlib/utils/escape-regexp-string":383}],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'; /** * 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":357}],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'; // 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":158,"@stdlib/string/replace":354}],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 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":360,"@stdlib/assert/is-object":145,"@stdlib/math/base/special/modf":283,"@stdlib/math/base/special/round":286,"@stdlib/utils/global":395}],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'; // MODULES // var isFunction = require( '@stdlib/assert/is-function' ); // MAIN // var bool = isFunction( Date.now ); // EXPORTS // module.exports = bool; },{"@stdlib/assert/is-function":102}],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'; // 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":359,"./polyfill.js":361}],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'; // 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; },{}],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'; /** * 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":363}],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'; // 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":126,"@stdlib/time/tic":358}],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'; /** * Creates a function which always returns the same value. * * @param {*} [value] - value to always return * @returns {Function} constant function * * @example * var fcn = wrap( 3.14 ); * * var v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 */ function wrap( value ) { return constantFunction; /** * Constant function. * * @private * @returns {*} constant value */ function constantFunction() { return value; } } // EXPORTS // module.exports = wrap; },{}],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'; /** * Create a constant function. * * @module @stdlib/utils/constant-function * * @example * var constantFunction = require( '@stdlib/utils/constant-function' ); * * var fcn = constantFunction( 3.14 ); * * var v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 * * v = fcn(); * // returns 3.14 */ // MODULES // var constantFunction = require( './constant_function.js' ); // EXPORTS // module.exports = constantFunction; },{"./constant_function.js":364}],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'; /** * 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":367}],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 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":88,"@stdlib/regexp/function-name":332,"@stdlib/utils/native-class":423}],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'; // 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":369,"@stdlib/assert/is-array":79,"@stdlib/assert/is-nonnegative-integer":127,"@stdlib/constants/float64/pinf":246}],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 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":371,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-array":79,"@stdlib/assert/is-buffer":88,"@stdlib/assert/is-error":96,"@stdlib/buffer/from-buffer":232,"@stdlib/utils/define-property":381,"@stdlib/utils/get-prototype-of":389,"@stdlib/utils/index-of":399,"@stdlib/utils/keys":416,"@stdlib/utils/property-descriptor":438,"@stdlib/utils/property-names":442,"@stdlib/utils/regexp-from-string":445,"@stdlib/utils/type-of":450}],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'; /** * 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":368}],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'; // 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":20,"@stdlib/array/uint32":23,"@stdlib/array/uint8":26,"@stdlib/array/uint8c":29}],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'; /** * 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":373}],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'; // 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":381}],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'; /** * 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":375}],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 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":381}],376:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-write accessor. * * @module @stdlib/utils/define-nonenumerable-read-write-accessor * * @example * var setNonEnumerableReadWriteAccessor = require( '@stdlib/utils/define-nonenumerable-read-write-accessor' ); * * function getter() { * return name + ' foo'; * } * * function setter( v ) { * name = v; * } * * var name = 'bar'; * var obj = {}; * * setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter ); * * var v = obj.foo; * // returns 'bar foo' * * obj.foo = 'beep'; * * v = obj.foo; * // returns 'beep foo' */ // MODULES // var setNonEnumerableReadWriteAccessor = require( './main.js' ); // EXPORTS // module.exports = setNonEnumerableReadWriteAccessor; },{"./main.js":377}],377:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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-write accessor. * * @param {Object} obj - object on which to define the property * @param {(string|symbol)} prop - property name * @param {Function} getter - get accessor * @param {Function} setter - set accessor * * @example * function getter() { * return name + ' foo'; * } * * function setter( v ) { * name = v; * } * * var name = 'bar'; * var obj = {}; * * setNonEnumerableReadWriteAccessor( obj, 'foo', getter, setter ); * * var v = obj.foo; * // returns 'bar foo' * * obj.foo = 'beep'; * * v = obj.foo; * // returns 'beep foo' */ function setNonEnumerableReadWriteAccessor( obj, prop, getter, setter ) { // eslint-disable-line id-length defineProperty( obj, prop, { 'configurable': false, 'enumerable': false, 'get': getter, 'set': setter }); } // EXPORTS // module.exports = setNonEnumerableReadWriteAccessor; },{"@stdlib/utils/define-property":381}],378:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],379:[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; },{}],380:[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":379}],381:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":378,"./has_define_property_support.js":380,"./polyfill.js":382}],382:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT 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; },{}],383:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":384}],384:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":158}],385:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 hasFunctionNameSupport = require( '@stdlib/assert/has-function-name-support' ); var RE = require( '@stdlib/regexp/function-name' ).REGEXP; // VARIABLES // var isFunctionNameSupported = hasFunctionNameSupport(); // MAIN // /** * Returns the name of a function. * * @param {Function} fcn - input function * @throws {TypeError} must provide a function * @returns {string} function name * * @example * var v = functionName( Math.sqrt ); * // returns 'sqrt' * * @example * var v = functionName( function foo(){} ); * // returns 'foo' * * @example * var v = functionName( function(){} ); * // returns '' || 'anonymous' * * @example * var v = functionName( String ); * // returns 'String' */ function functionName( fcn ) { // TODO: add support for generator functions? if ( isFunction( fcn ) === false ) { throw new TypeError( 'invalid argument. Must provide a function. Value: `' + fcn + '`.' ); } if ( isFunctionNameSupported ) { return fcn.name; } return RE.exec( fcn.toString() )[ 1 ]; } // EXPORTS // module.exports = functionName; },{"@stdlib/assert/has-function-name-support":39,"@stdlib/assert/is-function":102,"@stdlib/regexp/function-name":332}],386:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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 name of a function. * * @module @stdlib/utils/function-name * * @example * var functionName = require( '@stdlib/utils/function-name' ); * * var v = functionName( String ); * // returns 'String' * * v = functionName( function foo(){} ); * // returns 'foo' * * v = functionName( function(){} ); * // returns '' || 'anonymous' */ // MODULES // var functionName = require( './function_name.js' ); // EXPORTS // module.exports = functionName; },{"./function_name.js":385}],387:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":390,"./polyfill.js":391,"@stdlib/assert/is-function":102}],388:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":387}],389:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":388}],390:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],391:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":392,"@stdlib/utils/native-class":423}],392:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],393:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],394:[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 : {}) },{}],395:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":396}],396:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":393,"./global.js":394,"./self.js":397,"./window.js":398,"@stdlib/assert/is-boolean":81}],397:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],398:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],399:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":400}],400:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":90,"@stdlib/assert/is-integer":110,"@stdlib/assert/is-nan":118,"@stdlib/assert/is-string":158}],401:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":404,"./polyfill.js":405}],402:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":403}],403:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":401,"./validate.js":406,"@stdlib/utils/define-property":381}],404:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],405:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],406:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],407:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],408:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":407,"@stdlib/assert/is-arguments":74}],409:[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" ] },{}],410:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":407}],411:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":409,"./is_constructor_prototype.js":417,"./window.js":422,"@stdlib/assert/has-own-property":53,"@stdlib/utils/index-of":399,"@stdlib/utils/type-of":450}],412:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],413:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":93,"@stdlib/utils/noop":430}],414:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":93}],415:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],416:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":419}],417:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],418:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":411,"./has_window.js":415,"./is_constructor_prototype.js":417}],419:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":407,"./builtin_wrapper.js":408,"./has_arguments_bug.js":410,"./has_builtin.js":412,"./polyfill.js":421}],420:[function(require,module,exports){ module.exports=[ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ] },{}],421:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":413,"./has_non_enumerable_properties_bug.js":414,"./is_constructor_prototype_wrapper.js":418,"./non_enumerable.json":420,"@stdlib/assert/has-own-property":53,"@stdlib/assert/is-arguments":74,"@stdlib/assert/is-object-like":143}],422:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],423:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":424,"./polyfill.js":425,"@stdlib/assert/has-tostringtag-support":57}],424:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":426}],425:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":426,"./tostringtag.js":427,"@stdlib/assert/has-own-property":53}],426:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],427:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],428:[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":429}],429:[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":466}],430:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":431}],431:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],432:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":433}],433:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":158,"@stdlib/assert/is-string-array":157,"@stdlib/utils/index-of":399,"@stdlib/utils/keys":416}],434:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":435}],435:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":53,"@stdlib/assert/is-string":158,"@stdlib/assert/is-string-array":157}],436:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],437:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],438:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":436,"./has_builtin.js":437,"./polyfill.js":439}],439:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":53}],440:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],441:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],442:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":440,"./has_builtin.js":441,"./polyfill.js":443}],443:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":416}],444:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":158,"@stdlib/regexp/regexp":335}],445:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":444}],446:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":447,"./fixtures/re.js":448,"./fixtures/typedarray.js":449}],447:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":395}],448:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],449:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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; },{}],450:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":446,"./polyfill.js":451,"./typeof.js":452}],451:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":366}],452:[function(require,module,exports){ /** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR 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":366}],453:[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('') } },{}],454:[function(require,module,exports){ },{}],455:[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); } } },{}],456:[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":453,"buffer":456,"ieee754":460}],457:[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":462}],458:[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":459,"_process":466}],459:[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":464}],460:[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 } },{}],461:[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 } } } },{}],462:[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)) } },{}],463:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],464:[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'; } },{}],465:[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":466}],466:[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; }; },{}],467:[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":469,"./_stream_writable":471,"core-util-is":457,"inherits":461,"process-nextick-args":465}],468:[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":470,"core-util-is":457,"inherits":461}],469:[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":467,"./internal/streams/BufferList":472,"./internal/streams/destroy":473,"./internal/streams/stream":474,"_process":466,"core-util-is":457,"events":455,"inherits":461,"isarray":463,"process-nextick-args":465,"safe-buffer":476,"string_decoder/":477,"util":454}],470:[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":467,"core-util-is":457,"inherits":461}],471:[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":467,"./internal/streams/destroy":473,"./internal/streams/stream":474,"_process":466,"core-util-is":457,"inherits":461,"process-nextick-args":465,"safe-buffer":476,"timers":478,"util-deprecate":479}],472:[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":476,"util":454}],473:[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":465}],474:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":455}],475:[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":467,"./lib/_stream_passthrough.js":468,"./lib/_stream_readable.js":469,"./lib/_stream_transform.js":470,"./lib/_stream_writable.js":471}],476:[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":456}],477:[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":476}],478:[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":466,"timers":478}],479:[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 : {}) },{}]},{},[338]);
stdlib-js/www
public/docs/api/latest/@stdlib/stats/base/dists/exponential/pdf/benchmark_bundle.js
JavaScript
apache-2.0
938,262
/* Dopetrope 2.0 by HTML5 UP html5up.net | @n33co Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) */ window._skel_config = { preset: 'standard', prefix: DPT.theme + '/css/style', resetCSS: true, breakpoints: { 'desktop': { grid: { gutters: 50 } } } }; window._skel_panels_config = { preset: 'standard' };
leagueofbeards/habaridopetrope
js/config.js
JavaScript
apache-2.0
387
/** * @license * Copyright 2014 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. */ // Asynchronous eval workaround for lack of eval in Chrome Apps. Do not add // workaround in Cordova Chrome Apps. if ( ! (window.cordova && window.chrome) ) { TemplateUtil.compile = function() { return function() { return this.name_ + " wasn't required. Models must be arequired()'ed for Templates to be compiled in Packaged Apps."; }; }; var __EVAL_CALLBACKS__ = {}; var aeval = (function() { var nextID = 0; var future = afuture(); if ( ! document.body ) window.addEventListener('load', future.set); else future.set(); return function(src) { return aseq( future.get, function(ret) { var id = 'c' + (nextID++); var newjs = ['__EVAL_CALLBACKS__["' + id + '"](' + src + ');']; var blob = new Blob(newjs, {type: 'text/javascript'}); var url = window.URL.createObjectURL(blob); // TODO: best values? // url.defer = ?; // url.async = ?; __EVAL_CALLBACKS__[id] = function(data) { delete __EVAL_CALLBACKS__[id]; ret && ret.call(this, data); }; var script = document.createElement('script'); script.src = url; script.onload = function() { this.remove(); window.URL.revokeObjectURL(url); // document.body.removeChild(this); }; document.body.appendChild(script); }); }; })(); var TEMPLATE_FUNCTIONS = []; var aevalTemplate = function(t, model) { var doEval_ = function(t) { // Parse result: [isSimple, maybeCode]: [true, null] or [false, codeString]. var parseResult = TemplateCompiler.parseString(t.template); // Simple case, just a string literal if ( parseResult[0] ) return aconstant(ConstantTemplate(t.language === 'css' ? X.foam.grammars.CSS3.create().parser.parseString(t.template).toString() : t.template)); var code = TemplateUtil.HEADER + parseResult[1] + TemplateUtil.FOOTERS[t.language]; var args = ['opt_out']; if ( t.args ) { for ( var i = 0 ; i < t.args.length ; i++ ) { args.push(t.args[i].name); } } return aeval('function(' + args.join(',') + '){' + code + '}'); }; var doEval = function(t) { try { return doEval_(t); } catch (err) { console.log('Template Error: ', err); console.log(code); return aconstant(function() {return 'TemplateError: Check console.';}); } }; var i = TEMPLATE_FUNCTIONS.length; TEMPLATE_FUNCTIONS[i] = ''; return aseq( t.futureTemplate, function(ret, t) { doEval(t)(ret); }, function(ret, f) { TEMPLATE_FUNCTIONS[i] = f; ret(f); }); }; }
osric-the-knight/foam
core/ChromeEval.js
JavaScript
apache-2.0
3,509
/** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {mod} from '../../../src/utils/math'; /** * @enum {number} */ export const Axis = { X: 0, Y: 1, }; /** * @enum {string} */ export const Alignment = { START: 'start', CENTER: 'center', }; /** * @enum {string} */ export const Orientation = { HORIZONTAL: 'horizontal', VERTICAL: 'vertical', }; /** * @typedef {{ * start: number, * end: number, * length: number, * }} */ let BaseCarouselDimensionDef; /** * @param {!Axis} axis The Axis to get the Dimension for. * @param {*} el The Element to get the Dimension For. * @return {!BaseCarouselDimensionDef} The dimension for the Element along the given Axis. */ export function getDimension(axis, el) { const { top, bottom, height, left, right, width, } = el./*OK*/ getBoundingClientRect(); return { start: Math.round(axis == Axis.X ? left : top), end: Math.round(axis == Axis.X ? right : bottom), length: Math.round(axis == Axis.X ? width : height), }; } /** * @param {!Axis} axis The axis to get the center point for. * @param {!Element} el The Element to get the center point for. * @return {number} The center point. */ export function getCenter(axis, el) { const {start, end} = getDimension(axis, el); return (start + end) / 2; } /** * @param {!Axis} axis The axis to get the start point for. * @param {!Element} el The Element to get the start point for. * @return {number} The start point. */ export function getStart(axis, el) { const {start} = getDimension(axis, el); return start; } /** * @param {!Axis} axis The Axis to get the position for. * @param {!Alignment} alignment The Alignment to get the position for. * @param {!Element} el The Element to get the position for. * @return {number} The position for the given Element along the given axis for * the given alignment. */ export function getPosition(axis, alignment, el) { return alignment == Alignment.START ? getStart(axis, el) : getCenter(axis, el); } /** * @param {!Axis} axis The axis to check for overlap. * @param {!Element} el The Element to check for overlap. * @param {number} position A position to check. * @return {boolean} If the element overlaps the position along the given axis. */ export function overlaps(axis, el, position) { const {start, end} = getDimension(axis, el); // Ignore the end point, since that is shared with the adjacent Element. return start <= position && position < end; } /** * @param {!Axis} axis The axis to align on. * @param {!Alignment} alignment The desired alignment. * @param {!Element} container The container to align against. * @param {!Element} el The Element get the offset for. * @return {number} How far el is from alignment, as a percentage of its length. */ export function getPercentageOffsetFromAlignment( axis, alignment, container, el ) { const elPos = getPosition(axis, alignment, el); const containerPos = getPosition(axis, alignment, container); const {length: elLength} = getDimension(axis, el); return (elPos - containerPos) / elLength; } /** * Finds the index of a child that overlaps a point within the parent, * determined by an axis and alignment. A startIndex is used to look at the * children that are more likely to overlap first. * @param {!Axis} axis The axis to look along. * @param {!Alignment} alignment The alignment to look for within the parent * container. * @param {!Element} container The parent container to look in. * @param {!HTMLCollection} children The children to look among. * @param {number} startIndex The index to start looking at. * @return {number|undefined} The overlapping index, if one exists. */ export function findOverlappingIndex( axis, alignment, container, children, startIndex ) { const pos = getPosition(axis, alignment, container); // First look at the start index, since is the most likely to overlap. if (overlaps(axis, children[startIndex], pos)) { return startIndex; } // Move outwards, since the closer indicies are more likely to overlap. for (let i = 1; i <= children.length / 2; i++) { const nextIndex = mod(startIndex + i, children.length); const prevIndex = mod(startIndex - i, children.length); if (overlaps(axis, children[nextIndex], pos)) { return nextIndex; } if (overlaps(axis, children[prevIndex], pos)) { return prevIndex; } } } /** * Gets the current scroll position for an element along a given axis. * @param {!Axis} axis The axis to set the scroll position for. * @param {!Element} el The Element to set the scroll position for. * @return {number} The scroll position. */ export function getScrollPosition(axis, el) { if (axis == Axis.X) { return el./*OK*/ scrollLeft; } return el./*OK*/ scrollTop; } /** * Sets the scroll position for an element along a given axis. * @param {!Axis} axis The axis to set the scroll position for. * @param {!Element} el The Element to set the scroll position for. * @param {number} position The scroll position. */ export function setScrollPosition(axis, el, position) { if (axis == Axis.X) { el./*OK*/ scrollLeft = position; } else { el./*OK*/ scrollTop = position; } } /** * Updates the scroll position for an element along a given axis. * @param {!Axis} axis The axis to set the scroll position for. * @param {!Element} el The Element to set the scroll position for. * @param {number} delta The scroll delta. */ export function updateScrollPosition(axis, el, delta) { setScrollPosition(axis, el, getScrollPosition(axis, el) + delta); } /** * Scrolls the position within a scrolling container to an Element. Unlike * `scrollIntoView`, this function does not scroll the container itself into * view. * @param {!Axis} axis The axis to scroll along. * @param {!Alignment} alignment How to align the element within the container. * @param {!Element} container The scrolling container. * @param {!Element} el The Element to scroll to. * @param {number} offset A percentage offset within the element to scroll to. * @return {boolean} Whether not scrolling was performed. */ export function scrollContainerToElement( axis, alignment, container, el, offset = 0 ) { const startAligned = alignment == Alignment.START; const {length} = getDimension(axis, el); const snapOffset = startAligned ? getStart(axis, el) : getCenter(axis, el); const scrollOffset = startAligned ? getStart(axis, container) : getCenter(axis, container); const delta = Math.round(snapOffset - scrollOffset - offset * length); updateScrollPosition(axis, container, delta); return !!delta; }
jmadler/amphtml
extensions/amp-base-carousel/1.0/dimensions.js
JavaScript
apache-2.0
7,290
module.controller('ResourceServerCtrl', function($scope, realm, ResourceServer) { $scope.realm = realm; ResourceServer.query({realm : realm.realm}, function (data) { $scope.servers = data; }); }); module.controller('ResourceServerDetailCtrl', function($scope, $http, $route, $location, $upload, realm, ResourceServer, client, AuthzDialog, Notifications) { $scope.realm = realm; $scope.client = client; ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = angular.copy(data); $scope.changed = false; $scope.$watch('server', function() { if (!angular.equals($scope.server, data)) { $scope.changed = true; } }, true); $scope.save = function() { ResourceServer.update({realm : realm.realm, client : $scope.server.clientId}, $scope.server, function() { $route.reload(); Notifications.success("The resource server has been created."); }); } $scope.reset = function() { $scope.server = angular.copy(data); $scope.changed = false; } $scope.export = function() { $scope.exportSettings = true; ResourceServer.settings({ realm : $route.current.params.realm, client : client.id }, function(data) { var tmp = angular.fromJson(data); $scope.settings = angular.toJson(tmp, true); }) } $scope.downloadSettings = function() { saveAs(new Blob([$scope.settings], { type: 'application/json' }), $scope.server.name + "-authz-config.json"); } $scope.cancelExport = function() { delete $scope.settings } $scope.onFileSelect = function($files) { $scope.files = $files; }; $scope.clearFileSelect = function() { $scope.files = null; } $scope.uploadFile = function() { //$files: an array of files selected, each file has name, size, and type. for (var i = 0; i < $scope.files.length; i++) { var $file = $scope.files[i]; $scope.upload = $upload.upload({ url: authUrl + '/admin/realms/' + $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server', //upload.php script, node.js route, or servlet url // method: POST or PUT, // headers: {'headerKey': 'headerValue'}, withCredential: true, data: {myObj: ""}, file: $file /* set file formData name for 'Content-Desposition' header. Default: 'file' */ //fileFormDataName: myFile, /* customize how data is added to formData. See #40#issuecomment-28612000 for example */ //formDataAppender: function(formData, key, val){} }).progress(function(evt) { console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total)); }).success(function(data, status, headers) { $route.reload(); Notifications.success("The resource server has been updated."); }).error(function() { Notifications.error("The resource server can not be uploaded. Please verify the file."); }); } }; }); }); module.controller('ResourceServerResourceCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerResource, client) { $scope.realm = realm; $scope.client = client; ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; $scope.createPolicy = function(resource) { $location.path('/realms/' + $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/permission/resource/create').search({rsrid: resource._id}); } ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) { $scope.resources = data; }); }); }); module.controller('ResourceServerResourceDetailCtrl', function($scope, $http, $route, $location, realm, ResourceServer, client, ResourceServerResource, ResourceServerScope, AuthzDialog, Notifications) { $scope.realm = realm; $scope.client = client; ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) { $scope.scopes = data; }); ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; var resourceId = $route.current.params.rsrid; if (!resourceId) { $scope.create = true; $scope.changed = false; var resource = {}; resource.scopes = []; $scope.resource = angular.copy(resource); $scope.$watch('resource', function() { if (!angular.equals($scope.resource, resource)) { $scope.changed = true; } }, true); $scope.save = function() { ResourceServerResource.save({realm : realm.realm, client : $scope.client.id}, $scope.resource, function(data) { $location.url("/realms/" + realm.realm + "/clients/" + $scope.client.id + "/authz/resource-server/resource/" + data._id); Notifications.success("The resource has been created."); }); } $scope.cancel = function() { $location.url("/realms/" + realm.realm + "/clients/" + $scope.client.id + "/authz/resource-server/resource/"); } } else { ResourceServerResource.get({ realm : $route.current.params.realm, client : client.id, rsrid : $route.current.params.rsrid, }, function(data) { $scope.resource = angular.copy(data); $scope.changed = false; for (i = 0; i < $scope.resource.scopes.length; i++) { $scope.resource.scopes[i] = $scope.resource.scopes[i].name; } $scope.$watch('resource', function() { if (!angular.equals($scope.resource, data)) { $scope.changed = true; } }, true); $scope.save = function() { ResourceServerResource.update({realm : realm.realm, client : $scope.client.id, rsrid : $scope.resource._id}, $scope.resource, function() { $route.reload(); Notifications.success("The resource has been updated."); }); } $scope.remove = function() { var msg = ""; if ($scope.resource.policies.length > 0) { msg = "<p>This resource is referenced in some policies:</p>"; msg += "<ul>"; for (i = 0; i < $scope.resource.policies.length; i++) { msg+= "<li><strong>" + $scope.resource.policies[i].name + "</strong></li>"; } msg += "</ul>"; msg += "<p>If you remove this resource, the policies above will be affected and will not be associated with this resource anymore.</p>"; } AuthzDialog.confirmDeleteWithMsg($scope.resource.name, "Resource", msg, function() { ResourceServerResource.delete({realm : realm.realm, client : $scope.client.id, rsrid : $scope.resource._id}, null, function() { $location.url("/realms/" + realm.realm + "/clients/" + $scope.client.id + "/authz/resource-server/resource"); Notifications.success("The resource has been deleted."); }); }); } $scope.reset = function() { $scope.resource = angular.copy(data); $scope.changed = false; } }); } }); }); module.controller('ResourceServerScopeCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerScope, client) { $scope.realm = realm; $scope.client = client; ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) { $scope.scopes = data; }); }); }); module.controller('ResourceServerScopeDetailCtrl', function($scope, $http, $route, $location, realm, ResourceServer, client, ResourceServerScope, AuthzDialog, Notifications) { $scope.realm = realm; $scope.client = client; ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; var scopeId = $route.current.params.id; if (!scopeId) { $scope.create = true; $scope.changed = false; var scope = {}; $scope.resource = angular.copy(scope); $scope.$watch('scope', function() { if (!angular.equals($scope.scope, scope)) { $scope.changed = true; } }, true); $scope.save = function() { ResourceServerScope.save({realm : realm.realm, client : $scope.client.id}, $scope.scope, function(data) { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/scope/" + data.id); Notifications.success("The scope has been created."); }); } } else { ResourceServerScope.get({ realm : $route.current.params.realm, client : client.id, id : $route.current.params.id, }, function(data) { $scope.scope = angular.copy(data); $scope.changed = false; $scope.$watch('scope', function() { if (!angular.equals($scope.scope, data)) { $scope.changed = true; } }, true); $scope.save = function() { ResourceServerScope.update({realm : realm.realm, client : $scope.client.id, id : $scope.scope.id}, $scope.scope, function() { $scope.changed = false; Notifications.success("The scope has been updated."); }); } $scope.remove = function() { var msg = ""; if ($scope.scope.policies.length > 0) { msg = "<p>This resource is referenced in some policies:</p>"; msg += "<ul>"; for (i = 0; i < $scope.scope.policies.length; i++) { msg+= "<li><strong>" + $scope.scope.policies[i].name + "</strong></li>"; } msg += "</ul>"; msg += "<p>If you remove this resource, the policies above will be affected and will not be associated with this resource anymore.</p>"; } AuthzDialog.confirmDeleteWithMsg($scope.scope.name, "Scope", msg, function() { ResourceServerScope.delete({realm : realm.realm, client : $scope.client.id, id : $scope.scope.id}, null, function() { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/scope"); Notifications.success("The scope has been deleted."); }); }); } $scope.reset = function() { $scope.scope = angular.copy(data); $scope.changed = false; } }); } }); }); module.controller('ResourceServerPolicyCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerPolicy, PolicyProvider, client) { $scope.realm = realm; $scope.client = client; $scope.policyProviders = []; PolicyProvider.query({ realm : $route.current.params.realm, client : client.id }, function (data) { for (i = 0; i < data.length; i++) { if (data[i].type != 'resource' && data[i].type != 'scope') { $scope.policyProviders.push(data[i]); } } }); ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) { $scope.policies = []; for (i = 0; i < data.length; i++) { if (data[i].type != 'resource' && data[i].type != 'scope') { $scope.policies.push(data[i]); } } }); }); $scope.addPolicy = function(policyType) { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy/" + policyType.type + "/create"); } }); module.controller('ResourceServerPermissionCtrl', function($scope, $http, $route, $location, realm, ResourceServer, ResourceServerPolicy, PolicyProvider, client) { $scope.realm = realm; $scope.client = client; $scope.policyProviders = []; PolicyProvider.query({ realm : $route.current.params.realm, client : client.id }, function (data) { for (i = 0; i < data.length; i++) { if (data[i].type == 'resource' || data[i].type == 'scope') { $scope.policyProviders.push(data[i]); } } }); ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) { $scope.policies = []; for (i = 0; i < data.length; i++) { if (data[i].type == 'resource' || data[i].type == 'scope') { $scope.policies.push(data[i]); } } }); }); $scope.addPolicy = function(policyType) { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission/" + policyType.type + "/create"); } }); module.controller('ResourceServerPolicyDroolsDetailCtrl', function($scope, $http, $route, realm, client, PolicyController) { PolicyController.onInit({ getPolicyType : function() { return "drools"; }, onInit : function() { $scope.drools = {}; $scope.resolveModules = function(policy) { if (!policy) { policy = $scope.policy; } $http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/drools/resolveModules' , policy).success(function(data) { $scope.drools.moduleNames = data; $scope.resolveSessions(); }); } $scope.resolveSessions = function() { $http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/drools/resolveSessions' , $scope.policy).success(function(data) { $scope.drools.moduleSessions = data; }); } }, onInitUpdate : function(policy) { policy.config.scannerPeriod = parseInt(policy.config.scannerPeriod); $scope.resolveModules(policy); }, onUpdate : function() { $scope.policy.config.resources = JSON.stringify($scope.policy.config.resources); }, onInitCreate : function(newPolicy) { newPolicy.config.scannerPeriod = 1; newPolicy.config.scannerPeriodUnit = 'Hours'; } }, realm, client, $scope); }); module.controller('ResourceServerPolicyResourceDetailCtrl', function($scope, $route, $location, realm, client, PolicyController, ResourceServerPolicy, ResourceServerResource) { PolicyController.onInit({ getPolicyType : function() { return "resource"; }, isPermission : function() { return true; }, onInit : function() { ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) { $scope.resources = data; }); ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) { $scope.policies = []; for (i = 0; i < data.length; i++) { if (data[i].type != 'resource' && data[i].type != 'scope') { $scope.policies.push(data[i]); } } }); $scope.applyToResourceType = function() { if ($scope.policy.config.default) { $scope.policy.config.resources = []; } else { $scope.policy.config.defaultResourceType = null; } } }, onInitUpdate : function(policy) { policy.config.default = eval(policy.config.default); policy.config.resources = eval(policy.config.resources); policy.config.applyPolicies = eval(policy.config.applyPolicies); }, onUpdate : function() { $scope.policy.config.resources = JSON.stringify($scope.policy.config.resources); $scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies); }, onInitCreate : function(newPolicy) { newPolicy.decisionStrategy = 'UNANIMOUS'; newPolicy.config = {}; newPolicy.config.resources = ''; var resourceId = $location.search()['rsrid']; if (resourceId) { newPolicy.config.resources = [resourceId]; } }, onCreate : function() { $scope.policy.config.resources = JSON.stringify($scope.policy.config.resources); $scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies); } }, realm, client, $scope); }); module.controller('ResourceServerPolicyScopeDetailCtrl', function($scope, $route, realm, client, PolicyController, ResourceServerPolicy, ResourceServerResource, ResourceServerScope) { PolicyController.onInit({ getPolicyType : function() { return "scope"; }, isPermission : function() { return true; }, onInit : function() { ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) { $scope.scopes = data; }); ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) { $scope.resources = data; }); ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) { $scope.policies = []; for (i = 0; i < data.length; i++) { if (data[i].type != 'resource' && data[i].type != 'scope') { $scope.policies.push(data[i]); } } }); $scope.resolveScopes = function(policy, keepScopes) { if (!keepScopes) { policy.config.scopes = []; } if (!policy) { policy = $scope.policy; } if (policy.config.resources != null) { ResourceServerResource.get({ realm : $route.current.params.realm, client : client.id, rsrid : policy.config.resources }, function(data) { $scope.scopes = data.scopes; }); } else { ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) { $scope.scopes = data; }); } } }, onInitUpdate : function(policy) { if (policy.config.resources) { policy.config.resources = eval(policy.config.resources); if (policy.config.resources.length > 0) { policy.config.resources = policy.config.resources[0]; } else { policy.config.resources = null; } } $scope.resolveScopes(policy, true); policy.config.applyPolicies = eval(policy.config.applyPolicies); policy.config.scopes = eval(policy.config.scopes); }, onUpdate : function() { if ($scope.policy.config.resources != null) { var resources = undefined; if ($scope.policy.config.resources.length != 0) { resources = JSON.stringify([$scope.policy.config.resources]) } $scope.policy.config.resources = resources; } $scope.policy.config.scopes = JSON.stringify($scope.policy.config.scopes); $scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies); }, onInitCreate : function(newPolicy) { newPolicy.decisionStrategy = 'UNANIMOUS'; newPolicy.config = {}; newPolicy.config.resources = ''; }, onCreate : function() { if ($scope.policy.config.resources != null) { var resources = undefined; if ($scope.policy.config.resources.length != 0) { resources = JSON.stringify([$scope.policy.config.resources]) } $scope.policy.config.resources = resources; } $scope.policy.config.scopes = JSON.stringify($scope.policy.config.scopes); $scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies); } }, realm, client, $scope); }); module.controller('ResourceServerPolicyUserDetailCtrl', function($scope, $route, realm, client, PolicyController, User) { PolicyController.onInit({ getPolicyType : function() { return "user"; }, onInit : function() { User.query({realm: $route.current.params.realm}, function(data) { $scope.users = data; }); $scope.selectedUsers = []; $scope.selectUser = function(user) { if (!user || !user.id) { return; } $scope.selectedUser = {}; $scope.selectedUsers.push(user); } $scope.removeFromList = function(list, index) { list.splice(index, 1); } }, onInitUpdate : function(policy) { var selectedUsers = []; if (policy.config.users) { var users = eval(policy.config.users); for (i = 0; i < users.length; i++) { User.get({realm: $route.current.params.realm, userId: users[i]}, function(data) { selectedUsers.push(data); $scope.selectedUsers = angular.copy(selectedUsers); }); } } $scope.$watch('selectedUsers', function() { if (!angular.equals($scope.selectedUsers, selectedUsers)) { $scope.changed = true; } }, true); }, onUpdate : function() { var users = []; for (i = 0; i < $scope.selectedUsers.length; i++) { users.push($scope.selectedUsers[i].id); } $scope.policy.config.users = JSON.stringify(users); }, onCreate : function() { var users = []; for (i = 0; i < $scope.selectedUsers.length; i++) { users.push($scope.selectedUsers[i].id); } $scope.policy.config.users = JSON.stringify(users); } }, realm, client, $scope); }); module.controller('ResourceServerPolicyRoleDetailCtrl', function($scope, $route, realm, client, PolicyController, Role, RoleById) { PolicyController.onInit({ getPolicyType : function() { return "role"; }, onInit : function() { Role.query({realm: $route.current.params.realm}, function(data) { $scope.roles = data; }); $scope.selectedRoles = []; $scope.selectRole = function(role) { if (!role || !role.id) { return; } $scope.selectedRole = {}; $scope.selectedRoles.push(role); } $scope.removeFromList = function(list, index) { list.splice(index, 1); } }, onInitUpdate : function(policy) { var selectedRoles = []; if (policy.config.roles) { var roles = eval(policy.config.roles); for (i = 0; i < roles.length; i++) { RoleById.get({realm: $route.current.params.realm, role: roles[i]}, function(data) { selectedRoles.push(data); $scope.selectedRoles = angular.copy(selectedRoles); }); } } $scope.$watch('selectedRoles', function() { if (!angular.equals($scope.selectedRoles, selectedRoles)) { $scope.changed = true; } }, true); }, onUpdate : function() { var roles = []; for (i = 0; i < $scope.selectedRoles.length; i++) { roles.push($scope.selectedRoles[i].id); } $scope.policy.config.roles = JSON.stringify(roles); }, onCreate : function() { var roles = []; for (i = 0; i < $scope.selectedRoles.length; i++) { roles.push($scope.selectedRoles[i].id); } $scope.policy.config.roles = JSON.stringify(roles); } }, realm, client, $scope); }); module.controller('ResourceServerPolicyJSDetailCtrl', function($scope, $route, $location, realm, PolicyController, client) { PolicyController.onInit({ getPolicyType : function() { return "js"; }, onInit : function() { $scope.initEditor = function(editor){ var session = editor.getSession(); session.setMode('ace/mode/javascript'); }; }, onInitUpdate : function(policy) { }, onUpdate : function() { }, onInitCreate : function(newPolicy) { newPolicy.config = {}; }, onCreate : function() { } }, realm, client, $scope); }); module.controller('ResourceServerPolicyTimeDetailCtrl', function($scope, $route, $location, realm, PolicyController, client) { PolicyController.onInit({ getPolicyType : function() { return "time"; }, onInit : function() { }, onInitUpdate : function(policy) { }, onUpdate : function() { }, onInitCreate : function(newPolicy) { newPolicy.config.expirationTime = 1; newPolicy.config.expirationUnit = 'Minutes'; }, onCreate : function() { } }, realm, client, $scope); }); module.controller('ResourceServerPolicyAggregateDetailCtrl', function($scope, $route, $location, realm, PolicyController, ResourceServerPolicy, client) { PolicyController.onInit({ getPolicyType : function() { return "aggregate"; }, onInit : function() { ResourceServerPolicy.query({realm : realm.realm, client : client.id}, function (data) { $scope.policies = []; for (i = 0; i < data.length; i++) { if (data[i].type != 'resource' && data[i].type != 'scope') { $scope.policies.push(data[i]); } } }); }, onInitUpdate : function(policy) { policy.config.applyPolicies = eval(policy.config.applyPolicies); }, onUpdate : function() { $scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies); }, onInitCreate : function(newPolicy) { newPolicy.config = {}; newPolicy.decisionStrategy = 'UNANIMOUS'; }, onCreate : function() { $scope.policy.config.applyPolicies = JSON.stringify($scope.policy.config.applyPolicies); } }, realm, client, $scope); }); module.service("PolicyController", function($http, $route, $location, ResourceServer, ResourceServerPolicy, AuthzDialog, Notifications) { var PolicyController = {}; PolicyController.onInit = function(delegate, realm, client, $scope) { if (!delegate.isPermission) { delegate.isPermission = function () { return false; } } $scope.realm = realm; $scope.client = client; $scope.decisionStrategies = ['AFFIRMATIVE', 'UNANIMOUS', 'CONSENSUS']; $scope.logics = ['POSITIVE', 'NEGATIVE']; delegate.onInit(); ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; var policyId = $route.current.params.id; if (!policyId) { $scope.create = true; $scope.changed = false; var policy = {}; policy.type = delegate.getPolicyType(); policy.config = {}; policy.logic = 'POSITIVE'; if (delegate.onInitCreate) { delegate.onInitCreate(policy); } $scope.policy = angular.copy(policy); $scope.$watch('policy', function() { if (!angular.equals($scope.policy, policy)) { $scope.changed = true; } }, true); $scope.save = function() { if (delegate.onCreate) { delegate.onCreate(); } ResourceServerPolicy.save({realm : realm.realm, client : client.id}, $scope.policy, function(data) { if (delegate.isPermission()) { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission/" + $scope.policy.type + "/" + data.id); Notifications.success("The permission has been created."); } else { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy/" + $scope.policy.type + "/" + data.id); Notifications.success("The policy has been created."); } }); } $scope.cancel = function() { if (delegate.isPermission()) { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission/"); } else { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy/"); } } } else { ResourceServerPolicy.get({ realm : $route.current.params.realm, client : client.id, id : $route.current.params.id, }, function(data) { var policy = angular.copy(data); if (delegate.onInitUpdate) { delegate.onInitUpdate(policy); } $scope.policy = angular.copy(policy); $scope.changed = false; $scope.$watch('policy', function() { if (!angular.equals($scope.policy, policy)) { $scope.changed = true; } }, true); $scope.save = function() { if (delegate.onUpdate) { delegate.onUpdate(); } ResourceServerPolicy.update({realm : realm.realm, client : client.id, id : $scope.policy.id}, $scope.policy, function() { $route.reload(); if (delegate.isPermission()) { Notifications.success("The permission has been updated."); } else { Notifications.success("The policy has been updated."); } }); } $scope.reset = function() { var freshPolicy = angular.copy(data); if (delegate.onInitUpdate) { delegate.onInitUpdate(freshPolicy); } $scope.policy = angular.copy(freshPolicy); $scope.changed = false; } }); $scope.remove = function() { var msg = ""; if ($scope.policy.dependentPolicies.length > 0) { msg = "<p>This policy is being used by other policies:</p>"; msg += "<ul>"; for (i = 0; i < $scope.policy.dependentPolicies.length; i++) { msg+= "<li><strong>" + $scope.policy.dependentPolicies[i].name + "</strong></li>"; } msg += "</ul>"; msg += "<p>If you remove this policy, the policies above will be affected and will not be associated with this policy anymore.</p>"; } AuthzDialog.confirmDeleteWithMsg($scope.policy.name, "Policy", msg, function() { ResourceServerPolicy.delete({realm : $scope.realm.realm, client : $scope.client.id, id : $scope.policy.id}, null, function() { if (delegate.isPermission()) { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/permission"); Notifications.success("The permission has been deleted."); } else { $location.url("/realms/" + realm.realm + "/clients/" + client.id + "/authz/resource-server/policy"); Notifications.success("The policy has been deleted."); } }); }); } } }); } return PolicyController; }); module.controller('PolicyEvaluateCtrl', function($scope, $http, $route, $location, realm, clients, roles, ResourceServer, client, ResourceServerResource, ResourceServerScope, User, Notifications) { $scope.realm = realm; $scope.client = client; $scope.clients = clients; $scope.roles = roles; $scope.authzRequest = {}; $scope.authzRequest.resources = []; $scope.authzRequest.context = {}; $scope.authzRequest.context.attributes = {}; $scope.authzRequest.roleIds = []; $scope.newResource = {}; $scope.resultUrl = resourceUrl + '/partials/authz/policy/resource-server-policy-evaluate-result.html'; ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) { $scope.scopes = data; }); $scope.addContextAttribute = function() { if (!$scope.newContextAttribute.value || $scope.newContextAttribute.value == '') { Notifications.error("You must provide a value to a context attribute."); return; } $scope.authzRequest.context.attributes[$scope.newContextAttribute.key] = $scope.newContextAttribute.value; delete $scope.newContextAttribute; } $scope.removeContextAttribute = function(key) { delete $scope.authzRequest.context.attributes[key]; } $scope.getContextAttribute = function(key) { for (i = 0; i < $scope.defaultContextAttributes.length; i++) { if ($scope.defaultContextAttributes[i].key == key) { return $scope.defaultContextAttributes[i]; } } return $scope.authzRequest.context.attributes[key]; } $scope.getContextAttributeName = function(key) { var attribute = $scope.getContextAttribute(key); if (!attribute.name) { return key; } return attribute.name; } $scope.defaultContextAttributes = [ { key : "custom", name : "Custom Attribute...", custom: true }, { key : "kc.authz.context.authc.method", name : "Authentication Method", values: [ { key : "pwd", name : "Password" }, { key : "otp", name : "One-Time Password" }, { key : "kbr", name : "Kerberos" } ] }, { key : "kc.authz.context.authc.realm", name : "Realm" }, { key : "kc.authz.context.time.date_time", name : "Date/Time (MM/dd/yyyy hh:mm:ss)" }, { key : "kc.authz.context.client.network.ip_address", name : "Client IPv4 Address" }, { key : "kc.authz.context.client.network.host", name : "Client Host" }, { key : "kc.authz.context.client.user_agent", name : "Client/User Agent" } ]; $scope.isDefaultContextAttribute = function() { if (!$scope.newContextAttribute) { return true; } if ($scope.newContextAttribute.custom) { return false; } if (!$scope.getContextAttribute($scope.newContextAttribute.key).custom) { return true; } return false; } $scope.selectDefaultContextAttribute = function() { $scope.newContextAttribute = angular.copy($scope.newContextAttribute); } $scope.setApplyToResourceType = function() { if ($scope.applyResourceType) { ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) { $scope.scopes = data; }); } delete $scope.newResource; $scope.authzRequest.resources = []; } $scope.addResource = function() { var resource = {}; resource.id = $scope.newResource._id; for (i = 0; i < $scope.resources.length; i++) { if ($scope.resources[i]._id == resource.id) { resource.name = $scope.resources[i].name; break; } } resource.scopes = $scope.newResource.scopes; $scope.authzRequest.resources.push(resource); delete $scope.newResource; } $scope.removeResource = function(index) { $scope.authzRequest.resources.splice(index, 1); } $scope.resolveScopes = function() { if ($scope.newResource._id) { $scope.newResource.scopes = []; $scope.scopes = []; ResourceServerResource.get({ realm: $route.current.params.realm, client : client.id, rsrid: $scope.newResource._id }, function (data) { $scope.scopes = data.scopes; }); } else { ResourceServerScope.query({realm : realm.realm, client : client.id}, function (data) { $scope.scopes = data; }); } } $scope.save = function() { $scope.authzRequest.entitlements = false; if ($scope.applyResourceType) { if (!$scope.newResource) { $scope.newResource = {}; } $scope.authzRequest.resources[0].scopes = $scope.newResource.scopes; } $http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/evaluate' , $scope.authzRequest).success(function(data) { $scope.evaluationResult = data; $scope.showResultTab(); }); } $scope.entitlements = function() { $scope.authzRequest.entitlements = true; $http.post(authUrl + '/admin/realms/'+ $route.current.params.realm + '/clients/' + client.id + '/authz/resource-server/policy/evaluate' , $scope.authzRequest).success(function(data) { $scope.evaluationResult = data; $scope.showResultTab(); }); } $scope.showResultTab = function() { $scope.showResult = true; } $scope.showRequestTab = function() { $scope.showResult = false; } User.query({realm: $route.current.params.realm}, function(data) { $scope.users = data; }); ResourceServerResource.query({realm : realm.realm, client : client.id}, function (data) { $scope.resources = data; }); ResourceServer.get({ realm : $route.current.params.realm, client : client.id }, function(data) { $scope.server = data; }); });
AOEpeople/keycloak
themes/src/main/resources/theme/base/admin/resources/js/authz/authz-controller.js
JavaScript
apache-2.0
43,159
'use strict'; let lib = { "_id": "5e409c94c5a59210a815262c", "name": "pay", "description": "MS pay service for marketplace", "type": "service", "configuration": { "subType": "ecommerce", "port": 4102, "group": "Marketplace", "requestTimeout": 30, "requestTimeoutRenewal": 5, "maintenance": { "port": { "type": "maintenance" }, "readiness": "/heartbeat" } }, "versions": [ { "version": "1", "extKeyRequired": true, "oauth": true, "provision_ACL": false, "tenant_Profile": false, "urac": false, "urac_ACL": false, "urac_Config": false, "urac_GroupConfig": false, "urac_Profile": false, "apis": [ { l: "pay items", v: "/pay", m: "post", group: "Pay" }, { l: "Get all pay ", v: "/pays", m: "get", group: "Pay" } ], "documentation": {} } ], "metadata": { "tags": ["order", "ecommerce"], "program": ["marketplace"] }, "ui": { "main": "Gateway", "sub": "" }, "settings": { "acl": { "public": { "ro": true } }, "recipes": [], "environments": {} }, "src": { "provider": "github", "owner": "ht", "repo": "mkpl.order" } }; module.exports = lib;
soajs/soajs
test/data/integration/marketplace/pay.js
JavaScript
apache-2.0
1,208
!function(o){o("#word").keydown(function(){o(this).css("background-color","#fff")}),o("#search button").on({click:function(c){return""==o("#word").val()?(o("#word").focus().css("background-color","#FAEBCC"),!1):($tmp=o("#word").val(),void o("#word").val($tmp+" site:geeknav.applinzi.com"))},focusout:function(c){o("#word").val("").css("background-color","#fff")}})}(jQuery); //# sourceMappingURL=default.js.map
darkless456/Geek_Navigation
dist/js/default.js
JavaScript
apache-2.0
411
define("gallery/spin/2.0.0/spin-debug", [], function(require, exports, module) { /** * Copyright (c) 2011-2014 Felix Gnass * Licensed under the MIT license */ (function(root, factory) { /* CommonJS */ if (typeof exports == "object") module.exports = factory(); else if (typeof define == "function" && define.amd) define(factory); else root.Spinner = factory(); })(this, function() { "use strict"; var prefixes = [ "webkit", "Moz", "ms", "O" ], animations = {}, useCssAnimations; /* Whether to use CSS animations or setTimeout */ /** * Utility function to create elements. If no tag name is given, * a DIV is created. Optionally properties can be passed. */ function createEl(tag, prop) { var el = document.createElement(tag || "div"), n; for (n in prop) el[n] = prop[n]; return el; } /** * Appends children and returns the parent. */ function ins(parent) { for (var i = 1, n = arguments.length; i < n; i++) parent.appendChild(arguments[i]); return parent; } /** * Insert a new stylesheet to hold the @keyframe or VML rules. */ var sheet = function() { var el = createEl("style", { type: "text/css" }); ins(document.getElementsByTagName("head")[0], el); return el.sheet || el.styleSheet; }(); /** * Creates an opacity keyframe animation rule and returns its name. * Since most mobile Webkits have timing issues with animation-delay, * we create separate rules for each line/segment. */ function addAnimation(alpha, trail, i, lines) { var name = [ "opacity", trail, ~~(alpha * 100), i, lines ].join("-"), start = .01 + i / lines * 100, z = Math.max(1 - (1 - alpha) / trail * (100 - start), alpha), prefix = useCssAnimations.substring(0, useCssAnimations.indexOf("Animation")).toLowerCase(), pre = prefix && "-" + prefix + "-" || ""; if (!animations[name]) { sheet.insertRule("@" + pre + "keyframes " + name + "{" + "0%{opacity:" + z + "}" + start + "%{opacity:" + alpha + "}" + (start + .01) + "%{opacity:1}" + (start + trail) % 100 + "%{opacity:" + alpha + "}" + "100%{opacity:" + z + "}" + "}", sheet.cssRules.length); animations[name] = 1; } return name; } /** * Tries various vendor prefixes and returns the first supported property. */ function vendor(el, prop) { var s = el.style, pp, i; prop = prop.charAt(0).toUpperCase() + prop.slice(1); for (i = 0; i < prefixes.length; i++) { pp = prefixes[i] + prop; if (s[pp] !== undefined) return pp; } if (s[prop] !== undefined) return prop; } /** * Sets multiple style properties at once. */ function css(el, prop) { for (var n in prop) el.style[vendor(el, n) || n] = prop[n]; return el; } /** * Fills in default values. */ function merge(obj) { for (var i = 1; i < arguments.length; i++) { var def = arguments[i]; for (var n in def) if (obj[n] === undefined) obj[n] = def[n]; } return obj; } /** * Returns the absolute page-offset of the given element. */ function pos(el) { var o = { x: el.offsetLeft, y: el.offsetTop }; while (el = el.offsetParent) o.x += el.offsetLeft, o.y += el.offsetTop; return o; } /** * Returns the line color from the given string or array. */ function getColor(color, idx) { return typeof color == "string" ? color : color[idx % color.length]; } // Built-in defaults var defaults = { lines: 12, // The number of lines to draw length: 7, // The length of each line width: 5, // The line thickness radius: 10, // The radius of the inner circle rotate: 0, // Rotation offset corners: 1, // Roundness (0..1) color: "#000", // #rgb or #rrggbb direction: 1, // 1: clockwise, -1: counterclockwise speed: 1, // Rounds per second trail: 100, // Afterglow percentage opacity: 1 / 4, // Opacity of the lines fps: 20, // Frames per second when using setTimeout() zIndex: 2e9, // Use a high z-index by default className: "spinner", // CSS class to assign to the element top: "50%", // center vertically left: "50%", // center horizontally position: "absolute" }; /** The constructor */ function Spinner(o) { this.opts = merge(o || {}, Spinner.defaults, defaults); } // Global defaults that override the built-ins: Spinner.defaults = {}; merge(Spinner.prototype, { /** * Adds the spinner to the given target element. If this instance is already * spinning, it is automatically removed from its previous target b calling * stop() internally. */ spin: function(target) { this.stop(); var self = this, o = self.opts, el = self.el = css(createEl(0, { className: o.className }), { position: o.position, width: 0, zIndex: o.zIndex }), mid = o.radius + o.length + o.width; if (target) { target.insertBefore(el, target.firstChild || null); css(el, { left: o.left, top: o.top }); } el.setAttribute("role", "progressbar"); self.lines(el, self.opts); if (!useCssAnimations) { // No CSS animation support, use setTimeout() instead var i = 0, start = (o.lines - 1) * (1 - o.direction) / 2, alpha, fps = o.fps, f = fps / o.speed, ostep = (1 - o.opacity) / (f * o.trail / 100), astep = f / o.lines; (function anim() { i++; for (var j = 0; j < o.lines; j++) { alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity); self.opacity(el, j * o.direction + start, alpha, o); } self.timeout = self.el && setTimeout(anim, ~~(1e3 / fps)); })(); } return self; }, /** * Stops and removes the Spinner. */ stop: function() { var el = this.el; if (el) { clearTimeout(this.timeout); if (el.parentNode) el.parentNode.removeChild(el); this.el = undefined; } return this; }, /** * Internal method that draws the individual lines. Will be overwritten * in VML fallback mode below. */ lines: function(el, o) { var i = 0, start = (o.lines - 1) * (1 - o.direction) / 2, seg; function fill(color, shadow) { return css(createEl(), { position: "absolute", width: o.length + o.width + "px", height: o.width + "px", background: color, boxShadow: shadow, transformOrigin: "left", transform: "rotate(" + ~~(360 / o.lines * i + o.rotate) + "deg) translate(" + o.radius + "px" + ",0)", borderRadius: (o.corners * o.width >> 1) + "px" }); } for (;i < o.lines; i++) { seg = css(createEl(), { position: "absolute", top: 1 + ~(o.width / 2) + "px", transform: o.hwaccel ? "translate3d(0,0,0)" : "", opacity: o.opacity, animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + " " + 1 / o.speed + "s linear infinite" }); if (o.shadow) ins(seg, css(fill("#000", "0 0 4px " + "#000"), { top: 2 + "px" })); ins(el, ins(seg, fill(getColor(o.color, i), "0 0 1px rgba(0,0,0,.1)"))); } return el; }, /** * Internal method that adjusts the opacity of a single line. * Will be overwritten in VML fallback mode below. */ opacity: function(el, i, val) { if (i < el.childNodes.length) el.childNodes[i].style.opacity = val; } }); function initVML() { /* Utility function to create a VML tag */ function vml(tag, attr) { return createEl("<" + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr); } // No CSS transforms but VML support, add a CSS rule for VML elements: sheet.addRule(".spin-vml", "behavior:url(#default#VML)"); Spinner.prototype.lines = function(el, o) { var r = o.length + o.width, s = 2 * r; function grp() { return css(vml("group", { coordsize: s + " " + s, coordorigin: -r + " " + -r }), { width: s, height: s }); } var margin = -(o.width + o.length) * 2 + "px", g = css(grp(), { position: "absolute", top: margin, left: margin }), i; function seg(i, dx, filter) { ins(g, ins(css(grp(), { rotation: 360 / o.lines * i + "deg", left: ~~dx }), ins(css(vml("roundrect", { arcsize: o.corners }), { width: r, height: o.width, left: o.radius, top: -o.width >> 1, filter: filter }), vml("fill", { color: getColor(o.color, i), opacity: o.opacity }), vml("stroke", { opacity: 0 })))); } if (o.shadow) for (i = 1; i <= o.lines; i++) seg(i, -2, "progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)"); for (i = 1; i <= o.lines; i++) seg(i); return ins(el, g); }; Spinner.prototype.opacity = function(el, i, val, o) { var c = el.firstChild; o = o.shadow && o.lines || 0; if (c && i + o < c.childNodes.length) { c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild; if (c) c.opacity = val; } }; } var probe = css(createEl("group"), { behavior: "url(#default#VML)" }); if (!vendor(probe, "transform") && probe.adj) initVML(); else useCssAnimations = vendor(probe, "animation"); return Spinner; }); });
fuxiaoling/gulp
src/static/libs/cmd/gallery/spin/2.0.0/spin-debug.js
JavaScript
apache-2.0
12,137
/* ========================================================== * bootstrap-affix.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#affix * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* AFFIX CLASS DEFINITION * ====================== */ var Affix = function (element, options) { this.options = $.extend({}, $.fn.affix.defaults, options) this.$window = $(window) .on('scroll.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this)) this.$element = $(element) this.checkPosition() } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() , scrollTop = this.$window.scrollTop() , position = this.$element.offset() , offset = this.options.offset , offsetBottom = offset.bottom , offsetTop = offset.top , reset = 'affix affix-top affix-bottom' , affix if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && scrollTop <= offsetTop ? 'top' : false if (this.affixed === affix) return this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : '')) } /* AFFIX PLUGIN DEFINITION * ======================= */ var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('affix') , options = typeof option == 'object' && option if (!data) $this.data('affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix $.fn.affix.defaults = { offset: 0 } /* AFFIX NO CONFLICT * ================= */ $.fn.affix.noConflict = function () { $.fn.affix = old return this } /* AFFIX DATA-API * ============== */ $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) , data = $spy.data() data.offset = data.offset || {} data.offsetBottom && (data.offset.bottom = data.offsetBottom) data.offsetTop && (data.offset.top = data.offsetTop) $spy.affix(data) }) }) }(window.jQuery);
michaelcouck/ikube
code/war/src/main/webapp/assets/javascripts/bootstrap/bootstrap-affix.js
JavaScript
apache-2.0
3,485
describe('Service: angelloModel', function() { //load module for service beforeEach(module('Angello')); var modelService; beforeEach(inject(function(angelloModel) { modelService = angelloModel; })); describe('#getStatuses', function() { it('should return seven different statuses', function() { expect(modelService.getStatuses().length).toBe(7); }); it('should have a status named "To Do"', function() { expect(modelService.getStatuses().map(function(status) { // get just the name of each status return status.name; })).toContain('To Do'); }); describe('#getTypes', function() { it('should return four different types', function() { expect(modelService.getTypes().length).toBe(4); }); it('should have a type named "Bug"', function() { expect(modelService.getTypes().map(function(status) { // get just the name of each status return status.name; })). toContain('Bug'); }); }); describe('#getStories', function() { it('should return six different stories', function() { expect(modelService.getStories().length).toBe(6); }); it('should return stories that have a description property', function() { modelService.getStories().forEach(function(story) { expect(story.description).toBeDefined(); }); }); }); }); });
jimfmunro/angello
tests/angelloModelSpec.js
JavaScript
apache-2.0
1,326
// Alias to import the folder import Logo from './Logo'; export default Logo;
Angelmmiguel/discuzzion
client/src/components/Logo/index.js
JavaScript
apache-2.0
77
(function () { 'use strict'; angular.module('app.bankmaintenance').run(appRun); /* @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [ { state: 'app.listBanks', config: { url: '/listBanks', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/ListBanks.html', controller: 'ControllerListBanks as vm' } } } }, { state: 'app.addBank', config: { url: '/addBank', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/BankDetail.html', controller: 'ControllerAddBank as vm' } } } }, { state: 'app.viewBank', config: { url: '/viewBank', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/BankDetail.html', controller: 'ControllerViewBank as vm', } }, params: { rid: true }, resolve: { organizationDetails: getBankDetailsResolve } } }, { state: 'app.editBank', config: { url: '/editBank', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/profiles/BankDetail.html', controller: 'ControllerEditBank as vm', } }, params: { rid: true }, resolve: { organizationDetails: getBankDetailsResolve } } }, { state: 'app.listBanksForSelection', config: { url: '/listBanksForSelection', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/listBanksForSelection.html', controller: 'ControllerListBanksForSelection as vm' } }, params : { targetUIState: null } } }, { state: 'app.listBankUsers', config: { url: '/listBankUsers', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/listBankUsers.html', controller: 'ControllerListBankUsers as vm' } }, params : { selectedOrgId: null } } }, { state: 'app.addBankUser', config: { url: '/addBankUser', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/BankUserDetail.html', controller: 'ControllerAddBankUser as vm' } }, params : { selectedOrgId: null } } }, { state: 'app.viewBankUser', config: { url: '/viewBankUser', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/BankUserDetail.html', controller: 'ControllerViewBankUser as vm', } }, params: { rid: true }, resolve: { userDetails: getBankUserDetailsResolve } } }, { state: 'app.editBankUser', config: { url: '/editBankUser', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userprofiles/BankUserDetail.html', controller: 'ControllerEditBankUser as vm', } }, params: { rid: true }, resolve: { userDetails: getBankUserDetailsResolve } } }, { state: 'app.listBankPermissions', config: { url: '/listBankPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/permissions/listBankPermissions.html', controller: 'ControllerListBankPermissions as vm' } } } }, { state: 'app.editBankPermissions', config: { url: '/editBankPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/permissions/BankPermissionsDetail.html', controller: 'ControllerEditBankPermissions as vm', } }, params: { orgId: true }, resolve: { organizationRoles: getOrganizationRolesResolve } } }, { state: 'app.viewBankPermissions', config: { url: '/viewBankPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/permissions/BankPermissionsDetail.html', controller: 'ControllerViewBankPermissions as vm', } }, params: { orgId: true }, resolve: { organizationRoles: getOrganizationRolesResolve } } }, //BANK USER PERMISSION ROUTING { state: 'app.listBankUsersPermissions', config: { url: '/listBankUsersPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userpermissions/ListBankUsersPermissions.html', controller: 'ControllerListBankUsersPermissions as vm' } }, params : { selectedOrgId: null } } }, { state: 'app.editBankUserPermissions', config: { url: '/editBankUserPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userpermissions/BankUserPermissionsDetail.html', controller: 'ControllerEditBankUserPermissions as vm', } }, params: { userId: true }, resolve: { userRoles: getBankUserRolesResolve } } }, { state: 'app.viewBankUserPermissions', config: { url: '/viewBankUserPermissions', views: { 'mainContent': { templateUrl: 'app/modules/bankmaintenance/userpermissions/BankUserPermissionsDetail.html', controller: 'ControllerViewBankUserPermissions as vm', } }, params: { userId: true }, resolve: { userRoles: getBankUserRolesResolve } } } ]; } function getBankUserDetailsResolve(UserService, $stateParams) { 'ngInject'; return UserService.getUserDetails($stateParams.rid); } function getBankDetailsResolve(OrganizationService, $stateParams) { 'ngInject'; return OrganizationService.getOrganizationDetails($stateParams.rid); } function getOrganizationRolesResolve(OrganizationRoleService, $stateParams) { 'ngInject'; return OrganizationRoleService.getOrganizationRoles($stateParams.orgId); } function getBankUserRolesResolve(UserRoleService, $stateParams) { 'ngInject'; return UserRoleService.getUserRoles($stateParams.userId); } })();
blessonkavala/cp
cashportal/src/main/resources/static/app/modules/bankmaintenance/bankmaintenance.route.js
JavaScript
apache-2.0
9,943
var extend = require('node.extend'); var PersistentCollection = require('./persistent-collection'); var preference = require('../model/preference'); var preferences = extend(true, {}, new PersistentCollection(), function() { "use strict"; return { collectionName: 'preferences', fieldDefinition: preference }; }()); module.exports = preferences;
stamp-web/stamp-webservices
app/services/preferences.js
JavaScript
apache-2.0
376
import React from 'react' import GenericField from './genericfield' import {object_is_equal, map_drop} from 'app/utils' import PropTypes from 'prop-types' import uuid4 from 'uuid/v4' class GenericForm extends React.Component{ constructor(props){ super(props) this.state = this.getInitialState(props) this.state.form_id = uuid4() this.updateForm = _.debounce(this.updateForm, 100) } getInitialState(props){ props = props || this.props let state={}; (props.fields || []).map((f) => { if (f.name){ let v = f.value if (v == undefined){ if (f.default == undefined) v = "" else v = f.default } state[f.name]=v } }) if (props.data){ Object.keys(props.data).map( (k) => { if (k){ state[k]=props.data[k] }}) } return state } setValue(k, v){ let update = {[k]: v } this.setState( update ) let nstate=Object.assign({}, this.state, update ) // looks like react delays state change, I need it now //console.log(nstate, this.props) this.updateForm() } componentWillReceiveProps(newprops){ if (!object_is_equal(newprops.fields, this.props.fields) || !object_is_equal(newprops.data, this.props.data)){ this.setState( this.getInitialState(newprops) ) } } componentDidMount(){ let fields = {}; (this.props.fields || []).map((f) => { if (f.validation) fields[f.name]=f.validation }) $(this.refs.form).form({ on: 'blur', fields }).on('submit', function(ev){ ev.preventDefault() }) this.updateForm() } updateForm(){ if (this.props.updateForm){ const data = map_drop(this.state, ["form_id"]) this.props.updateForm(data) } } render(){ const props=this.props return ( <form ref="form" className={`ui form ${props.className || ""}`} onSubmit={(ev) => { ev.preventDefault(); props.onSubmit && props.onSubmit(ev) }}> {(props.fields || []).map((f, i) => ( <GenericField {...f} key={f.name || i} setValue={(v) => this.setValue(f.name, v)} value={this.state[f.name]} fields={props.fields} form_data={this.state} /> ))} {props.children} </form> ) } } GenericForm.propTypes = { fields: PropTypes.arrayOf( PropTypes.shape({ label: PropTypes.string, name: PropTypes.string, description: PropTypes.string, type: PropTypes.string, value: PropTypes.oneOfType([PropTypes.string, PropTypes.Boolean]), params: PropTypes.string, }).isRequired).isRequired, data: PropTypes.object, updateForm: PropTypes.func.isRequired } export default GenericForm
serverboards/serverboards
frontend/app/js/components/genericform/index.js
JavaScript
apache-2.0
2,808
'use strict'; var chai = require('chai'); var supertest = require('supertest'); var api = supertest('https://apis-bank-dev.apigee.net'); // supertest init; chai.should(); describe('/branches', function() { describe('get', function() { it('should respond with 200 OK', function(done) { this.timeout(0); api.get('/apis/v1/locations/branches') .expect(200) .end(function(err, res) { if (err) return done(err); done(); }); }); }); });
siriscac/apigee-ci-demo
tests/branches-test.js
JavaScript
apache-2.0
488
import React from 'react'; import { screen } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import '__mock__/stripesCore.mock'; import renderWithRouter from 'helpers/renderWithRouter'; import account from 'fixtures/account'; import openLoans from 'fixtures/openLoans'; import okapiCurrentUser from 'fixtures/okapiCurrentUser'; import AccountDetails from './AccountDetails'; jest.mock('../../components/Accounts/Actions/FeeFineActions', () => () => <></>); jest.unmock('@folio/stripes/components'); const history = createMemoryHistory(); const props = { history, location: history.location, match: { params: { } }, isLoading: false, resources: { feefineshistory: { records: [] }, accountActions: {}, accounts: {}, feefineactions: {}, loans: {}, user: { update: jest.fn(), }, }, mutator: { activeRecord: { update: jest.fn(), }, feefineactions: { POST: jest.fn(), }, accountActions: { GET: jest.fn(), }, user: { update: jest.fn(), } }, num: 42, user: { id: '123' }, patronGroup: { group: 'Shiny happy people' }, itemDetails: {}, stripes: { hasPerm: () => true, }, account, owedAmount: 45.67, intl: {}, okapi: { url: 'https://localhost:9130', tenant: 'diku', okapiReady: true, authFailure: [], bindings: {}, currentUser: okapiCurrentUser, }, }; const accountWithLoan = { ...account, barcode: openLoans[0].item.barcode, loanId: openLoans[0].id, }; const accountWithAnonymizedLoan = { ...account, barcode: 'b612', }; const loanResources = { ...props.resources, loans: { records: openLoans, } }; const renderAccountDetails = (extraProps = {}) => renderWithRouter( <AccountDetails {...props} {...extraProps} /> ); afterEach(() => jest.clearAllMocks()); describe('Account Details', () => { test('without loan', () => { renderAccountDetails({ account }); expect(screen.getByTestId('loan-details')).toHaveTextContent(/-$/); }); test('with loan', () => { renderAccountDetails({ account: accountWithLoan, resources: loanResources }); expect(screen.getByTestId('loan-details')).toHaveTextContent(/ui-users.details.field.loan$/); }); test('with anonymized loan', () => { renderAccountDetails({ account: accountWithAnonymizedLoan, resources: loanResources }); expect(screen.getByTestId('loan-details')).toHaveTextContent(/ui-users.details.label.loanAnonymized$/); }); });
folio-org/ui-users
src/views/AccountDetails/AccountDetails.test.js
JavaScript
apache-2.0
2,518
// this sets the background color of the master UIView (when there are no windows/tab groups on it) Titanium.UI.setBackgroundColor('#000'); Ti.API.info( "Platform: " + Titanium.Platform.name ); ///////////////////////////////////////////// // Global Variables ///////////////////////////////////////////// var site_url = 'http://www.wedvite.us/'; var idKey = ''; // This is the event_id_seq // Arbitrary Windows var arbitraryWinID = ''; var textAboutUs = ''; var textWeddingParty = ''; ///////////////////////////////////////////// // Creating All Windows ///////////////////////////////////////////// var windowLogin = Titanium.UI.createWindow({ title:'User Authentication', url:'main_windows/login.js', exitOnClose: true }); var windowHome = Titanium.UI.createWindow({ title:'Home Page', url:'main_windows/home.js' }); var windowEventInfo = Titanium.UI.createWindow({ title:'Event Info', url:'main_windows/eventInfo.js' }); var windowMap = Titanium.UI.createWindow({ title:'Map', url:'main_windows/map.js' }); var windowRsvp = Titanium.UI.createWindow({ title:'RSVP', url:'main_windows/rsvp.js' }); var windowArbitrary = Titanium.UI.createWindow({ title:'Arbitrary', url:'main_windows/arbitrary.js' }); // This window just displays a picture var windowFullPhoto = Titanium.UI.createWindow({ title:'Full PHoto', url:'main_windows/photoFullScreen.js' }); var windowPhotos = Titanium.UI.createWindow({ title:'Guests Photos', url:'main_windows/photos.js' }); var windowGiftRegistry = Titanium.UI.createWindow({ title:'Gift Registry', url:'main_windows/giftRegistry.js' }); var windowLBS = Titanium.UI.createWindow({ title:'Location Based Search', url:'main_windows/lbs.js' }); var windowLocationList = Titanium.UI.createWindow({ title:'LBS Location List', url:'main_windows/lbsLocationList.js' }); var windowLocationDetail = Titanium.UI.createWindow({ title:'LBS Location Details', url:'main_windows/lbsLocationDetails.js' }); var windowWeddingComments = Titanium.UI.createWindow({ title:'Wedding Comments', url:'main_windows/weddingComments.js' }); var windowComments = Titanium.UI.createWindow({ title:'Comment Anything Page', url:'main_windows/comments.js' }); var windowAnonymousLogin = Titanium.UI.createWindow({ title:'Anonymous Login', url:'main_windows/anonymousLogin.js' }); ///////////////////////////////////////////// // Creating App Objects ///////////////////////////////////////////// // Can only have one map view. Creating it here and passing it around var mapview = Titanium.Map.createView({ top:40, mapType: Titanium.Map.STANDARD_TYPE, animate:true, regionFit:true, userLocation:false }); // Having problems with webviews. Trying to create one and pass it around var webview = Titanium.UI.createWebView({ top:40, scalesPageToFit:false }); // Create our HTTP Client and name it "loader" //var loader = Titanium.Network.createHTTPClient(); ///////////////////////////////////////////// // Passing Variables to Each Window ///////////////////////////////////////////// // Login Window windowLogin.windowHome = windowHome; windowLogin.windowAnonymousLogin = windowAnonymousLogin; windowLogin.idkey = idKey; windowLogin.site_url = site_url; //windowLogin.loader = loader; // Home Screen Window windowHome.windowLogin = windowLogin; windowHome.windowEventInfo = windowEventInfo; windowHome.windowMap = windowMap; windowHome.mapview = mapview; windowHome.windowRsvp = windowRsvp; windowHome.idKey = idKey; windowHome.site_url = site_url; windowHome.windowArbitrary = windowArbitrary; windowHome.windowFullPhoto = windowFullPhoto; windowHome.windowPhotos = windowPhotos; windowHome.windowGiftRegistry = windowGiftRegistry; windowHome.windowLBS = windowLBS; windowHome.windowWeddingComments = windowWeddingComments; //windowHome.loader = loader; // Event Info Window windowEventInfo.windowHome = windowHome; windowEventInfo.idKey = idKey; windowEventInfo.site_url = site_url; //windowEventInfo.loader = loader; // Map Window windowMap.windowHome = windowHome; windowMap.mapview = mapview; windowMap.idKey = idKey; windowMap.site_url = site_url; //windowMap.loader = loader; // RSVP Window windowRsvp.windowHome = windowHome; windowRsvp.site_url = site_url; //windowRsvp.loader = loader; // Arbitrary Window windowArbitrary.windowHome = windowHome; windowArbitrary.site_url = site_url; //windowArbitrary.loader = loader; // Full Photo Window windowFullPhoto.windowHome = windowHome; windowFullPhoto.windowPhotos = windowPhotos; //windowFullPhoto.webview = webview; windowFullPhoto.windowComments = windowComments; // Photos windowPhotos.windowHome = windowHome; windowPhotos.windowFullPhoto = windowFullPhoto; windowPhotos.site_url = site_url; windowPhotos.idKey = idKey; //windowPhotos.loader = loader; // Gift Registry windowGiftRegistry.site_url = site_url; windowGiftRegistry.windowHome = windowHome; windowGiftRegistry.idKey = idKey; // LBS windowLBS.windowHome = windowHome; windowLBS.windowLocationList = windowLocationList; windowLBS.mapview = mapview; // LBS -> Category List windowLocationList.windowLocationDetail = windowLocationDetail; // LBS -> Category List -> Detail Page with map windowLocationDetail.windowLBS = windowLBS; // Wedding Comments windowWeddingComments.windowHome = windowHome; windowWeddingComments.idKey = idKey; windowWeddingComments.webview = webview; windowWeddingComments.site_url = site_url; // Comment Anything Page windowComments.webview = webview; windowComments.site_url = site_url; // Anonymous Login Screen windowAnonymousLogin.windowLogin = windowLogin; ///////////////////////////////////////////// // Open First Window ///////////////////////////////////////////// windowLogin.open();
sekka1/Events-App
Resources/app.js
JavaScript
apache-2.0
5,846
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require jquery.Jcrop.min //= require bootstrap //= require bootstrap-datepicker //= require jquery-fileupload/basic //= require attendances //= require courses //= require jcrop_mugshot //= require people //= require rolls //= require users //= require hogan-2.0.0 //= require typeahead //= require people_typeahead //= require underscore //= require jquery.tokeninput //= require token-input-wireup //= require_tree . function initializeDatePicker() { $('input.date_picker').datepicker({ autoclose: true, todayHighlight: true, dateFormat: 'mm/dd/yyyy' }); } $(document).ready(initializeDatePicker); $(document).on('page:change', initializeDatePicker); // whenever the bootstrap modal closes, reset it's contents $(function() { $('#myModal').on('hidden', function () { $('#myModal div.modal-body').html("<p>Loading... <i class=\"icon-refresh\"></i></p>"); $('#myModalLabel').text(''); }); }); // handle link_to remote and replace contents into data-replace id element $(function() { $(document) .data('type', 'html') .delegate('[data-remote][data-replace]', 'ajax:success', function(event, data) { var $this = $(this); $($this.data('replace')).html(data); $this.trigger('ajax:replaced'); }); });
mfrederickson/ssat
app/assets/javascripts/application.js
JavaScript
apache-2.0
1,885
var searchData= [ ['scroll',['scroll',['../select2_8js.html#a6e3896ca7181e81b7757bfcca39055ec',1,'select2.js']]], ['scrollbardimensions',['scrollBarDimensions',['../select2_8js.html#a30eb565a7710bd54761b6bfbcfd9d3fd',1,'select2.js']]], ['select',['select',['../select2_8js.html#ac07257b5178416a2fbbba7365d2703a6',1,'select2.js']]], ['select2',['Select2',['../select2_8js.html#affb4af66e7784ac044be37289c148953',1,'Select2():&#160;select2.js'],['../select2_8js.html#a30a3359bfdd9ad6a698d6fd69a38a76a',1,'select2():&#160;select2.js']]], ['self',['self',['../select2_8js.html#ab3e74e211b41d329801623ae131d2585',1,'select2.js']]], ['singleselect2',['SingleSelect2',['../select2_8js.html#ab661105ae7b811b84224646465ea5c63',1,'select2.js']]], ['sizer',['sizer',['../select2_8js.html#a9db90058e07b269a04a8990251dab3c4',1,'select2.js']]], ['sn',['sn',['../j_query_8js.html#a70ece1b3f74db2cb3cb7e4b72d59b226',1,'jQuery.js']]] ];
zwmcfarland/MSEF
doxygen documentation/search/variables_15.js
JavaScript
apache-2.0
936
/* globals define */ define(function(require, exports, module) { "use strict"; // Import famo.us dependencies var Engine = require("famous/core/Engine"); var FastClick = require("famous/inputs/FastClick"); // Create main application view var AppView = require("views/AppView"); var context = Engine.createContext(); context.setPerspective(2000); var view = new AppView(); context.add(view); });
trigger-corp/generator-famous-triggerio
app/templates/src/js/main.js
JavaScript
bsd-2-clause
437
/* global define */ define([ 'jquery', 'marionette' ], function($, Marionette) { var CountItem = Marionette.ItemView.extend({ tagName: 'tr', template: 'stats/count-item' }); var CountList = Marionette.CompositeView.extend({ template: 'stats/count-list', itemView: CountItem, itemViewContainer: 'tbody', ui: { 'statsTable': 'table', 'loader': '.loading-message' }, events: { 'click thead th': 'handleSort' }, collectionEvents: { 'sort': '_renderChildren', 'request': 'showLoader', 'reset': 'hideLoader' }, hideLoader: function() { this.ui.loader.hide(); this.ui.statsTable.show(); }, showLoader: function() { this.ui.loader.show(); this.ui.statsTable.hide(); }, handleSort: function(event) { if (!this.collection.length) return; this.applySort($(event.target).data('sort')); }, applySort: function(attr) { var dir = 'asc'; // Already sorted by the attribute, cycle direction. if (this.collection._sortAttr === attr) { dir = this.collection._sortDir === 'asc' ? 'desc' : 'asc'; } this.$('[data-sort=' + this.collection._sortAttr + ']') .removeClass(this.collection._sortDir); this.$('[data-sort=' + attr + ']').addClass(dir); // Reference for cycling. this.collection._sortAttr = attr; this.collection._sortDir = dir; // Parse function for handling the sort attributes. var parse = function(v) { return v; }; this.collection.comparator = function(m1, m2) { var v1 = parse(m1.get(attr)), v2 = parse(m2.get(attr)); if (v1 < v2) return (dir === 'asc' ? -1 : 1); if (v1 > v2) return (dir === 'asc' ? 1 : -1); return 0; }; this.collection.sort(); } }); return { CountList: CountList }; });
chop-dbhi/varify
varify/static/cilantro/js/cilantro/ui/stats.js.src.js
JavaScript
bsd-2-clause
2,255
var proj4 = require('proj4'); var transformCoordinates = function transformCoordinates(fromProjection, toProjection, coordinates) { proj4.defs([ [ 'EPSG:3006', '+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3007', '+proj=tmerc +lat_0=0 +lon_0=12 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3008', '+proj=tmerc +lat_0=0 +lon_0=13.5 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3009', '+proj=tmerc +lat_0=0 +lon_0=15 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3010', '+proj=tmerc +lat_0=0 +lon_0=16.5 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3011', '+proj=tmerc +lat_0=0 +lon_0=18 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3012', '+proj=tmerc +lat_0=0 +lon_0=14.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3013', '+proj=tmerc +lat_0=0 +lon_0=15.75 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3014', '+proj=tmerc +lat_0=0 +lon_0=17.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3015', '+proj=tmerc +lat_0=0 +lon_0=18.75 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3016', '+proj=tmerc +lat_0=0 +lon_0=20.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3017', '+proj=tmerc +lat_0=0 +lon_0=21.75 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ], [ 'EPSG:3018', '+proj=tmerc +lat_0=0 +lon_0=23.25 +k=1 +x_0=150000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' ] ]); // If the projections is the same do nothing otherwise try transform if (fromProjection === toProjection) { return coordinates; } else { try { return proj4('EPSG:' + fromProjection, 'EPSG:' + toProjection, coordinates); } catch (e) { console.error('Error: ' + e); return coordinates; } } } module.exports = transformCoordinates;
origo-map/origo-server
lib/utils/transformcoordinates.js
JavaScript
bsd-2-clause
2,452
/* */ "format cjs"; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the common/testing package. */ export { SpyLocation } from './location_mock'; export { MockLocationStrategy } from './mock_location_strategy'; //# sourceMappingURL=index.js.map
poste9/crud
deps/npm/@angular/[email protected]/testing/index.js
JavaScript
bsd-2-clause
470
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-get-value-err.case // - src/dstr-binding/error/gen-func-decl-dflt.template /*--- description: Error thrown when accessing the corresponding property of the value object (generator function declaration (default parameter)) esid: sec-generator-function-definitions-runtime-semantics-instantiatefunctionobject es6id: 14.4.12 features: [generators, destructuring-binding, default-parameters] flags: [generated] info: | GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody } [...] 2. Let F be GeneratorFunctionCreate(Normal, FormalParameters, GeneratorBody, scope, strict). [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 4. Let v be GetV(value, propertyName). 5. ReturnIfAbrupt(v). ---*/ var poisonedProperty = Object.defineProperty({}, 'poisoned', { get: function() { throw new Test262Error(); } }); function* f({ poisoned } = poisonedProperty) {} assert.throws(Test262Error, function() { f(); });
sebastienros/jint
Jint.Tests.Test262/test/language/statements/generators/dstr-dflt-obj-ptrn-id-get-value-err.js
JavaScript
bsd-2-clause
1,835
// This file was procedurally generated from the following sources: // - src/dstr-binding/ary-ptrn-elem-obj-val-undef.case // - src/dstr-binding/error/cls-expr-meth.template /*--- description: Nested object destructuring with a value of `undefined` (class expression method) esid: sec-class-definitions-runtime-semantics-evaluation es6id: 14.5.16 features: [destructuring-binding] flags: [generated] info: | ClassExpression : class BindingIdentifieropt ClassTail 1. If BindingIdentifieropt is not present, let className be undefined. 2. Else, let className be StringValue of BindingIdentifier. 3. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then i. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false. [...] 14.3.8 Runtime Semantics: DefineMethod MethodDefinition : PropertyName ( StrictFormalParameters ) { FunctionBody } [...] 6. Let closure be FunctionCreate(kind, StrictFormalParameters, FunctionBody, scope, strict). If functionPrototype was passed as a parameter then pass its value as the functionPrototype optional argument of FunctionCreate. [...] 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.6 Runtime Semantics: IteratorBindingInitialization BindingElement : BindingPattern Initializeropt 1. If iteratorRecord.[[done]] is false, then [...] e. Else i. Let v be IteratorValue(next). [...] 4. Return the result of performing BindingInitialization of BindingPattern with v and environment as the arguments. 13.3.3.5 Runtime Semantics: BindingInitialization BindingPattern : ObjectBindingPattern 1. Let valid be RequireObjectCoercible(value). 2. ReturnIfAbrupt(valid). ---*/ var C = class { method([{ x }]) {} }; var c = new C(); assert.throws(TypeError, function() { c.method([]); });
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/class/dstr-meth-ary-ptrn-elem-obj-val-undef.js
JavaScript
bsd-2-clause
2,782
function privatesquare_trips_datepicker_init(){$(".form-control").focus(function(){var c=$(this).attr("id");if(c=="arrival"){$("#x-calendar-arrival-wrapper").show();$("#x-calendar-departure-wrapper").hide()}else if(c=="departure"){$("#x-calendar-arrival-wrapper").hide();$("#x-calendar-departure-wrapper").show()}else{$("#x-calendar-arrival-wrapper").hide();$("#x-calendar-departure-wrapper").hide()}});var a=document.getElementById("x-calendar-arrival-wrapper").querySelector("x-calendar"),b=document.getElementById("x-calendar-departure-wrapper").querySelector("x-calendar"); a.addEventListener("datetap",function(c){var d=c.detail.date;c=c.detail.iso;$("#arrival").val(c);a.chosen=d;c=d.toISOString();c=c.split("T")[0];b.view=d;b.chosen=d;$("#departure").val(c)});b.addEventListener("datetap",function(c){var d=c.detail.date;c=c.detail.iso;$("#departure").val(c);b.chosen=d;if(a.chosen>d){a.view=d;a.chosen=d;c=d.toISOString();d=c.split("T")[0];$("#arrival").val(d)}})} function privatesquare_trips_select2_init(){var a=privatesquare_abs_root_url()+"api/rest/";$("#where").select2({minimumInputLength:3,ajax:{url:a,dataType:"json",data:function(b){return{method:"privatesquare.geo.geocode",q:b}},results:function(b){return{results:b.results}}}}).on("select2-opening",function(){$("#x-calendar-arrival-wrapper").hide();$("#x-calendar-departure-wrapper").hide()})} function privatesquare_trips_gather_trip_info(){var a=$("#where").val(),b=$("#arrival").val(),c=$("#departure").val(),d=$("#arrive_by").val(),e=$("#depart_by").val(),f=$("#status_id").val(),g=$("#note").val();a={woeid:a,arrival:b,departure:c,arrive_by:d,depart_by:e,status_id:f,note:g};if(trip=$("#trip"))a.id=trip.val();return a} function privatesquare_trips_add_init(){privatesquare_trips_datepicker_init();privatesquare_trips_select2_init();$("#add-trip").submit(function(){var a=$("#add-trip").attr("data-add-trip-crumb"),b=privatesquare_trips_gather_trip_info();b.crumb=a;a=$("#select2-chosen-1").html();$("#add-trip").attr("disabled","disabled");privatesquare_api_call("privatesquare.trips.addTrip",b,_privatesquare_trips_add_trip_onsuccess);privatesquare_set_status("Adding trip to "+htmlspecialchars(a));return false})} function _privatesquare_trips_add_trip_onsuccess(a){if(a.stat!="ok"){privatesquare_set_status(a.error.error,"danger");$("#add-trip").removeAttr("disabled");return false}location.href=a.trip.trip_url+"?success=1"} function privatesquare_trips_edit_init(){privatesquare_trips_datepicker_init();$("#trip-editor-show").click(function(){$("#trip-summary").hide();$("#trip-related").hide();$("#trip-editor").show();return false});$("#trip-editor-cancel").click(function(){$("#trip-editor").hide();$("#trip-summary").show();$("#trip-related").show();return false});$("#change-city").click(function(){$(this).hide();privatesquare_trips_select2_init();$("#where").select2("open");return false});$("#edit-trip").submit(function(){$("#where").select2("close"); var a=$("#edit-trip").attr("data-edit-trip-crumb"),b=privatesquare_trips_gather_trip_info();b.crumb=a;privatesquare_api_call("privatesquare.trips.editTrip",b,_privatesquare_trips_edit_trip_onsuccess);privatesquare_set_status("Updating your trip");return false});$("#delete-trip").click(function(){if(!confirm("Are you sure you want to delete this trip?"))return false;var a=$("#edit-trip").attr("data-delete-trip-crumb");a={id:$("#trip").val(),crumb:a};privatesquare_api_call("privatesquare.trips.deleteTrip", a,_privatesquare_trips_delete_trip_onsuccess);privatesquare_set_status("Deleting your trip");return false})} function _privatesquare_trips_edit_trip_onsuccess(a){if(a.stat!="ok"){privatesquare_set_status(a.error.error,"danger");return false}a=a.trip;var b=$("#short-name");b.html(a.locality.woe_name);b.attr("href",a.place_url);$("#long-name").html(a.locality.name);b=$("#trip-note");b.html()!=a.note&&b.html(a.note);b=$(".trip-status-str");b.html()!=a.status&&b.html(a.status);b=$(".trip-arrival-str");b.html()!=a.arrival_str&&b.html(a.arrival_str);b=$(".trip-departure-str");b.html()!=a.departure_str&&b.html(a.departure_str); $("#where").select2("destroy");$("#change-city").show();$("#trip-editor").hide();$("#trip-summary").show();$("#trip-related").show();privatesquare_set_status("Your trip has been updated!")}function _privatesquare_trips_delete_trip_onsuccess(a){if(a.stat!="ok"){privatesquare_set_status(a.error.error,"danger");return false}a=privatesquare_abs_root_url()+"me/trips/?deleted=1";location.href=a};function privatesquare_trips_calendars_select2_init(){var a=privatesquare_abs_root_url()+"user_trips_add_geocode.php";$("#calendar-where").select2({minimumInputLength:3,ajax:{url:a,dataType:"json",data:function(b){return{q:b}},results:function(b){return{results:b.results}}}})} function privatesquare_trips_calendars_write_init(){privatesquare_trips_calendars_select2_init();$(".form-control").focus(function(){$(this).attr("id")=="calendar-expires"?$("#x-calendar-wrapper").show():$("#x-calendar-wrapper").hide()});document.getElementById("x-calendar-wrapper").querySelector("x-calendar").addEventListener("datetap",function(a){a=a.detail.iso;$("#calendar-expires").val(a)})} function privatesquare_trips_calendars_add_init(){privatesquare_trips_calendars_write_init();$("#calendar").submit(function(){var a=$("#calendar").attr("data-calendar-crumb"),b=privatesquare_trips_calendars_gather_args();b.crumb=a;privatesquare_api_call("privatesquare.trips.calendars.addCalendar",b,_privatesquare_trips_calendars_add_onsuccess);privatesquare_set_status("Adding calendar...");return false})} function privatesquare_trips_calendars_edit_init(){privatesquare_trips_calendars_write_init();$("#calendar").submit(function(){var a=$("#calendar").attr("data-calendar-edit-crumb"),b=$(this).attr("data-calendar-id"),c=privatesquare_trips_calendars_gather_args();c.id=b;c.crumb=a;privatesquare_api_call("privatesquare.trips.calendars.editCalendar",c,_privatesquare_trips_calendars_edit_onsuccess);privatesquare_set_status("Updating your calendar...");return false});$("#calendar-delete").click(function(){if(!confirm("Are you sure want to delete this calendar? There is no UNDO."))return false; var a=$(this),b=a.attr("data-calendar-id");a=a.attr("data-calendar-delete-crumb");privatesquare_api_call("privatesquare.trips.calendars.deleteCalendar",{id:b,crumb:a},_privatesquare_trips_calendars_delete_onsuccess);privatesquare_set_status("Deleting your calendar now...");return false})} function privatesquare_trips_calendars_gather_args(){var a={},b=$("#calendar-name");a.name=b.val();b=$("#calendar-where");a.woeid=b.val();b=$("#calendar-notes");a.note=b.val();b=$("#calendar-expires");a.expires=b.val();b=$("#calendar-trip-status");a.status_id=b.val();b=$("#calendar-include-notes");a.include_notes=b.attr("checked")?1:0;b=$("#calendar-past-trips");a.past_trips=b&&b.attr("checked")?1:0;return a} function _privatesquare_trips_calendars_add_onsuccess(a){if(a.stat!="ok"){privatesquare_api_error(a);return false}a=a.calendar.id;htmlspecialchars(a);a=privatesquare_abs_root_url()+"me/trips/calendars/"+a+"?created=1";location.href=a;return false}function _privatesquare_trips_calendars_edit_onsuccess(a){if(a.stat!="ok"){privatesquare_api_error(a);return false}privatesquare_set_status("Okay! Your calendar has been updated.")} function _privatesquare_trips_calendars_delete_onsuccess(a){if(a.stat!="ok"){privatesquare_api_error(a);return false}a=privatesquare_abs_root_url()+"me/trips/calendars/?deleted=1";location.href=a};
straup/privatesquare
www/javascript/privatesquare.trips.min.js
JavaScript
bsd-2-clause
7,486
/*****************************************************************************/ /* */ /* RobotIRC 0.1.2 */ /* Copyright (c) 2013-2017, Frederic Cambus */ /* https://github.com/fcambus/robotirc */ /* */ /* Created: 2013-12-17 */ /* Last Updated: 2017-02-03 */ /* */ /* RobotIRC is released under the BSD 2-Clause license. */ /* See LICENSE file for details. */ /* */ /*****************************************************************************/ var crypto = require('crypto'); var dns = require('dns'); var net = require('net'); /**[ NPM Modules ]************************************************************/ var alexa = require('alexarank'); var irc = require('irc'); var log = require('npmlog'); var request = require('request'); /**[ RobotIRC ]***************************************************************/ module.exports = function(config) { var client = new irc.Client(config.server, config.nickname, config.options); /**[ Connection ]*********************************************************/ client.addListener('registered', function(message) { log.info("", "RobotIRC is now connected to " + config.server); }); /**[ Error handler ]******************************************************/ client.addListener('error', function(message) { log.error("", message.args.splice(1, message.args.length).join(" - ")); }); /**[ CTCP VERSION handler ]***********************************************/ client.addListener('ctcp-version', function(from, to, message) { client.ctcp(from, 'notice', "VERSION " + config.options.realName); }); /**[ Message handler ]****************************************************/ client.addListener('message', function(from, to, message) { var params = message.split(' ').slice(1).join(' '); if (to == client.nick) { // Handling private messages to = from; } /**********************************************************[ !help ]**/ if (message.match(/^!help/)) { var help = "RobotIRC 0.1.2 supports the following commands:\n" + "!alexa => Get Alexa traffic rank for a domain or URL\n" + "!date => Display server local time\n" + "!expand => Expand a shortened URL\n" + "!headers => Display HTTP headers for queried URL\n" + "!resolve => Get A records (IPv4) and AAAA records (IPv6) for queried domain\n" + "!reverse => Get reverse (PTR) records from IPv4 or IPv6 addresses\n" + "!wikipedia => Query Wikipedia for an article summary\n"; client.say(to, help); } /*********************************************************[ !alexa ]**/ if (message.match(/^!alexa/)) { alexa(params, function(error, result) { if (!error && typeof result.rank != "undefined") { client.say(to, "Alexa Traffic Rank for " + result.idn.slice(0, -1) + ": " + result.rank); } }); } /**********************************************************[ !date ]**/ if (message.match(/^!date/)) { client.say(to, Date()); } /********************************************************[ !expand ]**/ if (message.match(/^!expand/)) { request({ method: "HEAD", url: params, followAllRedirects: true }, function(error, response) { if (!error && response.statusCode == 200) { client.say(to, response.request.href); } }); } /*******************************************************[ !headers ]**/ if (message.match(/^!headers/)) { request(params, function(error, response, body) { if (!error && response.statusCode == 200) { for (var item in response.headers) { client.say(to, item + ": " + response.headers[item] + "\n"); } } }); } /*******************************************************[ !resolve ]**/ if (message.match(/^!resolve/)) { dns.resolve4(params, function(error, addresses) { if (!error) { for (var item in addresses) { client.say(to, addresses[item] + "\n"); } } dns.resolve6(params, function(error, addresses) { if (!error) { for (var item in addresses) { client.say(to, addresses[item] + "\n"); } } }); }); } /*******************************************************[ !reverse ]**/ if (message.match(/^!reverse/)) { if (net.isIP(params)) { dns.reverse(params, function(error, domains) { if (!error) { client.say(to, domains[0]); } }); } } /*****************************************************[ !wikipedia ]**/ if (message.match(/^!wikipedia/)) { params.split(' ').join('_'); dns.resolveTxt(params + ".wp.dg.cx", function(error, txt) { if (!error) { client.say(to, txt[0]); } }); } }); };
fcambus/robotirc
lib/robotirc.js
JavaScript
bsd-2-clause
6,242
'use strict' class ScheduleEvents { constructor (aws) { // Authenticated `aws` object in `lib/main.js` this.lambda = new aws.Lambda({ apiVersion: '2015-03-31' }) this.cloudwatchevents = new aws.CloudWatchEvents({ apiVersion: '2015-10-07' }) } _ruleDescription (params) { if ('ScheduleDescription' in params && params.ScheduleDescription != null) { return `${params.ScheduleDescription}` } return `${params.ScheduleName} - ${params.ScheduleExpression}` } _functionName (params) { return params.FunctionArn.split(':').pop() } _putRulePrams (params) { return { Name: params.ScheduleName, Description: this._ruleDescription(params), State: params.ScheduleState, ScheduleExpression: params.ScheduleExpression } } _putRule (params) { // return RuleArn if created return new Promise((resolve, reject) => { const _params = this._putRulePrams(params) this.cloudwatchevents.putRule(_params, (err, rule) => { if (err) reject(err) resolve(rule) }) }) } _addPermissionParams (params) { return { Action: 'lambda:InvokeFunction', FunctionName: this._functionName(params), Principal: 'events.amazonaws.com', SourceArn: params.RuleArn, StatementId: params.ScheduleName } } _addPermission (params) { return new Promise((resolve, reject) => { const _params = this._addPermissionParams(params) this.lambda.addPermission(_params, (err, data) => { if (err) { if (err.code !== 'ResourceConflictException') reject(err) // If it exists it will result in an error but there is no problem. resolve('Permission already set') } resolve(data) }) }) } _putTargetsParams (params) { return { Rule: params.ScheduleName, Targets: [{ Arn: params.FunctionArn, Id: this._functionName(params), Input: params.hasOwnProperty('Input') ? JSON.stringify(params.Input) : '' }] } } _putTargets (params) { return new Promise((resolve, reject) => { const _params = this._putTargetsParams(params) this.cloudwatchevents.putTargets(_params, (err, data) => { // even if it is already registered, it will not be an error. if (err) reject(err) resolve(data) }) }) } add (params) { return Promise.resolve().then(() => { return this._putRule(params) }).then(rule => { return this._addPermission(Object.assign(params, rule)) }).then(data => { return this._putTargets(params) }) } } module.exports = ScheduleEvents
teebu/node-lambda
lib/schedule_events.js
JavaScript
bsd-2-clause
2,692
var middleware = require('../../middleware') ; function handler (req, res, next) { var profile = { }; res.send(200, res.profile); next( ); return; } var endpoint = { path: '/users/:user/create' , method: 'get' , handler: handler }; module.exports = function configure (opts, server) { function mount (server) { server.get(endpoint.path, endpoint.middleware, updateUser, endpoint.handler); } var userInfo = middleware.minUser(opts, server); var mandatory = middleware.mandatory(opts, server); endpoint.middleware = mandatory.concat(userInfo); function updateUser (req, res, next) { var profile = { }; var name = req.params.user; var update = req.params; server.updateUser(name, update, {save:false, create:true}, function (result) { server.log.debug('UPDATED user', arguments); res.profile = result; next( ); }); } endpoint.mount = mount; return endpoint; }; module.exports.endpoint = endpoint;
bewest/restify-git-json
lib/handlers/users/create.js
JavaScript
bsd-2-clause
976
if(!org) var org={}; if(!org.judison) org.judison={}; if(!org.judison.bmsp) org.judison.bmsp={}; with(org.judison.bmsp){ init = function(){ document.getElementById("bookmarks-view").place = "place:queryType=1&folder=" + window.top.PlacesUtils.bookmarksMenuFolderId; } }
judison/bmsp
src/content/overlay.js
JavaScript
bsd-2-clause
290
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; console.log(process.env.NODE_ENV); ReactDOM.render(<App />, document.getElementById('root'));
freoff/zlecenia
src/index.js
JavaScript
bsd-2-clause
204
(function() { 'use strict' function queryLink() { return { restrict: 'E', scope: { 'query': '=', 'visualization': '=?' }, template: '<a ng-href="{{link}}" class="query-link">{{query.displayname}}</a>', link: function(scope, element) { var hash = null; if (scope.visualization) { if (scope.visualization.type === 'TABLE') { // link to hard-coded table tab instead of the (hidden) visualization tab hash = 'table'; } else { hash = scope.visualization.id; } } scope.link = scope.query.getUrl(false, hash); } } } function querySourceLink($location) { return { restrict: 'E', template: '<span ng-show="query.id && canViewSource">\ <a ng-show="!sourceMode"\ ng-href="{{query.getUrl(true, selectedTab)}}" class="btn btn-default">Show Source\ </a>\ <a ng-show="sourceMode"\ ng-href="{{query.getUrl(false, selectedTab)}}" class="btn btn-default">Hide Source\ </a>\ </span>' } } function queryResultLink() { return { restrict: 'A', link: function (scope, element, attrs) { var fileType = attrs.fileType ? attrs.fileType : "csv"; scope.$watch('queryResult && queryResult.getData()', function(data) { if (!data) { return; } if (scope.queryResult.getId() == null) { element.attr('href', ''); } else { element.attr('href', 'api/queries/' + scope.query.id + '/results/' + scope.queryResult.getId() + '.' + fileType); element.attr('download', scope.query.name.replace(" ", "_") + moment(scope.queryResult.getUpdatedAt()).format("_YYYY_MM_DD") + "." + fileType); } }); } } } // By default Ace will try to load snippet files for the different modes and fail. We don't need them, so we use these // placeholders until we define our own. function defineDummySnippets(mode) { ace.define("ace/snippets/" + mode, ["require", "exports", "module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = mode; }); }; defineDummySnippets("python"); defineDummySnippets("sql"); defineDummySnippets("json"); function queryEditor(QuerySnippet) { return { restrict: 'E', scope: { 'query': '=', 'lock': '=', 'schema': '=', 'syntax': '=' }, template: '<div ui-ace="editorOptions" ng-model="query.query"></div>', link: { pre: function ($scope, element) { $scope.syntax = $scope.syntax || 'sql'; $scope.editorOptions = { mode: 'json', require: ['ace/ext/language_tools'], advanced: { behavioursEnabled: true, enableSnippets: true, enableBasicAutocompletion: true, enableLiveAutocompletion: true, autoScrollEditorIntoView: true, }, onLoad: function(editor) { QuerySnippet.query(function(snippets) { var snippetManager = ace.require("ace/snippets").snippetManager; var m = { snippetText: '' }; m.snippets = snippetManager.parseSnippetFile(m.snippetText); _.each(snippets, function(snippet) { m.snippets.push(snippet.getSnippet()); }); snippetManager.register(m.snippets || [], m.scope); }); editor.$blockScrolling = Infinity; editor.getSession().setUseWrapMode(true); editor.setShowPrintMargin(false); $scope.$watch('syntax', function(syntax) { var newMode = 'ace/mode/' + syntax; editor.getSession().setMode(newMode); }); $scope.$watch('schema', function(newSchema, oldSchema) { if (newSchema !== oldSchema) { var tokensCount = _.reduce(newSchema, function(totalLength, table) { return totalLength + table.columns.length }, 0); // If there are too many tokens we disable live autocomplete, as it makes typing slower. if (tokensCount > 5000) { editor.setOption('enableLiveAutocompletion', false); } else { editor.setOption('enableLiveAutocompletion', true); } } }); $scope.$parent.$on("angular-resizable.resizing", function (event, args) { editor.resize(); }); editor.focus(); } }; var langTools = ace.require("ace/ext/language_tools"); var schemaCompleter = { getCompletions: function(state, session, pos, prefix, callback) { if (prefix.length === 0 || !$scope.schema) { callback(null, []); return; } if (!$scope.schema.keywords) { var keywords = {}; _.each($scope.schema, function (table) { keywords[table.name] = 'Table'; _.each(table.columns, function (c) { keywords[c] = 'Column'; keywords[table.name + "." + c] = 'Column'; }); }); $scope.schema.keywords = _.map(keywords, function(v, k) { return { name: k, value: k, score: 0, meta: v }; }); } callback(null, $scope.schema.keywords); } }; langTools.addCompleter(schemaCompleter); } } }; } function queryFormatter($http, growl) { return { restrict: 'E', // don't create new scope to avoid ui-codemirror bug // seehttps://github.com/angular-ui/ui-codemirror/pull/37 scope: false, template: '<button type="button" class="btn btn-default btn-s"\ ng-click="formatQuery()">\ <span class="zmdi zmdi-format-indent-increase"></span>\ Format Query\ </button>', link: function($scope) { $scope.formatQuery = function formatQuery() { if ($scope.dataSource.syntax == 'json') { try { $scope.query.query = JSON.stringify(JSON.parse($scope.query.query), ' ', 4); } catch(err) { growl.addErrorMessage(err); } } else if ($scope.dataSource.syntax =='sql') { $scope.queryFormatting = true; $http.post('api/queries/format', { 'query': $scope.query.query }).success(function (response) { $scope.query.query = response; }).finally(function () { $scope.queryFormatting = false; }); } else { growl.addInfoMessage("Query formatting is not supported for your data source syntax."); } }; } } } function schemaBrowser() { return { restrict: 'E', scope: { schema: '=' }, templateUrl: '/views/directives/schema_browser.html', link: function ($scope) { $scope.showTable = function(table) { table.collapsed = !table.collapsed; $scope.$broadcast('vsRepeatTrigger'); } $scope.getSize = function(table) { var size = 18; if (!table.collapsed) { size += 18 * table.columns.length; } return size; } } } } function queryTimePicker() { return { restrict: 'E', template: '<select ng-disabled="refreshType != \'daily\'" ng-model="hour" ng-change="updateSchedule()" ng-options="c as c for c in hourOptions"></select> :\ <select ng-disabled="refreshType != \'daily\'" ng-model="minute" ng-change="updateSchedule()" ng-options="c as c for c in minuteOptions"></select>', link: function($scope) { var padWithZeros = function(size, v) { v = String(v); if (v.length < size) { v = "0" + v; } return v; }; $scope.hourOptions = _.map(_.range(0, 24), _.partial(padWithZeros, 2)); $scope.minuteOptions = _.map(_.range(0, 60, 5), _.partial(padWithZeros, 2)); if ($scope.query.hasDailySchedule()) { var parts = $scope.query.scheduleInLocalTime().split(':'); $scope.minute = parts[1]; $scope.hour = parts[0]; } else { $scope.minute = "15"; $scope.hour = "00"; } $scope.updateSchedule = function() { var newSchedule = moment().hour($scope.hour).minute($scope.minute).utc().format('HH:mm'); if (newSchedule != $scope.query.schedule) { $scope.query.schedule = newSchedule; $scope.saveQuery(); } }; $scope.$watch('refreshType', function() { if ($scope.refreshType == 'daily') { $scope.updateSchedule(); } }); } } } function queryRefreshSelect() { return { restrict: 'E', template: '<select\ ng-disabled="refreshType != \'periodic\'"\ ng-model="query.schedule"\ ng-change="saveQuery()"\ ng-options="c.value as c.name for c in refreshOptions">\ <option value="">No Refresh</option>\ </select>', link: function($scope) { $scope.refreshOptions = [ { value: "60", name: '每分钟' } ]; _.each([5, 10, 15, 30], function(i) { $scope.refreshOptions.push({ value: String(i*60), name: "每" + i + "分钟" }) }); _.each(_.range(1, 13), function (i) { $scope.refreshOptions.push({ value: String(i * 3600), name: '每' + i + '小时' }); }) $scope.refreshOptions.push({ value: String(24 * 3600), name: '每24小时' }); $scope.refreshOptions.push({ value: String(7 * 24 * 3600), name: '每7天' }); $scope.refreshOptions.push({ value: String(14 * 24 * 3600), name: '每14天' }); $scope.refreshOptions.push({ value: String(30 * 24 * 3600), name: '每30天' }); $scope.$watch('refreshType', function() { if ($scope.refreshType == 'periodic') { if ($scope.query.hasDailySchedule()) { $scope.query.schedule = null; $scope.saveQuery(); } } }); } } } angular.module('redash.directives') .directive('queryLink', queryLink) .directive('querySourceLink', ['$location', querySourceLink]) .directive('queryResultLink', queryResultLink) .directive('queryEditor', ['QuerySnippet', queryEditor]) .directive('queryRefreshSelect', queryRefreshSelect) .directive('queryTimePicker', queryTimePicker) .directive('schemaBrowser', schemaBrowser) .directive('queryFormatter', ['$http', 'growl', queryFormatter]); })();
guaguadev/redash
rd_ui/app/scripts/directives/query_directives.js
JavaScript
bsd-2-clause
11,659
// ## twig.functions.js // // This file handles parsing filters. module.exports = function (Twig) { /** * @constant * @type {string} */ var TEMPLATE_NOT_FOUND_MESSAGE = 'Template "{name}" is not defined.'; // Determine object type function is(type, obj) { var clas = Object.prototype.toString.call(obj).slice(8, -1); return obj !== undefined && obj !== null && clas === type; } Twig.functions = { // attribute, block, constant, date, dump, parent, random,. // Range function from http://phpjs.org/functions/range:499 // Used under an MIT License range: function (low, high, step) { // http://kevin.vanzonneveld.net // + original by: Waldo Malqui Silva // * example 1: range ( 0, 12 ); // * returns 1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] // * example 2: range( 0, 100, 10 ); // * returns 2: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] // * example 3: range( 'a', 'i' ); // * returns 3: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] // * example 4: range( 'c', 'a' ); // * returns 4: ['c', 'b', 'a'] var matrix = []; var inival, endval, plus; var walker = step || 1; var chars = false; if (!isNaN(low) && !isNaN(high)) { inival = parseInt(low, 10); endval = parseInt(high, 10); } else if (isNaN(low) && isNaN(high)) { chars = true; inival = low.charCodeAt(0); endval = high.charCodeAt(0); } else { inival = (isNaN(low) ? 0 : low); endval = (isNaN(high) ? 0 : high); } plus = ((inival > endval) ? false : true); if (plus) { while (inival <= endval) { matrix.push(((chars) ? String.fromCharCode(inival) : inival)); inival += walker; } } else { while (inival >= endval) { matrix.push(((chars) ? String.fromCharCode(inival) : inival)); inival -= walker; } } return matrix; }, cycle: function(arr, i) { var pos = i % arr.length; return arr[pos]; }, dump: function() { var EOL = '\n', indentChar = ' ', indentTimes = 0, out = '', args = Array.prototype.slice.call(arguments), indent = function(times) { var ind = ''; while (times > 0) { times--; ind += indentChar; } return ind; }, displayVar = function(variable) { out += indent(indentTimes); if (typeof(variable) === 'object') { dumpVar(variable); } else if (typeof(variable) === 'function') { out += 'function()' + EOL; } else if (typeof(variable) === 'string') { out += 'string(' + variable.length + ') "' + variable + '"' + EOL; } else if (typeof(variable) === 'number') { out += 'number(' + variable + ')' + EOL; } else if (typeof(variable) === 'boolean') { out += 'bool(' + variable + ')' + EOL; } }, dumpVar = function(variable) { var i; if (variable === null) { out += 'NULL' + EOL; } else if (variable === undefined) { out += 'undefined' + EOL; } else if (typeof variable === 'object') { out += indent(indentTimes) + typeof(variable); indentTimes++; out += '(' + (function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) { size++; } } return size; })(variable) + ') {' + EOL; for (i in variable) { out += indent(indentTimes) + '[' + i + ']=> ' + EOL; displayVar(variable[i]); } indentTimes--; out += indent(indentTimes) + '}' + EOL; } else { displayVar(variable); } }; // handle no argument case by dumping the entire render context if (args.length == 0) args.push(this.context); Twig.forEach(args, function(variable) { dumpVar(variable); }); return out; }, date: function(date, time) { var dateObj; if (date === undefined) { dateObj = new Date(); } else if (Twig.lib.is("Date", date)) { dateObj = date; } else if (Twig.lib.is("String", date)) { if (date.match(/^[0-9]+$/)) { dateObj = new Date(date * 1000); } else { dateObj = new Date(Twig.lib.strtotime(date) * 1000); } } else if (Twig.lib.is("Number", date)) { // timestamp dateObj = new Date(date * 1000); } else { throw new Twig.Error("Unable to parse date " + date); } return dateObj; }, block: function(block) { if (this.originalBlockTokens[block]) { return Twig.logic.parse.apply(this, [this.originalBlockTokens[block], this.context]).output; } else { return this.blocks[block]; } }, parent: function() { // Add a placeholder return Twig.placeholders.parent; }, attribute: function(object, method, params) { if (Twig.lib.is('Object', object)) { if (object.hasOwnProperty(method)) { if (typeof object[method] === "function") { return object[method].apply(undefined, params); } else { return object[method]; } } } // Array will return element 0-index return object[method] || undefined; }, max: function(values) { if(Twig.lib.is("Object", values)) { delete values["_keys"]; return Twig.lib.max(values); } return Twig.lib.max.apply(null, arguments); }, min: function(values) { if(Twig.lib.is("Object", values)) { delete values["_keys"]; return Twig.lib.min(values); } return Twig.lib.min.apply(null, arguments); }, template_from_string: function(template) { if (template === undefined) { template = ''; } return Twig.Templates.parsers.twig({ options: this.options, data: template }); }, random: function(value) { var LIMIT_INT31 = 0x80000000; function getRandomNumber(n) { var random = Math.floor(Math.random() * LIMIT_INT31); var limits = [0, n]; var min = Math.min.apply(null, limits), max = Math.max.apply(null, limits); return min + Math.floor((max - min + 1) * random / LIMIT_INT31); } if(Twig.lib.is("Number", value)) { return getRandomNumber(value); } if(Twig.lib.is("String", value)) { return value.charAt(getRandomNumber(value.length-1)); } if(Twig.lib.is("Array", value)) { return value[getRandomNumber(value.length-1)]; } if(Twig.lib.is("Object", value)) { var keys = Object.keys(value); return value[keys[getRandomNumber(keys.length-1)]]; } return getRandomNumber(LIMIT_INT31-1); }, /** * Returns the content of a template without rendering it * @param {string} name * @param {boolean} [ignore_missing=false] * @returns {string} */ source: function(name, ignore_missing) { var templateSource; var templateFound = false; var isNodeEnvironment = typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof window === 'undefined'; var loader; var path; //if we are running in a node.js environment, set the loader to 'fs' and ensure the // path is relative to the CWD of the running script //else, set the loader to 'ajax' and set the path to the value of name if (isNodeEnvironment) { loader = 'fs'; path = __dirname + '/' + name; } else { loader = 'ajax'; path = name; } //build the params object var params = { id: name, path: path, method: loader, parser: 'source', async: false, fetchTemplateSource: true }; //default ignore_missing to false if (typeof ignore_missing === 'undefined') { ignore_missing = false; } //try to load the remote template // //on exception, log it try { templateSource = Twig.Templates.loadRemote(name, params); //if the template is undefined or null, set the template to an empty string and do NOT flip the // boolean indicating we found the template // //else, all is good! flip the boolean indicating we found the template if (typeof templateSource === 'undefined' || templateSource === null) { templateSource = ''; } else { templateFound = true; } } catch (e) { Twig.log.debug('Twig.functions.source: ', 'Problem loading template ', e); } //if the template was NOT found AND we are not ignoring missing templates, return the same message // that is returned by the PHP implementation of the twig source() function // //else, return the template source if (!templateFound && !ignore_missing) { return TEMPLATE_NOT_FOUND_MESSAGE.replace('{name}', name); } else { return templateSource; } } }; Twig._function = function(_function, value, params) { if (!Twig.functions[_function]) { throw "Unable to find function " + _function; } return Twig.functions[_function](value, params); }; Twig._function.extend = function(_function, definition) { Twig.functions[_function] = definition; }; return Twig; };
dave-irvine/twig.js
src/twig.functions.js
JavaScript
bsd-2-clause
11,876
define( ['helper/english', 'vendor/underscore'], function(englishHelper, _){ var persons, irregularVerbs; /** * @type {Array} */ persons = ['s1', 's2', 's3', 'p1', 'p2', 'p3']; irregularVerbs = { be: { present: ['am', 'are', 'is', 'are', 'are', 'are'], past: ['was', 'were', 'was', 'were', 'were', 'were'] }, have: { present: 'has', past: 'had' } }; /** * * @param {String} verb * @param {String} person * @return {Object} */ function irregularPresent(verb, person) { var result = false, personIndex; if (typeof irregularVerbs[verb] != 'undefined' && typeof irregularVerbs[verb].present != 'undefined') { result = irregularVerbs[verb].present; if (_.isArray(result)) { personIndex = persons.indexOf(person); return {result: result[personIndex], personalize: false}; } if ('s3' == person) { return {result: result, personalize: false}; } } return {result: verb, personalize: true}; } /** * * @param {String} defaultForm present tense, plural, 3rd person * @param {String} person to use, one of s1-s3, p1-p3 * @return {String} */ function personalize(defaultForm, person){ var shortenedVerb; switch (person) { case 's3': shortenedVerb = defaultForm.substr(0, defaultForm.length - 1); if (englishHelper.checkConsonantEnding(shortenedVerb)) { if (defaultForm[defaultForm.length-1] == 'y') { return shortenedVerb + 'ies'; } else if (defaultForm[defaultForm.length-1] == 'o') { return defaultForm + 'es'; } } return defaultForm + 's'; default: return defaultForm; } } /** * * @param {String} defaultForm present tense, plural, 3rd person * @param {String} person to use, one of s1-s3, p1-p3 * @return {*} */ function present(defaultForm, person){ var irregularResult, personIndex; personIndex = persons.indexOf(person); if (personIndex == -1) { throw 'Given person is not allowed'; } irregularResult = irregularPresent(defaultForm, person); if (irregularResult.personalize) { return personalize(irregularResult.result, person); } return irregularResult.result; } return { present: present }; } );
peteraba/deutschodoro
app/library/english/verb.js
JavaScript
bsd-2-clause
3,037
var Tag = require('./tag'); var ScriptTag = require('./script-tag'); var Utils = require('./../utils'); /** * Script tag class that is loaded in a synchronous way. * * This is the class that will generate script tags that will be appended to the * page using the document.write method. * * @param string The tag data. * @param TagLoader The loader instance that has instantiated the tag. * * @return void */ class SynchronousScriptTag extends ScriptTag { constructor(data = {}, loader_instance) { super(data, loader_instance); this.data = Utils.mergeObject(this.data, { attributes: { async: false, defer: false } }, false); this.data = Utils.mergeObject(this.data, data); if (this.data !== data) { this.data = Utils.getSanitizedObject(this.data, Tag.properties); } } /** * Returns the script node that will be appended to the DOM. * * @return HTMLElement */ getDomNode() { var s, data; if (!this.data.src) { return false; } if (Utils.isDomReady() === true) { data = Utils.mergeObject({}, this.data, false); data.type = 'script'; this.loader_instance.addToQueue([data]); return false; } s = this.getScriptNode(false); s.text = this.getDomNodeSource(s); return s; } /** * Returns the JS code that will insert the script source using * document.write. * * @return string */ getDomNodeSource(s) { var text; text = 'document.write(\'<script src="' + this.data.src + '"'; text += ' id="' + this.data.id + '"'; if (s.addEventListener) { text += ' onload="' + this.getOnTagLoadPageCode() + '"'; } else { text += ' onreadystatechange="' + this.getIeOnLoadFunction() + '"'; } text += '></scr' + 'ipt>\');'; return text; } /** * Returns function that will be called only on older IE versions when the * tag has been loaded by the browser. * * @return string */ getIeOnLoadFunction() { var text = ''; text += 'if (this.addEventListener || '; text += 'this.amc_load || '; text += '(this.readyState && '; text += 'this.readyState !== \\\'complete\\\')'; text += ') { return; } '; text += 'this.amc_load = true; '; text += this.getOnTagLoadPageCode(); return text; } } module.exports = SynchronousScriptTag;
dompuiu/personal-tag-manager-enhanced-js-library
src/engine/tags/synchronous-script-tag.js
JavaScript
bsd-3-clause
2,396
/* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dijit.Editor"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dijit.Editor"] = true; dojo.provide("dijit.Editor"); dojo.require("dijit._editor.RichText"); dojo.require("dijit.Toolbar"); dojo.require("dijit.ToolbarSeparator"); dojo.require("dijit._editor._Plugin"); dojo.require("dijit._editor.plugins.EnterKeyHandling"); dojo.require("dijit._editor.range"); dojo.require("dijit._Container"); dojo.require("dojo.i18n"); dojo.require("dijit.layout._LayoutWidget"); dojo.require("dijit._editor.range"); dojo.requireLocalization("dijit._editor", "commands", null, "ROOT,ar,ca,cs,da,de,el,es,fi,fr,he,hu,it,ja,kk,ko,nb,nl,pl,pt,pt-pt,ro,ru,sk,sl,sv,th,tr,zh,zh-tw"); dojo.declare( "dijit.Editor", dijit._editor.RichText, { // summary: // A rich text Editing widget // // description: // This widget provides basic WYSIWYG editing features, based on the browser's // underlying rich text editing capability, accompanied by a toolbar (`dijit.Toolbar`). // A plugin model is available to extend the editor's capabilities as well as the // the options available in the toolbar. Content generation may vary across // browsers, and clipboard operations may have different results, to name // a few limitations. Note: this widget should not be used with the HTML // &lt;TEXTAREA&gt; tag -- see dijit._editor.RichText for details. // plugins: Object[] // A list of plugin names (as strings) or instances (as objects) // for this widget. // // When declared in markup, it might look like: // | plugins="['bold',{name:'dijit._editor.plugins.FontChoice', command:'fontName', generic:true}]" plugins: null, // extraPlugins: Object[] // A list of extra plugin names which will be appended to plugins array extraPlugins: null, constructor: function(){ // summary: // Runs on widget initialization to setup arrays etc. // tags: // private if(!dojo.isArray(this.plugins)){ this.plugins=["undo","redo","|","cut","copy","paste","|","bold","italic","underline","strikethrough","|", "insertOrderedList","insertUnorderedList","indent","outdent","|","justifyLeft","justifyRight","justifyCenter","justifyFull", "dijit._editor.plugins.EnterKeyHandling" /*, "createLink"*/]; } this._plugins=[]; this._editInterval = this.editActionInterval * 1000; //IE will always lose focus when other element gets focus, while for FF and safari, //when no iframe is used, focus will be lost whenever another element gets focus. //For IE, we can connect to onBeforeDeactivate, which will be called right before //the focus is lost, so we can obtain the selected range. For other browsers, //no equivelent of onBeforeDeactivate, so we need to do two things to make sure //selection is properly saved before focus is lost: 1) when user clicks another //element in the page, in which case we listen to mousedown on the entire page and //see whether user clicks out of a focus editor, if so, save selection (focus will //only lost after onmousedown event is fired, so we can obtain correct caret pos.) //2) when user tabs away from the editor, which is handled in onKeyDown below. if(dojo.isIE){ this.events.push("onBeforeDeactivate"); this.events.push("onBeforeActivate"); } }, postMixInProperties: function() { // summary: // Extension to make sure a deferred is in place before certain functions // execute, like making sure all the plugins are properly inserted. // Set up a deferred so that the value isn't applied to the editor // until all the plugins load, needed to avoid timing condition // reported in #10537. this.setValueDeferred = new dojo.Deferred(); this.inherited(arguments); }, postCreate: function(){ //for custom undo/redo, if enabled. this._steps=this._steps.slice(0); this._undoedSteps=this._undoedSteps.slice(0); if(dojo.isArray(this.extraPlugins)){ this.plugins=this.plugins.concat(this.extraPlugins); } this.inherited(arguments); this.commands = dojo.i18n.getLocalization("dijit._editor", "commands", this.lang); if(!this.toolbar){ // if we haven't been assigned a toolbar, create one this.toolbar = new dijit.Toolbar({ dir: this.dir, lang: this.lang }); this.header.appendChild(this.toolbar.domNode); } dojo.forEach(this.plugins, this.addPlugin, this); // Okay, denote the value can now be set. this.setValueDeferred.callback(true); dojo.addClass(this.iframe.parentNode, "dijitEditorIFrameContainer"); dojo.addClass(this.iframe, "dijitEditorIFrame"); dojo.attr(this.iframe, "allowTransparency", true); if(dojo.isWebKit){ // Disable selecting the entire editor by inadvertant double-clicks. // on buttons, title bar, etc. Otherwise clicking too fast on // a button such as undo/redo selects the entire editor. dojo.style(this.domNode, "KhtmlUserSelect", "none"); } this.toolbar.startup(); this.onNormalizedDisplayChanged(); //update toolbar button status }, destroy: function(){ dojo.forEach(this._plugins, function(p){ if(p && p.destroy){ p.destroy(); } }); this._plugins=[]; this.toolbar.destroyRecursive(); delete this.toolbar; this.inherited(arguments); }, addPlugin: function(/*String||Object*/plugin, /*Integer?*/index){ // summary: // takes a plugin name as a string or a plugin instance and // adds it to the toolbar and associates it with this editor // instance. The resulting plugin is added to the Editor's // plugins array. If index is passed, it's placed in the plugins // array at that index. No big magic, but a nice helper for // passing in plugin names via markup. // // plugin: String, args object or plugin instance // // args: // This object will be passed to the plugin constructor // // index: Integer // Used when creating an instance from // something already in this.plugins. Ensures that the new // instance is assigned to this.plugins at that index. var args=dojo.isString(plugin)?{name:plugin}:plugin; if(!args.setEditor){ var o={"args":args,"plugin":null,"editor":this}; dojo.publish(dijit._scopeName + ".Editor.getPlugin",[o]); if(!o.plugin){ var pc = dojo.getObject(args.name); if(pc){ o.plugin=new pc(args); } } if(!o.plugin){ console.warn('Cannot find plugin',plugin); return; } plugin=o.plugin; } if(arguments.length > 1){ this._plugins[index] = plugin; }else{ this._plugins.push(plugin); } plugin.setEditor(this); if(dojo.isFunction(plugin.setToolbar)){ plugin.setToolbar(this.toolbar); } }, //the following 3 functions are required to make the editor play nice under a layout widget, see #4070 startup: function(){ // summary: // Exists to make Editor work as a child of a layout widget. // Developers don't need to call this method. // tags: // protected //console.log('startup',arguments); }, resize: function(size){ // summary: // Resize the editor to the specified size, see `dijit.layout._LayoutWidget.resize` if(size){ // we've been given a height/width for the entire editor (toolbar + contents), calls layout() // to split the allocated size between the toolbar and the contents dijit.layout._LayoutWidget.prototype.resize.apply(this, arguments); } /* else{ // do nothing, the editor is already laid out correctly. The user has probably specified // the height parameter, which was used to set a size on the iframe } */ }, layout: function(){ // summary: // Called from `dijit.layout._LayoutWidget.resize`. This shouldn't be called directly // tags: // protected // Converts the iframe (or rather the <div> surrounding it) to take all the available space // except what's needed for the header (toolbars) and footer (breadcrumbs, etc). // A class was added to the iframe container and some themes style it, so we have to // calc off the added margins and padding too. See tracker: #10662 var areaHeight = (this._contentBox.h - (this.getHeaderHeight() + this.getFooterHeight() + dojo._getPadBorderExtents(this.iframe.parentNode).h + dojo._getMarginExtents(this.iframe.parentNode).h)); this.editingArea.style.height = areaHeight + "px"; if(this.iframe){ this.iframe.style.height="100%"; } this._layoutMode = true; }, _onIEMouseDown: function(/*Event*/ e){ // summary: // IE only to prevent 2 clicks to focus // tags: // private var outsideClientArea; // IE 8's componentFromPoint is broken, which is a shame since it // was smaller code, but oh well. We have to do this brute force // to detect if the click was scroller or not. var b = this.document.body; var clientWidth = b.clientWidth; var clientHeight = b.clientHeight; var clientLeft = b.clientLeft; var offsetWidth = b.offsetWidth; var offsetHeight = b.offsetHeight; var offsetLeft = b.offsetLeft; //Check for vertical scroller click. bodyDir = b.dir?b.dir.toLowerCase():"" if(bodyDir != "rtl"){ if(clientWidth < offsetWidth && e.x > clientWidth && e.x < offsetWidth){ // Check the click was between width and offset width, if so, scroller outsideClientArea = true; } }else{ // RTL mode, we have to go by the left offsets. if(e.x < clientLeft && e.x > offsetLeft){ // Check the click was between width and offset width, if so, scroller outsideClientArea = true; } } if(!outsideClientArea){ // Okay, might be horiz scroller, check that. if(clientHeight < offsetHeight && e.y > clientHeight && e.y < offsetHeight){ // Horizontal scroller. outsideClientArea = true; } } if(!outsideClientArea){ delete this._cursorToStart; // Remove the force to cursor to start position. delete this._savedSelection; // new mouse position overrides old selection if(e.target.tagName == "BODY"){ setTimeout(dojo.hitch(this, "placeCursorAtEnd"), 0); } this.inherited(arguments); } }, onBeforeActivate: function(e){ this._restoreSelection(); }, onBeforeDeactivate: function(e){ // summary: // Called on IE right before focus is lost. Saves the selected range. // tags: // private if(this.customUndo){ this.endEditing(true); } //in IE, the selection will be lost when other elements get focus, //let's save focus before the editor is deactivated if(e.target.tagName != "BODY"){ this._saveSelection(); } //console.log('onBeforeDeactivate',this); }, /* beginning of custom undo/redo support */ // customUndo: Boolean // Whether we shall use custom undo/redo support instead of the native // browser support. By default, we only enable customUndo for IE, as it // has broken native undo/redo support. Note: the implementation does // support other browsers which have W3C DOM2 Range API implemented. // It was also enabled on WebKit, to fix undo/redo enablement. (#9613) customUndo: dojo.isIE || dojo.isWebKit, // editActionInterval: Integer // When using customUndo, not every keystroke will be saved as a step. // Instead typing (including delete) will be grouped together: after // a user stops typing for editActionInterval seconds, a step will be // saved; if a user resume typing within editActionInterval seconds, // the timeout will be restarted. By default, editActionInterval is 3 // seconds. editActionInterval: 3, beginEditing: function(cmd){ // summary: // Called to note that the user has started typing alphanumeric characters, if it's not already noted. // Deals with saving undo; see editActionInterval parameter. // tags: // private if(!this._inEditing){ this._inEditing=true; this._beginEditing(cmd); } if(this.editActionInterval>0){ if(this._editTimer){ clearTimeout(this._editTimer); } this._editTimer = setTimeout(dojo.hitch(this, this.endEditing), this._editInterval); } }, _steps:[], _undoedSteps:[], execCommand: function(cmd){ // summary: // Main handler for executing any commands to the editor, like paste, bold, etc. // Called by plugins, but not meant to be called by end users. // tags: // protected if(this.customUndo && (cmd == 'undo' || cmd == 'redo')){ return this[cmd](); }else{ if(this.customUndo){ this.endEditing(); this._beginEditing(); } var r; try{ r = this.inherited('execCommand', arguments); if(dojo.isWebKit && cmd == 'paste' && !r){ //see #4598: safari does not support invoking paste from js throw { code: 1011 }; // throw an object like Mozilla's error } }catch(e){ //TODO: when else might we get an exception? Do we need the Mozilla test below? if(e.code == 1011 /* Mozilla: service denied */ && /copy|cut|paste/.test(cmd)){ // Warn user of platform limitation. Cannot programmatically access clipboard. See ticket #4136 var sub = dojo.string.substitute, accel = {cut:'X', copy:'C', paste:'V'}; alert(sub(this.commands.systemShortcut, [this.commands[cmd], sub(this.commands[dojo.isMac ? 'appleKey' : 'ctrlKey'], [accel[cmd]])])); } r = false; } if(this.customUndo){ this._endEditing(); } return r; } }, queryCommandEnabled: function(cmd){ // summary: // Returns true if specified editor command is enabled. // Used by the plugins to know when to highlight/not highlight buttons. // tags: // protected if(this.customUndo && (cmd == 'undo' || cmd == 'redo')){ return cmd == 'undo' ? (this._steps.length > 1) : (this._undoedSteps.length > 0); }else{ return this.inherited('queryCommandEnabled',arguments); } }, _moveToBookmark: function(b){ // summary: // Selects the text specified in bookmark b // tags: // private var bookmark = b.mark; var mark = b.mark; var col = b.isCollapsed; var r, sNode, eNode, sel; if(mark){ if(dojo.isIE){ if(dojo.isArray(mark)){ //IE CONTROL, have to use the native bookmark. bookmark = []; dojo.forEach(mark,function(n){ bookmark.push(dijit.range.getNode(n,this.editNode)); },this); dojo.withGlobal(this.window,'moveToBookmark',dijit,[{mark: bookmark, isCollapsed: col}]); }else{ if(mark.startContainer && mark.endContainer){ // Use the pseudo WC3 range API. This works better for positions // than the IE native bookmark code. sel = dijit.range.getSelection(this.window); if(sel && sel.removeAllRanges){ sel.removeAllRanges(); r = dijit.range.create(this.window); sNode = dijit.range.getNode(mark.startContainer,this.editNode); eNode = dijit.range.getNode(mark.endContainer,this.editNode); if(sNode && eNode){ // Okay, we believe we found the position, so add it into the selection // There are cases where it may not be found, particularly in undo/redo, when // IE changes the underlying DOM on us (wraps text in a <p> tag or similar. // So, in those cases, don't bother restoring selection. r.setStart(sNode,mark.startOffset); r.setEnd(eNode,mark.endOffset); sel.addRange(r); } } } } }else{//w3c range sel = dijit.range.getSelection(this.window); if(sel && sel.removeAllRanges){ sel.removeAllRanges(); r = dijit.range.create(this.window); sNode = dijit.range.getNode(mark.startContainer,this.editNode); eNode = dijit.range.getNode(mark.endContainer,this.editNode); if(sNode && eNode){ // Okay, we believe we found the position, so add it into the selection // There are cases where it may not be found, particularly in undo/redo, when // formatting as been done and so on, so don't restore selection then. r.setStart(sNode,mark.startOffset); r.setEnd(eNode,mark.endOffset); sel.addRange(r); } } } } }, _changeToStep: function(from, to){ // summary: // Reverts editor to "to" setting, from the undo stack. // tags: // private this.setValue(to.text); var b=to.bookmark; if(!b){ return; } this._moveToBookmark(b); }, undo: function(){ // summary: // Handler for editor undo (ex: ctrl-z) operation // tags: // private //console.log('undo'); var ret = false; if(!this._undoRedoActive){ this._undoRedoActive = true; this.endEditing(true); var s=this._steps.pop(); if(s && this._steps.length>0){ this.focus(); this._changeToStep(s,this._steps[this._steps.length-1]); this._undoedSteps.push(s); this.onDisplayChanged(); delete this._undoRedoActive; ret = true; } delete this._undoRedoActive; } return ret; }, redo: function(){ // summary: // Handler for editor redo (ex: ctrl-y) operation // tags: // private //console.log('redo'); var ret = false; if(!this._undoRedoActive){ this._undoRedoActive = true; this.endEditing(true); var s=this._undoedSteps.pop(); if(s && this._steps.length>0){ this.focus(); this._changeToStep(this._steps[this._steps.length-1],s); this._steps.push(s); this.onDisplayChanged(); ret = true; } delete this._undoRedoActive; } return ret; }, endEditing: function(ignore_caret){ // summary: // Called to note that the user has stopped typing alphanumeric characters, if it's not already noted. // Deals with saving undo; see editActionInterval parameter. // tags: // private if(this._editTimer){ clearTimeout(this._editTimer); } if(this._inEditing){ this._endEditing(ignore_caret); this._inEditing=false; } }, _getBookmark: function(){ // summary: // Get the currently selected text // tags: // protected var b=dojo.withGlobal(this.window,dijit.getBookmark); var tmp=[]; if(b && b.mark){ var mark = b.mark; if(dojo.isIE){ // Try to use the pseudo range API on IE for better accuracy. var sel = dijit.range.getSelection(this.window); if(!dojo.isArray(mark)){ if(sel){ var range; if(sel.rangeCount){ range = sel.getRangeAt(0); } if(range){ b.mark = range.cloneRange(); }else{ b.mark = dojo.withGlobal(this.window,dijit.getBookmark); } } }else{ // Control ranges (img, table, etc), handle differently. dojo.forEach(b.mark,function(n){ tmp.push(dijit.range.getIndex(n,this.editNode).o); },this); b.mark = tmp; } } try{ if(b.mark && b.mark.startContainer){ tmp=dijit.range.getIndex(b.mark.startContainer,this.editNode).o; b.mark={startContainer:tmp, startOffset:b.mark.startOffset, endContainer:b.mark.endContainer===b.mark.startContainer?tmp:dijit.range.getIndex(b.mark.endContainer,this.editNode).o, endOffset:b.mark.endOffset}; } }catch(e){ b.mark = null; } } return b; }, _beginEditing: function(cmd){ // summary: // Called when the user starts typing alphanumeric characters. // Deals with saving undo; see editActionInterval parameter. // tags: // private if(this._steps.length === 0){ // You want to use the editor content without post filtering // to make sure selection restores right for the 'initial' state. // and undo is called. So not using this.savedContent, as it was 'processed' // and the line-up for selections may have been altered. this._steps.push({'text':dijit._editor.getChildrenHtml(this.editNode),'bookmark':this._getBookmark()}); } }, _endEditing: function(ignore_caret){ // summary: // Called when the user stops typing alphanumeric characters. // Deals with saving undo; see editActionInterval parameter. // tags: // private // Avoid filtering to make sure selections restore. var v = dijit._editor.getChildrenHtml(this.editNode); this._undoedSteps=[];//clear undoed steps this._steps.push({text: v, bookmark: this._getBookmark()}); }, onKeyDown: function(e){ // summary: // Handler for onkeydown event. // tags: // private //We need to save selection if the user TAB away from this editor //no need to call _saveSelection for IE, as that will be taken care of in onBeforeDeactivate if(!dojo.isIE && !this.iframe && e.keyCode == dojo.keys.TAB && !this.tabIndent){ this._saveSelection(); } if(!this.customUndo){ this.inherited(arguments); return; } var k = e.keyCode, ks = dojo.keys; if(e.ctrlKey && !e.altKey){//undo and redo only if the special right Alt + z/y are not pressed #5892 if(k == 90 || k == 122){ //z dojo.stopEvent(e); this.undo(); return; }else if(k == 89 || k == 121){ //y dojo.stopEvent(e); this.redo(); return; } } this.inherited(arguments); switch(k){ case ks.ENTER: case ks.BACKSPACE: case ks.DELETE: this.beginEditing(); break; case 88: //x case 86: //v if(e.ctrlKey && !e.altKey && !e.metaKey){ this.endEditing();//end current typing step if any if(e.keyCode == 88){ this.beginEditing('cut'); //use timeout to trigger after the cut is complete setTimeout(dojo.hitch(this, this.endEditing), 1); }else{ this.beginEditing('paste'); //use timeout to trigger after the paste is complete setTimeout(dojo.hitch(this, this.endEditing), 1); } break; } //pass through default: if(!e.ctrlKey && !e.altKey && !e.metaKey && (e.keyCode<dojo.keys.F1 || e.keyCode>dojo.keys.F15)){ this.beginEditing(); break; } //pass through case ks.ALT: this.endEditing(); break; case ks.UP_ARROW: case ks.DOWN_ARROW: case ks.LEFT_ARROW: case ks.RIGHT_ARROW: case ks.HOME: case ks.END: case ks.PAGE_UP: case ks.PAGE_DOWN: this.endEditing(true); break; //maybe ctrl+backspace/delete, so don't endEditing when ctrl is pressed case ks.CTRL: case ks.SHIFT: case ks.TAB: break; } }, _onBlur: function(){ // summary: // Called from focus manager when focus has moved away from this editor // tags: // protected //this._saveSelection(); this.inherited('_onBlur',arguments); this.endEditing(true); }, _saveSelection: function(){ // summary: // Save the currently selected text in _savedSelection attribute // tags: // private this._savedSelection=this._getBookmark(); //console.log('save selection',this._savedSelection,this); }, _restoreSelection: function(){ // summary: // Re-select the text specified in _savedSelection attribute; // see _saveSelection(). // tags: // private if(this._savedSelection){ // Clear off cursor to start, we're deliberately going to a selection. delete this._cursorToStart; // only restore the selection if the current range is collapsed // if not collapsed, then it means the editor does not lose // selection and there is no need to restore it if(dojo.withGlobal(this.window,'isCollapsed',dijit)){ this._moveToBookmark(this._savedSelection); } delete this._savedSelection; } }, onClick: function(){ // summary: // Handler for when editor is clicked // tags: // protected this.endEditing(true); this.inherited(arguments); }, _setDisabledAttr: function(/*Boolean*/ value){ var disableFunc = dojo.hitch(this, function(){ if((!this.disabled && value) || (!this._buttonEnabledPlugins && value)){ // Disable editor: disable all enabled buttons and remember that list this._buttonEnabledPlugins = dojo.filter(this._plugins, function(p){ if(p && p.button && !p.button.get("disabled")){ p.button.set("disabled", true); return true; } return false; }); }else if(this.disabled && !value){ // Enable editor: we only want to enable the buttons that should be // enabled (for example, the outdent button shouldn't be enabled if the current // text can't be outdented). dojo.forEach(this._buttonEnabledPlugins, function(p){ p.button.attr("disabled", false); p.updateState && p.updateState(); // just in case something changed, like caret position }); } }); this.setValueDeferred.addCallback(disableFunc); this.inherited(arguments); }, _setStateClass: function(){ this.inherited(arguments); // Let theme set the editor's text color based on editor enabled/disabled state. // We need to jump through hoops because the main document (where the theme CSS is) // is separate from the iframe's document. if(this.document && this.document.body){ dojo.style(this.document.body, "color", dojo.style(this.iframe, "color")); } } } ); // Register the "default plugins", ie, the built-in editor commands dojo.subscribe(dijit._scopeName + ".Editor.getPlugin",null,function(o){ if(o.plugin){ return; } var args = o.args, p; var _p = dijit._editor._Plugin; var name = args.name; switch(name){ case "undo": case "redo": case "cut": case "copy": case "paste": case "insertOrderedList": case "insertUnorderedList": case "indent": case "outdent": case "justifyCenter": case "justifyFull": case "justifyLeft": case "justifyRight": case "delete": case "selectAll": case "removeFormat": case "unlink": case "insertHorizontalRule": p = new _p({ command: name }); break; case "bold": case "italic": case "underline": case "strikethrough": case "subscript": case "superscript": p = new _p({ buttonClass: dijit.form.ToggleButton, command: name }); break; case "|": p = new _p({ button: new dijit.ToolbarSeparator(), setEditor: function(editor) {this.editor = editor;} }); } // console.log('name',name,p); o.plugin=p; }); }
najamelan/vhffs-4.5
vhffs-panel/js/dijit/Editor.js
JavaScript
bsd-3-clause
26,465
(function() { 'use strict'; angular.module('character-tracker.charactersheet') .controller('GearController', GearController); GearController.$inject =['GearService', 'InventoryService', '$scope']; function GearController(GearService, InventoryService, $scope) { var vm = this; var currentItem = ''; vm.inventory = InventoryService.getItems(); vm.gearSlots = GearService.getGearSlots(); vm.equipItem = function (item, slot){ if (item.equipped) { vm.unequipItem(item); } for (i = 0; i < vm.gearSlots.length; i++) { if (vm.gearSlots[i].slot === slot) { vm.gearSlots[i].equipped = true; vm.gearSlots[i].equippedItem = item; } } InventoryService.equipItem(item); } vm.unequipItem = function(item) { for (i = 0; i < vm.gearSlots.length; i++) { if (vm.gearSlots[i].equippedItem == item) { vm.gearSlots[i].equippedItem = {}; } InventoryService.unequipItem(item); } } vm.getItemAtSlot = function(slot) { currentItem = InventoryService.getItemAtSlot(slot); } init(); function init() { $.material.init(); } return vm; } }());
tenthirtyone/character-tracker
app/js/tracker/gear/gear.controller.js
JavaScript
bsd-3-clause
1,270
module.exports = { selector: '.skilifts .skilift', parse: { name: 1, status: { child: 0, attribute: 'class', regex: / ([a-z]+)$/ } } };
pirxpilot/liftie
lib/resorts/larosiere/index.js
JavaScript
bsd-3-clause
172
function postTodo ({input, state, output, services}) { const todo = state.get(`app.todos.${input.ref}`) services.http.post('/api/todos', todo) .then(output.success) .catch(output.error) } postTodo.async = true postTodo.outputs = ['success', 'error'] export default postTodo
morepath/morepath_cerebral_todomvc
client/modules/app/actions/postTodo.js
JavaScript
bsd-3-clause
289
'use strict'; angular.module('user-filters') .directive('zoUserFilters', function(){ return { restrict: 'E', replace: true, templateUrl: 'app/user-filters/list-directive.html', controller: 'UserFiltersDirectiveCtrl' } }) .controller('UserFiltersDirectiveCtrl', ['$scope', function($scope){ }]);
johnnycheng/AngularConcept
src/app/user-filters/list-directive.js
JavaScript
bsd-3-clause
347
import React from 'react'; import PrivateRoute from '../../../routes/PrivateRoute'; import TextNodesEditorLayout from '../layouts/TextNodesLayout/TextNodesEditorLayout'; export default ( <PrivateRoute exact path="/textNodes/edit" component={TextNodesEditorLayout} roles={['commenter', 'editor', 'admin']} /> );
CtrHellenicStudies/Commentary
src/modules/textNodes/routes/index.js
JavaScript
bsd-3-clause
323
var slug = require('slug'); var async = require('async'); var _ = require('underscore'); var kwery = require('kwery'); var functions = { getInstances: function (state, next) { var result = kwery.flat(state.db, { path: new RegExp('^' + state.data.path + '(/|$)') }); result.many(function (instances) { state.instances = instances; next(null, state); }); }, parentData: function (state, next) { // Get parent data if parent exists if (!state.data.parent) { return next(null, state); } if (state.data.parent === '/') { state.parent = { path: '/', sort: [], }; return next(null, state); } var result = kwery.flat(state.db, { path: state.data.parent }); result.one(function (instance) { state.parent = instance; next(null, state); }); }, targetData: function (state, next) { // Instance that's being updated var target = JSON.parse(JSON.stringify(state.instances[0])); _.extend(target, state.data); target.order = state.data.order || target.sort[target.sort.length - 1]; target.sort[target.sort.length - 1] = target.order; delete target.parent; if (state.parent) { target.path = (state.parent.path + '/' + slug(target.name).toLowerCase()).replace('//', '/'); target.sort = state.parent.sort.concat([target.sort[target.sort.length - 1]]); } else { target.path = target.path.substr(0, target.path.lastIndexOf('/') + 1) + slug(target.name).toLowerCase(); } state.target = target; next(null, state); }, instancesData: function (state, next) { var base; var instances = JSON.parse(JSON.stringify(state.instances)); var original = instances[0]; instances.forEach(function (instance, i) { if (i === 0) { instances[i] = state.target; } else { instance.path = instance.path.replace(new RegExp('^' + original.path), state.target.path); instance.sort = state.target.sort.concat(instance.sort.slice(original.sort.length)); } }); state.data_instances = instances; next(null, state); }, updateInstances: function (state, next) { var stored_instances = []; state.data_instances.forEach(function (instance, i) { stored_instances.push(_.extend(state.instances[i], instance)); }); state.stored_instances = stored_instances; next(null, state); }, }; module.exports = functions;
Enome/jungles
data-memory/update/functions.js
JavaScript
bsd-3-clause
2,479
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule RelayDefaultNetworkLayer * @typechecks * @flow */ 'use strict'; var Promise = require('Promise'); import type RelayMutationRequest from 'RelayMutationRequest'; import type RelayQueryRequest from 'RelayQueryRequest'; var fetchWithRetries = require('fetchWithRetries'); import type {InitWithRetries} from 'fetchWithRetries'; type GraphQLError = { message: string; locations: Array<GraphQLErrorLocation>; }; type GraphQLErrorLocation = { column: number; line: number; }; class RelayDefaultNetworkLayer { _uri: string; _init: $FlowIssue; // InitWithRetries constructor(uri: string, init?: ?InitWithRetries) { this._uri = uri; this._init = {...init}; // Bind instance methods to facilitate reuse when creating custom network // layers. var self: any = this; self.sendMutation = this.sendMutation.bind(this); self.sendQueries = this.sendQueries.bind(this); self.supports = this.supports.bind(this); } sendMutation(request: RelayMutationRequest): Promise { return this._sendMutation(request).then( result => result.json() ).then(payload => { if (payload.hasOwnProperty('errors')) { var error = new Error( 'Server request for mutation `' + request.getDebugName() + '` ' + 'failed for the following reasons:\n\n' + formatRequestErrors(request, payload.errors) ); (error: any).source = payload; request.reject(error); } else { request.resolve({response: payload.data}); } }).catch( error => request.reject(error) ); } sendQueries(requests: Array<RelayQueryRequest>): Promise { return Promise.all(requests.map(request => ( this._sendQuery(request).then( result => result.json() ).then(payload => { if (payload.hasOwnProperty('errors')) { var error = new Error( 'Server request for query `' + request.getDebugName() + '` ' + 'failed for the following reasons:\n\n' + formatRequestErrors(request, payload.errors) ); (error: any).source = payload; request.reject(error); } else if (!payload.hasOwnProperty('data')) { request.reject(new Error( 'Server response was missing for query `' + request.getDebugName() + '`.' )); } else { request.resolve({response: payload.data}); } }).catch( error => request.reject(error) ) ))); } supports(...options: Array<string>): boolean { // Does not support the only defined option, "defer". return false; } /** * Sends a POST request with optional files. */ _sendMutation(request: RelayMutationRequest): Promise { var init; var files = request.getFiles(); if (files) { if (!global.FormData) { throw new Error('Uploading files without `FormData` not supported.'); } var formData = new FormData(); formData.append('query', request.getQueryString()); formData.append('variables', JSON.stringify(request.getVariables())); for (var filename in files) { if (files.hasOwnProperty(filename)) { formData.append(filename, files[filename]); } } init = { ...this._init, body: formData, method: 'POST', }; } else { init = { ...this._init, body: JSON.stringify({ query: request.getQueryString(), variables: request.getVariables(), }), headers: { ...this._init.headers, 'Content-Type': 'application/json', }, method: 'POST', }; } return fetch(this._uri, init).then(throwOnServerError); } /** * Sends a POST request and retries if the request fails or times out. */ _sendQuery(request: RelayQueryRequest): Promise { return fetchWithRetries(this._uri, { ...this._init, body: JSON.stringify({ query: request.getQueryString(), variables: request.getVariables(), }), headers: { ...this._init.headers, 'Content-Type': 'application/json', }, method: 'POST', }); } } /** * Rejects HTTP responses with a status code that is not >= 200 and < 300. * This is done to follow the internal behavior of `fetchWithRetries`. */ function throwOnServerError(response: any): any { if (response.status >= 200 && response.status < 300) { return response; } else { throw response; } } /** * Formats an error response from GraphQL server request. */ function formatRequestErrors( request: RelayMutationRequest | RelayQueryRequest, errors: Array<GraphQLError> ): string { var CONTEXT_BEFORE = 20; var CONTEXT_LENGTH = 60; var queryLines = request.getQueryString().split('\n'); return errors.map(({locations, message}, ii) => { var prefix = (ii + 1) + '. '; var indent = ' '.repeat(prefix.length); //custom errors thrown in graphql-server may not have locations var locationMessage = locations ? ('\n' + locations.map(({column, line}) => { var queryLine = queryLines[line - 1]; var offset = Math.min(column - 1, CONTEXT_BEFORE); return [ queryLine.substr(column - 1 - offset, CONTEXT_LENGTH), ' '.repeat(offset) + '^^^' ].map(messageLine => indent + messageLine).join('\n'); }).join('\n')) : ''; return prefix + message + locationMessage; }).join('\n'); } module.exports = RelayDefaultNetworkLayer;
tmitchel2/relay
src/network-layer/default/RelayDefaultNetworkLayer.js
JavaScript
bsd-3-clause
5,878
$(document).ready(function(){ $('.service-wrapper img').hover( function(){ $(this).animate({'width':'100px'}); //$(this).next().css({'display':'none'}); }, function(){ $(this).animate({'width':'50px'}); //$(this).next().css({'display':'block'}); } ); /* $('.service-wrapper').hover(function () { $(this).css({'background':'red'}); })*/ }); /*$(document).ready(function(){ $('img').hover( function(){ $(this).animate({'width':'100px'}); //$(this).next().css({'display':'none'}); }, function(){ $(this).animate({'width':'50px'}); //$(this).next().css({'display':'block'}); } ); })*/
agent115/test2
web/js/js.js
JavaScript
bsd-3-clause
824
(function () { 'use strict'; var directives = angular.module('data-services.directives', []), relationshipFormatter = function(cellValue, options, rowObject) { var i, result = '', field; for (i = 0; i < rowObject.fields.length; i += 1) { if (rowObject.fields[i].name === options.colModel.name) { field = rowObject.fields[i]; break; } } if (field && field.displayValue) { if (typeof(field.displayValue) === 'string' || field.displayValue instanceof String) { result = field.displayValue; } else { angular.forEach(field.displayValue, function (value, key) { if (key) { result = result.concat(value, ", "); } }, result); if (result) { result = result.slice(0, -2); } } } return result; }, textFormatter = function (cellValue, options, rowObject) { var val = cellValue, TEXT_LENGTH_LIMIT = 40; //limit of characters for display in jqgrid instances if field type is textarea if (cellValue !== null && cellValue !== undefined && cellValue.length > TEXT_LENGTH_LIMIT) { val = cellValue.substring(0, TEXT_LENGTH_LIMIT); val = val + '...'; } return val; }, idFormatter = function (cellValue, options, rowObject) { var val = cellValue; if (cellValue !== undefined && !isNaN(cellValue) && parseInt(cellValue, 10) < 0) { val = ''; } return val; }, stringEscapeFormatter = function (cellValue, options, rowObject) { var val = ''; val = _.escape(cellValue); return val; }, mapFormatter = function (cellValue, options, rowObject) { var result = '', val = cellValue, STRING_LENGTH_LIMIT = 20; //limit of characters for display in jqgrid instances if field type is map angular.forEach(cellValue, function (value, key) { if (key) { if (key.length > STRING_LENGTH_LIMIT) { key = key.substring(0, STRING_LENGTH_LIMIT); key = key + '...'; } if (value && value.length > STRING_LENGTH_LIMIT) { value = value.substring(0, STRING_LENGTH_LIMIT); value = value + '...'; } result = result.concat(key, ' : ', value,'\n'); } }, result); return result; }; function findCurrentScope(startScope, functionName) { var parent = startScope; while (!parent[functionName]) { parent = parent.$parent; } return parent; } /* * This function checks if the field name is reserved for jqgrid (subgrid, cb, rn) * and if true temporarily changes that name. */ function changeIfReservedFieldName(fieldName) { if (fieldName === 'cb' || fieldName === 'rn' || fieldName === 'subgrid') { return fieldName + '___'; } else { return fieldName; } } /* * This function checks if the field name was changed * and if true changes this name to the original. */ function backToReservedFieldName(fieldName) { if (fieldName === 'cb___' || fieldName === 'rn___' || fieldName === 'subgrid___') { var fieldNameLength = fieldName.length; return fieldName.substring(0, fieldNameLength - 3); } else { return fieldName; } } /* * This function calculates width parameters * for fit jqGrid on the screen. */ function resizeGridWidth(gridId) { var intervalWidthResize, tableWidth; clearInterval(intervalWidthResize); intervalWidthResize = setInterval( function () { tableWidth = $('#gbox_' + gridId).parent().width(); $('#' + gridId).jqGrid("setGridWidth", tableWidth); clearInterval(intervalWidthResize); }, 200); } /* * This function calculates height parameters * for fit jqGrid on the screen. */ function resizeGridHeight(gridId) { var intervalHeightResize, gap, tableHeight; clearInterval(intervalHeightResize); intervalHeightResize = setInterval( function () { if ($('.overrideJqgridTable').offset() !== undefined) { gap = 1 + $('.overrideJqgridTable').offset().top - $('.inner-center .ui-layout-content').offset().top; tableHeight = Math.floor($('.inner-center .ui-layout-content').height() - gap - $('.ui-jqgrid-pager').outerHeight() - $('.ui-jqgrid-hdiv').outerHeight()); $('#' + gridId).jqGrid("setGridHeight", tableHeight); resizeGridWidth(gridId); } clearInterval(intervalHeightResize); }, 250); } /* * This function checks grid width * and increase this width if possible. */ function resizeIfNarrow(gridId) { var intervalIfNarrowResize; setTimeout(function() { clearInterval(intervalIfNarrowResize); }, 950); intervalIfNarrowResize = setInterval( function () { if (($('#' + gridId).jqGrid('getGridParam', 'width') - 20) > $('#gbox_' + gridId + ' .ui-jqgrid-btable').width()) { $('#' + gridId).jqGrid('setGridWidth', ($('#' + gridId).jqGrid('getGridParam', 'width') - 4), true); $('#' + gridId).jqGrid('setGridWidth', $('#inner-center.inner-center').width() - 2, false); } }, 550); } /* * This function checks the name of field * whether is selected for display in the jqGrid */ function isSelectedField(name, selectedFields) { var i; if (selectedFields) { for (i = 0; i < selectedFields.length; i += 1) { if (name === selectedFields[i].basic.name) { return true; } } } return false; } function handleGridPagination(pgButton, pager, scope) { var newPage = 1, last, newSize; if ("user" === pgButton) { //Handle changing page by the page input newPage = parseInt(pager.find('input:text').val(), 10); // get new page number last = parseInt($(this).getGridParam("lastpage"), 10); // get last page number if (newPage > last || newPage === 0) { // check range - if we cross range then stop return 'stop'; } } else if ("records" === pgButton) { //Page size change, we must update scope value to avoid wrong page size in the trash screen newSize = parseInt(pager.find('select')[0].value, 10); scope.entityAdvanced.userPreferences.gridRowsNumber = newSize; } } function buildGridColModel(colModel, fields, scope, removeVersionField, ignoreHideFields) { var i, j, cmd, field, skip = false, widthTable; widthTable = scope.getColumnsWidth(); for (i = 0; i < fields.length; i += 1) { field = fields[i]; skip = false; // for history and trash we don't generate version field if (removeVersionField && field.metadata !== undefined && field.metadata.length > 0) { for (j = 0; j < field.metadata.length; j += 1) { if (field.metadata[j].key === "version.field" && field.metadata[j].value === "true") { skip = true; break; } } } if (!skip && !field.nonDisplayable) { //if name is reserved for jqgrid need to change field name field.basic.name = changeIfReservedFieldName(field.basic.name); cmd = { label: field.basic.displayName, name: field.basic.name, index: field.basic.name, jsonmap: "fields." + i + ".value", width: widthTable[field.basic.name]? widthTable[field.basic.name] : 220, hidden: ignoreHideFields? false : !isSelectedField(field.basic.name, scope.selectedFields) }; cmd.formatter = stringEscapeFormatter; if (scope.isDateField(field)) { cmd.formatter = 'date'; cmd.formatoptions = { newformat: 'Y-m-d'}; } if (scope.isRelationshipField(field)) { // append a formatter for relationships cmd.formatter = relationshipFormatter; cmd.sortable = false; } if (field.basic.name === 'id') { cmd.formatter = idFormatter; } if (scope.isTextArea(field.settings)) { cmd.formatter = textFormatter; cmd.classes = 'text'; } if (scope.isMapField(field)) { cmd.formatter = mapFormatter; cmd.sortable = false; } if (scope.isComboboxField(field)) { cmd.jsonmap = "fields." + i + ".displayValue"; if (scope.isMultiSelectCombobox(field)) { cmd.sortable = false; } } colModel.push(cmd); } } } /* * This function checks if the next column is last of the jqgrid. */ function isLastNextColumn(colModel, index) { var result; $.each(colModel, function (i, val) { if ((index + 1) < i) { if (colModel[i].hidden !== false) { result = true; } else { result = false; } } return (result); }); return result; } function handleColumnResize(tableName, gridId, index, width, scope) { var tableWidth, widthNew, widthOrg, colModel = $('#' + gridId).jqGrid('getGridParam','colModel'); if (colModel.length - 1 === index + 1 || (colModel[index + 1] !== undefined && isLastNextColumn(colModel, index))) { widthOrg = colModel[index].widthOrg; if (Math.floor(width) > Math.floor(widthOrg)) { widthNew = colModel[index + 1].width + Math.floor(width - widthOrg); colModel[index + 1].width = widthNew; scope.saveColumnWidth(colModel[index + 1].index, widthNew); $('.ui-jqgrid-labels > th:eq('+(index + 1)+')').css('width', widthNew); $('#' + gridId + ' .jqgfirstrow > td:eq('+(index + 1)+')').css('width', widthNew); } colModel[index].widthOrg = width; } scope.saveColumnWidth(colModel[index].index, width); tableWidth = $(tableName).width(); $('#' + gridId).jqGrid("setGridWidth", tableWidth); } /* * This function expand input field if string length is long and when the cursor is focused on the text box, * and go back to default size when move out cursor */ directives.directive('extendInput', function($timeout) { return { restrict : 'A', link : function(scope, element, attr) { var elem = angular.element(element), width = 210, duration = 300, extraWidth = 550, height = 22, elemValue, lines, eventTimer; function extendInput(elemInput, event) { elemValue = elemInput[0].value; lines = elemValue.split("\n"); if (20 <= elemValue.length || lines.length > 1 || event.keyCode === 13) { //if more than 20 characters or more than 1 line duration = (event.type !== "keyup") ? 300 : 30; if (lines.length < 10) { height = 34; } else { height = 24; } elemInput.animate({ width: extraWidth, height: height * lines.length, overflow: 'auto' }, duration); } } elem.on({ 'focusout': function (e) { clearTimeout(eventTimer); eventTimer = setTimeout( function() { elem.animate({ width: width, height: 34, overflow: 'hidden' }, duration); }, 100); }, 'focus': function (e) { clearTimeout(eventTimer); extendInput($(this), e); }, 'keyup': function (e) { extendInput($(this), e); } }); } }; }); /** * Bring focus on input-box while opening the new entity box */ directives.directive('focusmodal', function() { return { restrict : 'A', link : function(scope, element, attr) { var elem = angular.element(element); elem.on({ 'shown.bs.modal': function () { elem.find('#inputEntityName').focus(); } }); } }; }); /** * Show/hide details about a field by clicking on caret icon in the first column in * the field table. */ directives.directive('mdsExpandAccordion', function () { return { restrict: 'A', link: function (scope, element) { var target = angular.element($('#entityFieldsLists')); target.on('show.bs.collapse', function (e) { $(e.target).siblings('.panel-heading').find('i.fa-caret-right') .removeClass('fa-caret-right') .addClass('fa-caret-down'); }); target.on('hide.bs.collapse', function (e) { $(e.target).siblings('.panel-heading').find('i.fa-caret-down') .removeClass('fa-caret-down') .addClass('fa-caret-right'); }); } }; }); directives.directive('mdsHeaderAccordion', function () { return { restrict: 'A', link: function (scope, element) { var elem = angular.element(element), target = elem.find(".panel-collapse"); target.on({ 'show.bs.collapse': function () { elem.find('.panel-icon') .removeClass('fa-caret-right') .addClass('fa-caret-down'); }, 'hide.bs.collapse': function () { elem.find('.panel-icon') .removeClass('fa-caret-down') .addClass('fa-caret-right'); } }); } }; }); /** * Ensure that if no field name has been entered it should be filled in by generating a camel * case name from the field display name. If you pass a 'new' value to this directive then it * will be check name of new field. Otherwise you have to pass a index to find a existing field. */ directives.directive('mdsCamelCase', function (MDSUtils) { return { restrict: 'A', link: function (scope, element, attrs) { angular.element(element).focusout(function () { var attrValue = attrs.mdsCamelCase, field; if (_.isEqual(attrValue, 'new')) { field = scope.newField; } else if (_.isNumber(+attrValue)) { field = scope.fields && scope.fields[+attrValue]; } if (field && field.basic && isBlank(field.basic.name)) { scope.safeApply(function () { field.basic.name = MDSUtils.camelCase(field.basic.displayName); }); } }); } }; }); /** * Add ability to change model property mode on UI from read to write and vice versa. For this * to work there should be two tags next to each other. First tag (span, div) should present * property in the read mode. Second tag (input) should present property in the write mode. By * default property should be presented in the read mode and the second tag should be hidden. */ directives.directive('mdsEditable', function () { return { restrict: 'A', link: function (scope, element) { var elem = angular.element(element), read = elem.find('span'), write = elem.find('input'); elem.click(function (e) { e.stopPropagation(); read.hide(); write.show(); write.focus(); }); write.click(function (e) { e.stopPropagation(); }); write.focusout(function () { write.hide(); read.show(); }); } }; }); directives.directive("fileread", function () { return { scope: { fileread: "=" }, link: function (scope, element, attributes) { element.bind("change", function (changeEvent) { var reader = new FileReader(); reader.onload = function (loadEvent) { scope.$apply(function () { scope.fileread = loadEvent.target.result; }); }; if(changeEvent.target.files[0] !== undefined) { reader.readAsDataURL(changeEvent.target.files[0]); } }); } }; }); /** * Add a datetime picker to an element. */ directives.directive('mdsDatetimePicker', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var isReadOnly = scope.$eval(attr.ngReadonly); if(!isReadOnly) { angular.element(element).datetimepicker({ showTimezone: true, changeYear: true, useLocalTimezone: true, dateFormat: 'yy-mm-dd', timeFormat: 'HH:mm z', onSelect: function (dateTex) { scope.safeApply(function () { ngModel.$setViewValue(dateTex); }); }, onClose: function (year, month, inst) { var viewValue = $(this).val(); scope.safeApply(function () { ngModel.$setViewValue(viewValue); }); }, onChangeMonthYear: function (year, month, inst) { var curDate = $(this).datepicker("getDate"); if (curDate === null) { return; } if (curDate.getFullYear() !== year || curDate.getMonth() !== month - 1) { curDate.setYear(year); curDate.setMonth(month - 1); $(this).datepicker("setDate", curDate); } } }); } } }; }); /** * Add a date picker to an element. */ directives.directive('mdsDatePicker', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var isReadOnly = scope.$eval(attr.ngReadonly); if(!isReadOnly) { angular.element(element).datepicker({ changeYear: true, showButtonPanel: true, dateFormat: 'yy-mm-dd', onSelect: function (dateTex) { scope.safeApply(function () { ngModel.$setViewValue(dateTex); }); }, onClose: function (year, month, inst) { var viewValue = $(this).val(); scope.safeApply(function () { ngModel.$setViewValue(viewValue); }); }, onChangeMonthYear: function (year, month, inst) { var curDate = $(this).datepicker("getDate"); if (curDate === null) { return; } if (curDate.getFullYear() !== year || curDate.getMonth() !== month - 1) { curDate.setYear(year); curDate.setMonth(month - 1); $(this).datepicker("setDate", curDate); } } }); } } }; }); /** * Add "Item" functionality of "Connected Lists" control to the element. "Connected Lists Group" * is passed as a value of the attribute. If item is selected '.connected-list-item-selected-{group} * class is added. */ directives.directive('connectedListTargetItem', function () { return { restrict: 'A', link: function (scope, element) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), condition = jQelem.attr('condition'); if (typeof condition !== 'undefined' && condition !== false) { if (!scope.$eval(condition)){ return; } } jQelem.attr('draggable','true'); jQelem.addClass(connectWith); jQelem.addClass("target-item"); jQelem.click(function() { $(this).toggleClass("selected"); scope.$apply(); }); jQelem.dblclick(function() { var e = $(this), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], index = parseInt(e.attr('item-index'), 10), item = target[index]; e.removeClass("selected"); scope.$apply(function() { source.push(item); target.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('dragstart', function(e) { var item = $(this); item.addClass('selected'); item.fadeTo(100, 0.4); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('origin', 'target'); e.dataTransfer.setData('index', item.attr('item-index')); return false; }, false); elem.addEventListener('dragend', function(e) { var item = $(this); item.removeClass('selected'); item.fadeTo(100, 1.0); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), thisIndex = parseInt($(this).attr('item-index'), 10), source, target, item; $(this).removeClass('over'); $(this.parentNode).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'target') { // movement inside one container item = target[index]; if(thisIndex > index) { thisIndex += 1; } scope.$apply(function() { target[index] = 'null'; target.splice(thisIndex, 0, item); target.splice(target.indexOf('null'), 1); targetContainer.trigger('contentChange', [target]); }); } else if (itemOriginContainer === 'source') { item = source[index]; scope.$apply(function() { target.splice(thisIndex, 0, item); source.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); } }; }); directives.directive('connectedListSourceItem', function () { return { restrict: 'A', link: function (scope, element) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), condition = jQelem.attr('condition'); if (typeof condition !== 'undefined' && condition !== false) { if (!scope.$eval(condition)){ return; } } jQelem.attr('draggable','true'); jQelem.addClass(connectWith); jQelem.addClass("source-item"); jQelem.click(function() { $(this).toggleClass("selected"); scope.$apply(); }); jQelem.dblclick(function() { var e = $(this), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], index = parseInt(e.attr('item-index'), 10), item = source[index]; e.removeClass("selected"); scope.$apply(function() { target.push(item); source.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); return false; }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('dragstart', function(e) { var item = $(this); item.addClass('selected'); item.fadeTo(100, 0.4); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('origin', 'source'); e.dataTransfer.setData('index', item.attr('item-index')); return false; }, false); elem.addEventListener('dragend', function(e) { var item = $(this); item.removeClass('selected'); item.fadeTo(100, 1.0); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), thisIndex = parseInt($(this).attr('item-index'), 10), source, target, item; $(this).removeClass('over'); $(this.parentNode).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'source') { // movement inside one container item = source[index]; if(thisIndex > index) { thisIndex += 1; } scope.$apply(function() { source[index] = 'null'; source.splice(thisIndex, 0, item); source.splice(source.indexOf('null'), 1); sourceContainer.trigger('contentChange', [source]); }); } else if (itemOriginContainer === 'target') { item = target[index]; scope.$apply(function() { source.splice(thisIndex, 0, item); target.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); } }; }); /** * Add "Source List" functionality of "Connected Lists" control to the element (container). * "Connected Lists Group" is passed as a value of the attribute. "onItemsAdd", "onItemsRemove" * and "onItemMove" callback functions are registered to handle items adding/removing/sorting. */ directives.directive('connectedListSource', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), onContentChange = jQelem.attr('on-content-change'); jQelem.addClass('connected-list-source'); jQelem.addClass(connectWith); if(typeof scope[onContentChange] === typeof Function) { jQelem.on('contentChange', function(e, content) { scope[onContentChange](content); }); } elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); return false; }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), source, target, item; $(this).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'source') { // movement inside one container item = source[index]; scope.$apply(function() { source.splice(index, 1); source.push(item); sourceContainer.trigger('contentChange', [source]); }); } else if (itemOriginContainer === 'target') { item = target[index]; scope.$apply(function() { source.push(item); target.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); jQelem.keyup(function(event) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = sourceContainer.children('.selected'), selectedIndices = [], selectedItems = [], array = []; if(event.which === 13) { selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = source[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { source.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { target.push(item); }); angular.forEach(target, function (item) { array.push(item.id); }); viewScope.draft({ edit: true, values: { path: attr.mdsPath, advanced: true, value: [array] } }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } }); } }; }); /** * Add "Target List" functionality of "Connected Lists" control to the element (container). * "Connected Lists Group" is passed as a value of the attribute. "onItemsAdd", "onItemsRemove" * and "onItemMove" callback functions are registered to handle items adding/removing/sorting. */ directives.directive('connectedListTarget', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { var jQelem = angular.element(element), elem = element[0], connectWith = jQelem.attr('connect-with'), onContentChange = jQelem.attr('on-content-change'); jQelem.addClass('connected-list-target'); jQelem.addClass(connectWith); if(typeof scope[onContentChange] === typeof Function) { jQelem.on('contentChange', function(e, content) { scope[onContentChange](content); }); } elem.addEventListener('dragenter', function(e) { $(this).addClass('over'); return false; }, false); elem.addEventListener('dragleave', function(e) { $(this).removeClass('over'); return false; }, false); elem.addEventListener('dragover', function(e) { e.preventDefault(); return false; }, false); elem.addEventListener('drop', function(e) { e.stopPropagation(); var itemOriginContainer = e.dataTransfer.getData('origin'), index = parseInt(e.dataTransfer.getData('index'), 10), sourceContainer = $('.connected-list-source.' + connectWith), targetContainer = $('.connected-list-target.' + connectWith), source, target, item; $(this).removeClass('over'); source = scope[sourceContainer.attr('connected-list-source')]; target = scope[targetContainer.attr('connected-list-target')]; if (itemOriginContainer === 'target') { // movement inside one container item = target[index]; scope.$apply(function() { target.splice(index, 1); target.push(item); targetContainer.trigger('contentChange', [target]); }); } else if (itemOriginContainer === 'source') { item = source[index]; scope.$apply(function() { target.push(item); source.splice(index, 1); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } return false; }, false); jQelem.keyup(function(event) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = targetContainer.children('.selected'), selectedIndices = [], selectedItems = [], array = []; if(event.which === 13) { selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = target[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { target.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { source.push(item); }); angular.forEach(target, function (item) { array.push(item.id); }); viewScope.draft({ edit: true, values: { path: attr.mdsPath, advanced: true, value: [array] } }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); } }); } }; }); /** * Add "Move selected to target" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnTo', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = sourceContainer.children('.selected'), selectedIndices = [], selectedItems = []; selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = source[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { source.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { target.push(item); }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); angular.element(element).disableSelection(); } }; }); /** * Add "Move all to target" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnToAll', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedItems = sourceContainer.children(), viewScope = findCurrentScope(scope, 'draft'); scope.safeApply(function () { angular.forEach(source, function(item) { target.push(item); }); source.length = 0; sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); } }; }); /** * Add "Move selected to source" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnFrom', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], selectedElements = targetContainer.children('.selected'), selectedIndices = [], selectedItems = []; selectedElements.each(function() { var that = $(this), index = parseInt(that.attr('item-index'), 10), item = target[index]; that.removeClass('selected'); selectedIndices.push(index); selectedItems.push(item); }); scope.safeApply(function () { var viewScope = findCurrentScope(scope, 'draft'); angular.forEach(selectedIndices.reverse(), function(itemIndex) { target.splice(itemIndex, 1); }); angular.forEach(selectedItems, function(item) { source.push(item); }); sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); } }; }); /** * Add "Move all to source" functionality of "Connected Lists" control to the element (button). * "Connected Lists Group" is passed as a value of the 'connect-with' attribute. */ directives.directive('connectedListBtnFromAll', function (Entities) { return { restrict: 'A', link: function (scope, element, attr) { angular.element(element).click(function (e) { var sourceContainer = $('.connected-list-source.' + attr.connectWith), targetContainer = $('.connected-list-target.' + attr.connectWith), source = scope[sourceContainer.attr('connected-list-source')], target = scope[targetContainer.attr('connected-list-target')], viewScope = findCurrentScope(scope, 'draft'), selectedItems = targetContainer.children(); scope.safeApply(function () { angular.forEach(target, function(item) { source.push(item); }); target.length = 0; sourceContainer.trigger('contentChange', [source]); targetContainer.trigger('contentChange', [target]); }); }); } }; }); /** * Initializes filterable checkbox and sets a watch in the filterable scope to track changes * in "advancedSettings.browsing.filterableFields". */ directives.directive('initFilterable', function () { return { restrict: 'A', link: function (scope) { scope.$watch('advancedSettings.browsing.filterableFields', function() { if (!scope.advancedSettings.browsing) { scope.checked = false; } else { scope.checked = (scope.advancedSettings.browsing.filterableFields.indexOf(scope.field.id) >= 0); } }); } }; }); /** * Filtering entity by selected filter. */ directives.directive('clickfilter', function () { return { restrict: 'A', link: function (scope, element, attrs) { var elm = angular.element(element), singleSelect = (attrs.singleselect === "true"); scope.wasAllSelected = function () { var i; for (i = 0; i < elm.parent().children().children.length; i += 1) { if ($(elm.parent().children()[i]).children().context.lastChild.data.trim() === "ALL") { if ($(elm.parent().children()[i]).hasClass('active')) { return true; } else { return false; } } } return false; }; elm.click(function (e) { if (elm.children().hasClass("fa-check-square-o")) { if (elm.text().trim() !== 'ALL') { if (scope.wasAllSelected()) { elm.parent().children().each(function(i) { $(elm.parent().children()[i]).children().removeClass('fa-check-square-o'); $(elm.parent().children()[i]).children().addClass("fa-square-o"); $(elm.parent().children()[i]).removeClass('active'); }); $(this).children().addClass('fa-check-square-o').removeClass('fa-square-o'); $(this).addClass('active'); } else { $(this).children().removeClass("fa-check-square-o").addClass("fa-square-o"); $(this).removeClass("active"); } } } else { if (elm.text().trim() === 'ALL') { elm.parent().children().each(function(i) { $(elm.parent().children()[i]).children().removeClass('fa-square-o').addClass("fa-check-square-o"); $(elm.parent().children()[i]).addClass('active'); }); } else { if (singleSelect === true) { elm.parent().children().each(function(i) { $(elm.parent().children()[i]).children().removeClass('fa-check-square-o'); $(elm.parent().children()[i]).children().addClass("fa-square-o"); $(elm.parent().children()[i]).removeClass('active'); }); } $(this).children().addClass("fa-check-square-o").removeClass("fa-square-o"); $(this).addClass("active"); } } }); } }; }); /** * Displays entity instances data using jqGrid */ directives.directive('entityInstancesGrid', function ($rootScope, $timeout) { return { restrict: 'A', link: function (scope, element, attrs) { var elem = angular.element(element), eventResize, eventChange, gridId = attrs.id, firstLoad = true; $.ajax({ type: "GET", url: "../mds/entities/" + scope.selectedEntity.id + "/entityFields", dataType: "json", success: function (result) { var colModel = [], i, noSelectedFields = true, spanText, noSelectedFieldsText = scope.msg('mds.dataBrowsing.noSelectedFieldsInfo'); buildGridColModel(colModel, result, scope, false, false); elem.jqGrid({ url: "../mds/entities/" + scope.selectedEntity.id + "/instances", headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "POST", postData: { fields: JSON.stringify(scope.lookupBy) }, rowNum: scope.entityAdvanced.userPreferences.gridRowsNumber, onPaging: function (pgButton) { handleGridPagination(pgButton, $(this.p.pager), scope); }, jsonReader: { repeatitems: false }, prmNames: { sort: 'sortColumn', order: 'sortDirection' }, onSelectRow: function (id) { firstLoad = true; scope.editInstance(id, scope.selectedEntity.module, scope.selectedEntity.name); }, resizeStop: function (width, index) { handleColumnResize('#entityInstancesTable', gridId, index, width, scope); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.entityInstancesGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { scope.setDataRetrievalError(false); spanText = $('<span>').addClass('ui-jqgrid-status-label ui-jqgrid ui-widget hidden'); spanText.append(noSelectedFieldsText).css({padding: '3px 15px'}); $('#entityInstancesTable .ui-paging-info').append(spanText); $('.ui-jqgrid-status-label').addClass('hidden'); $('#pageInstancesTable_center').addClass('page_instancesTable_center'); if (scope.selectedFields !== undefined && scope.selectedFields.length > 0) { noSelectedFields = false; } else { noSelectedFields = true; $('#pageInstancesTable_center').hide(); $('#entityInstancesTable .ui-jqgrid-status-label').removeClass('hidden'); } if ($('#instancesTable').getGridParam('records') > 0) { $('#pageInstancesTable_center').show(); $('#entityInstancesTable .ui-jqgrid-hdiv').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { if (noSelectedFields) { $('#pageInstancesTable_center').hide(); $('#entityInstancesTable .ui-jqgrid-hdiv').hide(); } $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } $('#entityInstancesTable .ui-jqgrid-hdiv').addClass("table-lightblue"); $('#entityInstancesTable .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 550); if (firstLoad) { resizeIfNarrow(gridId); firstLoad = false; } }, loadError: function(e) { scope.setDataRetrievalError(true, e.responseText); } }); scope.$watch("lookupRefresh", function () { $('#' + attrs.id).jqGrid('setGridParam', { page: 1, postData: { fields: JSON.stringify(scope.lookupBy), lookup: (scope.selectedLookup) ? scope.selectedLookup.lookupName : "", filter: (scope.filterBy) ? JSON.stringify(scope.filterBy) : "" } }).trigger('reloadGrid'); }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); resizeGridHeight(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 200); }); } }); } }; }); /** * Displays related instances data using jqGrid */ directives.directive('entityInstancesBrowserGrid', function ($timeout, $http, LoadingModal) { return { restrict: 'A', link: function (scope, element, attrs) { var tableWidth, relatedEntityId, relatedClass, selectedEntityNested, elem = angular.element(element), gridId = attrs.id, showGrid = function () { $.ajax({ type: "GET", url: "../mds/entities/" + relatedEntityId + "/entityFields", dataType: "json", success: function (result) { var colMd, colModel = [], i, spanText; buildGridColModel(colModel, result, scope, false, true); elem.jqGrid({ url: "../mds/entities/" + relatedEntityId + "/instances", headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "POST", postData: { fields: JSON.stringify(scope.lookupBy), filter: (scope.filterBy) ? JSON.stringify(scope.filterBy) : "" }, jsonReader: { repeatitems: false }, prmNames: { sort: 'sortColumn', order: 'sortDirection' }, onSelectRow: function (id) { if (scope.relatedMode.isNested) { scope.addRelatedInstance(id, selectedEntityNested, scope.editedField); } else { scope.addRelatedInstance(id, scope.selectedEntity, scope.editedField); } }, resizeStop: function (width, index) { var widthNew, widthOrg, colModel = $('#' + gridId).jqGrid('getGridParam','colModel'); if (colModel.length - 1 === index + 1 || (colModel[index + 1] !== undefined && isLastNextColumn(colModel, index))) { widthOrg = colModel[index].widthOrg; if (Math.floor(width) > Math.floor(widthOrg)) { widthNew = colModel[index + 1].width + Math.floor(width - widthOrg); colModel[index + 1].width = widthNew; $('.ui-jqgrid-labels > th:eq('+(index + 1)+')').css('width', widthNew); $('#' + gridId + ' .jqgfirstrow > td:eq('+(index + 1)+')').css('width', widthNew); } colModel[index].widthOrg = width; } tableWidth = $('#instanceBrowserTable').width(); $('#gview_' + gridId + ' .ui-jqgrid-htable').width(tableWidth); $('#gview_' + gridId + ' .ui-jqgrid-btable').width(tableWidth); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.entityInstancesBrowserGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { $('#' + attrs.entityInstancesBrowserGrid + '_center').addClass('page_instancesTable_center'); if ($('#' + gridId).getGridParam('records') > 0) { $('#' + attrs.entityInstancesBrowserGrid + '_center').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } tableWidth = $('#instanceBrowserTable').width(); $('#gbox_' + gridId).css('width','100%'); $('#gview_' + gridId).css('width','100%'); $('#gview_' + gridId + ' .ui-jqgrid-htable').addClass("table-lightblue"); $('#gview_' + gridId + ' .ui-jqgrid-btable').addClass("table-lightblue"); $('#gview_' + gridId + ' .ui-jqgrid-htable').width(tableWidth); $('#gview_' + gridId + ' .ui-jqgrid-btable').width(tableWidth); $('#gview_' + gridId + ' .ui-jqgrid-bdiv').width('100%'); $('#gview_' + gridId + ' .ui-jqgrid-hdiv').width('100%').show(); $('#gview_' + gridId + ' .ui-jqgrid-view').width('100%'); $('#gbox_' + gridId + ' .ui-jqgrid-pager').width('100%'); } }); } }); }; if (scope.relatedEntity !== undefined && scope.relatedMode.isNested !== true) { relatedEntityId = scope.relatedEntity.id; showGrid(); } else if (scope.relatedMode.isNested) { relatedClass = scope.getRelatedClass(scope.field); if (relatedClass !== undefined && scope.relatedMode.isNested) { LoadingModal.open(); $http.get('../mds/entities/getEntityByClassName?entityClassName=' + relatedClass).success(function (data) { relatedEntityId = data.id; LoadingModal.close(); showGrid(); if (scope.currentRelationRecord !== undefined) { selectedEntityNested = {id: scope.currentRelationRecord.entitySchemaId}; } }); } } scope.$watch("instanceBrowserRefresh", function () { elem.jqGrid('setGridParam', { page: 1, postData: { fields: JSON.stringify(scope.lookupBy), lookup: (scope.selectedLookup) ? scope.selectedLookup.lookupName : "", filter: (scope.filterBy) ? JSON.stringify(scope.filterBy) : "" } }).trigger('reloadGrid'); }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); } }; }); /** * Displays related instances data using jqGrid */ directives.directive('entityRelationsGrid', function ($timeout, $http, MDSUtils, ModalFactory, LoadingModal) { return { restrict: 'A', link: function (scope, element, attrs) { var tableWidth, isHiddenGrid, eventResize, eventChange, relatedClass, relatedEntityId, updatePostData, postdata, filter = {removedIds: [], addedIds: [], addedNewRecords: []}, elem = angular.element(element), gridId = attrs.id, gridRecords = 0, fieldId = attrs.fieldId, gridHide = attrs.gridHide, pagerHide = attrs.pagerHide, selectedEntityId = scope.selectedEntity.id, selectedInstance = (scope.selectedInstance !== undefined && angular.isNumber(parseInt(scope.selectedInstance, 10)))? parseInt(scope.selectedInstance, 10) : undefined; relatedClass = scope.getRelatedClass(scope.field); LoadingModal.open(); $http.get('../mds/entities/getEntityByClassName?entityClassName=' + relatedClass).success(function (data) { scope.relatedEntity = data; relatedEntityId = data.id; LoadingModal.close(); $.ajax({ type: "GET", url: "../mds/entities/" + scope.relatedEntity.id + "/entityFields", dataType: "json", success: function (result) { var colModel = [], i, spanText; if (scope.relatedMode.isNested) { selectedInstance = scope.editedInstanceId; if (scope.currentRelationRecord !== undefined) { selectedEntityId = scope.currentRelationRecord.entitySchemaId; } } else { colModel.push({ name: scope.msg('mds.form.label.action').toUpperCase(), width: 150, align: 'center', title: false, frozen: true, hidden: scope.field.nonEditable, formatter: function (array, options, data) { return "<button class='btn btn-default btn-xs btn-danger-hover removeRelatedInstance' " + " title='" + scope.msg('mds.dataBrowsing.removeRelatedInstance') + "'><i class='fa fa-fw fa-trash-o'></i>" + scope.msg('mds.dataBrowsing.remove') + "</button>"; }, sortable: false }); selectedEntityId = scope.selectedEntity.id; } buildGridColModel(colModel, result, scope, false, true); elem.jqGrid({ url: "../mds/instances/" + selectedEntityId + "/instance/" + ((selectedInstance !== undefined)? selectedInstance : "new") + "/" + scope.field.name, headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "POST", postData: { filters: (filter.removedIds !== null) ? JSON.stringify(filter) : "" }, jsonReader: { repeatitems: false }, onSelectRow: function (id, status, e) { if (!scope.field.nonEditable && e.target.getAttribute('class') !== null && (e.target.getAttribute('class').indexOf('removeRelatedInstance') >= 0 || (e.target.tagName ==='I' && e.target.parentElement.getAttribute('class').indexOf('removeRelatedInstance') >= 0))) { scope.relatedData.removeNewAdded(scope.field, parseInt(id, 10)); } else if (!scope.field.nonEditable && e.target.tagName !=='I' && e.target.tagName !== 'BUTTON' && e.target.tagName ==='TD' && !(e.target.children[0] !== undefined && e.target.children[0].getAttribute('class').indexOf('removeRelatedInstance') >= 0) && scope.newRelatedFields === null && !scope.relatedMode.isNested) { selectedInstance = parseInt(id, 10); scope.currentRelationRecord = {entitySchemaId: relatedEntityId}; if (scope.field.type.defaultName !== "manyToManyRelationship" && scope.field.type.defaultName !== "oneToManyRelationship" && scope.field.type.defaultName !== "oneToOneRelationship" && selectedInstance > 0) { scope.editRelatedInstanceOfEntity(scope.relatedData.getRelatedId(scope.field), undefined, scope.field); } else if (scope.field.type.defaultName !== "manyToManyRelationship" && scope.field.type.defaultName !== "oneToManyRelationship" && selectedInstance < 0) { scope.editRelatedInstanceOfEntity(selectedInstance, undefined, scope.field); } else { scope.editRelatedInstanceOfEntity(selectedInstance, relatedEntityId, scope.field); } } }, ondblClickRow : function(id,iRow,iCol,e) { }, resizeStop: function (width, index) { var widthNew, widthOrg, colModel = $('#' + gridId).jqGrid('getGridParam','colModel'); if (colModel.length - 1 === index + 1 || (colModel[index + 1] !== undefined && isLastNextColumn(colModel, index))) { widthOrg = colModel[index].widthOrg; widthNew = colModel[index + 1].width + Math.abs(widthOrg - width); colModel[index + 1].width = widthNew; colModel[index].width = width; $('.ui-jqgrid-labels > th:eq('+(index + 1)+')').css('width', widthNew); $('#' + gridId + ' .jqgfirstrow > td:eq('+(index + 1)+')').css('width', widthNew); } tableWidth = $('#instance_' + gridId).width(); $('#' + gridId).jqGrid("setGridWidth", tableWidth); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.entityRelationsGrid, viewrecords: true, autowidth: true, loadui: 'disable', shrinkToFit: false, gridComplete: function () { $('#' + attrs.entityRelationsGrid + '_center').addClass('page_' + gridId + '_center'); gridRecords = $('#' + gridId).getGridParam('records'); if (gridRecords > 0) { if (gridHide !== undefined && gridHide === "true") { $('body #instance_' + gridId).removeClass('hiddengrid'); } $('#relationsTableTotalRecords_' + fieldId).text(gridRecords + ' ' + scope.msg('mds.field.items')); $('#' + attrs.entityRelationsGrid + '_center').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css("height","0"); } else { $('#relationsTableTotalRecords_' + fieldId).text('0 ' + scope.msg('mds.field.items')); $('#' + attrs.entityRelationsGrid + '_center').hide(); $('#gbox_' + gridId + ' .jqgfirstrow').css("height","1px"); if (gridHide !== undefined && gridHide === "true") { $('body #instance_' + gridId).addClass('hiddengrid'); } } $('#gview_' + gridId + ' .ui-jqgrid-hdiv').show(); $('#gview_' + gridId + ' .ui-jqgrid-hdiv').addClass("table-lightblue"); $('#gview_' + gridId + ' .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridWidth(gridId); }, 250); } }).jqGrid('setFrozenColumns'); if (pagerHide === "true") { $('#' + attrs.entityRelationsGrid).addClass('hidden'); } if (gridHide !== undefined && gridHide === "true") { $('body #instance_' + gridId).addClass('hiddengrid'); } } }); }).error(function (response) { LoadingModal.close(); ModalFactory.showErrorAlertWithResponse('mds.error.cannotAddRelatedInstance', 'mds.error', response); }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); updatePostData = function (filter, postdata) { $('#' + attrs.id).jqGrid('setGridParam', { postData: { filters: ''} }); postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); $.extend(postdata, { filters: angular.toJson(filter) }); $('#' + attrs.id).jqGrid('setGridParam', { search: true, postData: postdata }); $timeout(function() { $('#' + attrs.id).jqGrid().trigger("reloadGrid"); }, 300); }; scope.$watch('field.value.removedIds', function (newValue) { postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); if (postdata !== undefined) { if (postdata.filters !== undefined) { filter = JSON.parse(postdata.filters); } if (newValue !== null) { filter.removedIds = newValue; } updatePostData(filter, postdata); } }, true); scope.$watch('field.value.addedIds', function (newValue) { postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); if (postdata !== undefined) { if (postdata.filters !== undefined) { filter = JSON.parse(postdata.filters); } if (newValue !== null) { filter.addedIds = newValue; } updatePostData(filter, postdata); } }, true); scope.$watch('field.value.addedNewRecords', function (newValue) { postdata = $('#' + attrs.id).jqGrid('getGridParam','postData'); if (postdata !== undefined) { if (postdata.filters !== undefined) { filter = JSON.parse(postdata.filters); } if (newValue !== null) { filter.addedNewRecords = newValue; } updatePostData(filter, postdata); } }, true); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridWidth(gridId); }, 200); }); } }; }); directives.directive('relatedfieldsform', function () { return { restrict: 'A', scope: false, require: 'ngModel', replace: true, link: function (scope, element, attrs, ngModel) { scope.$parent.$watch(attrs.ngModel, function (newValue, oldValue, scope) { scope.fields = newValue; if (scope.newRelatedFields !== undefined && scope.newRelatedFields !== null) { scope.fields = scope.newRelatedFields; } }); }, templateUrl: '../mds/resources/partials/widgets/entityInstanceFieldsRelated.html' }; }); directives.directive('editrelatedfieldsform', function () { return { restrict: 'A', scope: false, require: 'ngModel', replace: true, link: function(scope, element, attrs, ngModel) { scope.$parent.$watch(attrs.ngModel, function () { scope.fields = scope.editRelatedFields; if (scope.editRelatedFields !== undefined && scope.editRelatedFields !== null) { scope.fields = scope.editRelatedFields; } }); }, templateUrl: '../mds/resources/partials/widgets/entityInstanceFieldsRelated.html' }; }); directives.directive('showRelationsGrid', function () { return { restrict: 'A', link: function (scope, element, attrs) { var isHiddenGrid, elem = angular.element(element), gridId = attrs.showRelationsGrid, gridHide = attrs.gridHide, setHiddenGrid = function () { elem.children().removeClass('fa-angle-double-up'); elem.children().addClass('fa-angle-double-down'); $('#' + gridId).jqGrid('setGridState','hidden'); $('body #instance_' + gridId).addClass('hiddengrid'); }, setVisibleGrid = function () { elem.children().removeClass('fa-angle-double-down'); elem.children().addClass('fa-angle-double-up'); $('#' + gridId).jqGrid('setGridState','visible'); $('body #instance_' + gridId).removeClass('hiddengrid').delay(500).fadeIn("slow"); }; elem.on('click', function () { isHiddenGrid = $('#' + gridId).jqGrid('getGridParam','hiddengrid'); $('#' + gridId).jqGrid('setGridParam', { hiddengrid: !isHiddenGrid }); if (isHiddenGrid) { setVisibleGrid(); } else { setHiddenGrid(); } }); } }; }); directives.directive('multiselectDropdown', function () { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs) { var selectAll = scope.msg('mds.btn.selectAll'), target = attrs.targetTable, noSelectedFields = true; if (!target) { target = 'instancesTable'; } element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group" />', maxHeight : false, buttonText : function() { return scope.msg('mds.btn.fields'); }, selectAllText: selectAll, selectAllValue: 'multiselect-all', includeSelectAllOption: true, onChange: function (optionElement, checked) { if (optionElement) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } } element.change(); if (optionElement) { var name = scope.getFieldName(optionElement.text()); // don't act for fields show automatically in trash and history if (scope.autoDisplayFields.indexOf(name) === -1) { scope.addFieldForDataBrowser(name, checked); } } else { scope.addFieldsForDataBrowser(checked); } noSelectedFields = true; angular.forEach(element[0], function(field) { var name = scope.getFieldName(field.label); if (name) { // Change this name if it is reserved for jqgrid. name = changeIfReservedFieldName(name); if (field.selected){ $("#" + target).jqGrid('showCol', name); noSelectedFields = false; } else { $("#" + target).jqGrid('hideCol', name); } } }); if (noSelectedFields) { $('.page_' + target + '_center').hide(); $('.ui-jqgrid-status-label').removeClass('hidden'); $('.ui-jqgrid-hdiv').hide(); } else { $('.page_' + target + '_center').show(); $('.ui-jqgrid-status-label').addClass('hidden'); $('.ui-jqgrid-hdiv').show(); } }, onDropdownHide: function(event) { $("#" + target).trigger("resize"); } }); scope.$watch(function () { return element[0].length; }, function () { element.multiselect('rebuild'); }); $(element).parent().on("click", function () { element.multiselect('rebuild'); }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); } }; }); /** * Displays instance history data using jqGrid */ directives.directive('instanceHistoryGrid', function($compile, $http, $templateCache, $timeout) { return { restrict: 'A', link: function(scope, element, attrs) { var elem = angular.element(element), eventResize, eventChange, gridId = attrs.id, firstLoad = true; $.ajax({ type: "GET", url: "../mds/entities/" + scope.selectedEntity.id + "/entityFields", dataType: "json", success: function(result) { var colModel = [], i, noSelectedFields = true, spanText, noSelectedFieldsText = scope.msg('mds.dataBrowsing.noSelectedFieldsInfo'); colModel.push({ name: "", width: 28, formatter: function () { return "<a><i class='fa fa-lg fa-refresh'></i></a>"; }, sortable: false }); buildGridColModel(colModel, result, scope, true, false); elem.jqGrid({ url: "../mds/instances/" + scope.selectedEntity.id + "/" + scope.instanceId + "/history", datatype: 'json', jsonReader:{ repeatitems:false }, onSelectRow: function (id) { var myGrid = $('#historyTable'), cellValue = myGrid.jqGrid ('getCell', id, 'Changes'); if (cellValue === "Is Active") { scope.backToInstance(); } else { scope.historyInstance(id); } }, rowNum: scope.entityAdvanced.userPreferences.gridRowsNumber, onPaging: function (pgButton) { handleGridPagination(pgButton, $(this.p.pager), scope); }, resizeStop: function (width, index) { handleColumnResize('#instanceHistoryTable', gridId, index, width, scope); }, headertitles: true, colModel: colModel, pager: '#' + attrs.instanceHistoryGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { spanText = $('<span>').addClass('ui-jqgrid-status-label ui-jqgrid ui-widget hidden'); spanText.append(noSelectedFieldsText).css({padding: '3px 15px'}); $('#instanceHistoryTable .ui-paging-info').append(spanText); $('.ui-jqgrid-status-label').addClass('hidden'); $('#pageInstanceHistoryTable_center').addClass('page_historyTable_center'); if (scope.selectedFields !== undefined && scope.selectedFields.length > 0) { noSelectedFields = false; } else { noSelectedFields = true; $('#pageInstanceHistoryTable_center').hide(); $('#instanceHistoryTable .ui-jqgrid-status-label').removeClass('hidden'); } if ($('#historyTable').getGridParam('records') > 0) { $('#pageInstanceHistoryTable_center').show(); $('#instanceHistoryTable .ui-jqgrid-hdiv').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { if (noSelectedFields) { $('#pageInstanceHistoryTable_center').hide(); $('#instanceHistoryTable .ui-jqgrid-hdiv').hide(); } $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } $('#instanceHistoryTable .ui-jqgrid-hdiv').addClass('table-lightblue'); $('#instanceHistoryTable .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 550); if (firstLoad) { resizeIfNarrow(gridId); firstLoad = false; } } }); elem.on('jqGridSortCol', function (e, fieldName) { e.target.p.sortname = backToReservedFieldName(fieldName); }); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); resizeGridHeight(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 200); }); } }); } }; }); /** * Displays entity instance trash data using jqGrid */ directives.directive('instanceTrashGrid', function ($timeout) { return { restrict: 'A', link: function (scope, element, attrs) { var elem = angular.element(element), eventResize, eventChange, gridId = attrs.id, firstLoad = true; $.ajax({ type: "GET", url: "../mds/entities/" + scope.selectedEntity.id + "/entityFields", dataType: "json", success: function (result) { var colModel = [], i, noSelectedFields = true, spanText, noSelectedFieldsText = scope.msg('mds.dataBrowsing.noSelectedFieldsInfo'); buildGridColModel(colModel, result, scope, true, false); elem.jqGrid({ url: "../mds/entities/" + scope.selectedEntity.id + "/trash", headers: { 'Accept': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded' }, datatype: 'json', mtype: "GET", postData: { fields: JSON.stringify(scope.lookupBy) }, jsonReader: { repeatitems: false }, rowNum: scope.entityAdvanced.userPreferences.gridRowsNumber, onPaging: function (pgButton) { handleGridPagination(pgButton, $(this.p.pager), scope); }, onSelectRow: function (id) { firstLoad = true; scope.trashInstance(id); }, resizeStop: function (width, index) { handleColumnResize('#instanceTrashTable', gridId, index, width, scope); }, loadonce: false, headertitles: true, colModel: colModel, pager: '#' + attrs.instanceTrashGrid, viewrecords: true, autowidth: true, shrinkToFit: false, gridComplete: function () { spanText = $('<span>').addClass('ui-jqgrid-status-label ui-jqgrid ui-widget hidden'); spanText.append(noSelectedFieldsText).css({padding: '3px 15px'}); $('#instanceTrashTable .ui-paging-info').append(spanText); $('.ui-jqgrid-status-label').addClass('hidden'); $('#pageInstanceTrashTable_center').addClass('page_trashTable_center'); if (scope.selectedFields !== undefined && scope.selectedFields.length > 0) { noSelectedFields = false; } else { noSelectedFields = true; $('#pageInstanceTrashTable_center').hide(); $('#instanceTrashTable .ui-jqgrid-status-label').removeClass('hidden'); } if ($('#trashTable').getGridParam('records') > 0) { $('#pageInstanceTrashTable_center').show(); $('#instanceTrashTable .ui-jqgrid-hdiv').show(); $('#gbox_' + gridId + ' .jqgfirstrow').css('height','0'); } else { if (noSelectedFields) { $('#pageInstanceTrashTable_center').hide(); $('#instanceTrashTable .ui-jqgrid-hdiv').hide(); } $('#gbox_' + gridId + ' .jqgfirstrow').css('height','1px'); } $('#instanceTrashTable .ui-jqgrid-hdiv').addClass("table-lightblue"); $('#instanceTrashTable .ui-jqgrid-btable').addClass("table-lightblue"); $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 550); if (firstLoad) { resizeIfNarrow(gridId); firstLoad = false; } } }); elem.on('jqGridSortCol', function (e, fieldName) { // For correct sorting in jqgrid we need to convert back to the original name e.target.p.sortname = backToReservedFieldName(fieldName); }); $(window).on('resize', function() { clearTimeout(eventResize); eventResize = $timeout(function() { $(".ui-layout-content").scrollTop(0); resizeGridWidth(gridId); resizeGridHeight(gridId); }, 200); }).trigger('resize'); $('#inner-center').on('change', function() { clearTimeout(eventChange); eventChange = $timeout(function() { resizeGridHeight(gridId); resizeGridWidth(gridId); }, 200); }); } }); } }; }); directives.directive('droppable', function () { return { scope: { drop: '&' }, link: function (scope, element) { var el = element[0]; el.addEventListener('dragover', function (e) { e.dataTransfer.dropEffect = 'move'; if (e.preventDefault) { e.preventDefault(); } this.classList.add('over'); return false; }, false); el.addEventListener('dragenter', function () { this.classList.add('over'); return false; }, false); el.addEventListener('dragleave', function () { this.classList.remove('over'); return false; }, false); el.addEventListener('drop', function (e) { var fieldId = e.dataTransfer.getData('Text'), containerId = this.id; if (e.stopPropagation) { e.stopPropagation(); } scope.$apply(function (scope) { var fn = scope.drop(); if (_.isFunction(fn)) { fn(fieldId, containerId); } }); return false; }, false); } }; }); /** * Add auto saving for field properties. */ directives.directive('mdsAutoSaveFieldChange', function (Entities) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var func = attr.mdsAutoSaveFieldChange || 'focusout'; angular.element(element).on(func, function () { var viewScope = findCurrentScope(scope, 'draft'), fieldPath = attr.mdsPath, fieldId = attr.mdsFieldId, entity, value; if (fieldPath === undefined) { fieldPath = attr.ngModel; fieldPath = fieldPath.substring(fieldPath.indexOf('.') + 1); } value = ngModel.$modelValue; viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); }); } }; }); /* * Add auto saving for field properties. */ directives.directive('mdsAutoSaveAdvancedChange', function (Entities) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ngModel) { var func = attr.mdsAutoSaveAdvancedChange || 'focusout'; angular.element(element).on(func, function () { var viewScope = findCurrentScope(scope, 'draft'), advancedPath = attr.mdsPath, entity, value; if (advancedPath === undefined) { advancedPath = attr.ngModel; advancedPath = advancedPath.substring(advancedPath.indexOf('.') + 1); } value = _.isBoolean(ngModel.$modelValue) ? !ngModel.$modelValue : ngModel.$modelValue; viewScope.draft({ edit: true, values: { path: advancedPath, advanced: true, value: [value] } }); }); } }; }); /** * Add auto saving for field properties. */ directives.directive('mdsAutoSaveBtnSelectChange', function (Entities) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fieldId = attrs.mdsFieldId, criterionId = attrs.mdsCriterionId, entity, value; elm.children('ul').on('click', function () { value = scope.selectedRegexPattern; if ((value !== null && value.length === 0) || value === null) { value = ""; } viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); }); } }; }); /** * Sets a callback function to select2 on('change') event. */ directives.directive('select2NgChange', function () { return { restrict: 'A', link: function (scope, element, attrs) { var elem = angular.element(element), callback = elem.attr('select2-ng-change'); elem.on('change', scope[callback]); } }; }); directives.directive('multiselectList', function () { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs) { var fieldSettings = scope.field.settings, comboboxValues = scope.getComboboxValues(fieldSettings), typeField = attrs.multiselectList; element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group" />', maxHeight : false, numberDisplayed: 3, buttonText : function(options) { if (options.length === 0) { return scope.msg('mds.form.label.select'); } else { if (options.length > this.numberDisplayed) { return options.length + ' ' + scope.msg('mds.form.label.selected'); } else { var selected = ''; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); selected += label + ', '; }); selected = selected.substr(0, selected.length - 2); return (selected === '') ? scope.msg('mds.form.label.select'): selected; } } }, onChange: function (optionElement, checked) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } element.change(); } }); $("#saveoption" + scope.field.id).on("click", function () { element.multiselect('rebuild'); }); scope.$watch(function () { return element[0].length; }, function () { if (typeField === 'owner') { element.multiselect('rebuild'); } else { var comboboxValues = scope.getComboboxValues(scope.field.settings); if (comboboxValues !== null && comboboxValues !== undefined) { if (comboboxValues.length > 0 && comboboxValues[0] !== '') { element.multiselect('enable'); } else { element.multiselect('disable'); } element.multiselect('rebuild'); } } }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); } }; }); directives.directive('defaultMultiselectList', function (Entities) { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs, ngModel) { var entity, value, resetDefaultValue, checkIfNeedReset, viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fieldId = attrs.mdsFieldId, typeField = attrs.defaultMultiselectList; element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group" />', maxHeight : false, numberDisplayed: 3, buttonText : function(options) { if (options.length === 0) { return scope.msg('mds.form.label.select'); } else { if (options.length > this.numberDisplayed) { return options.length + ' ' + scope.msg('mds.form.label.selected'); } else { var selected = ''; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); selected += label + ', '; }); selected = selected.substr(0, selected.length - 2); return (selected === '') ? scope.msg('mds.form.label.select') : selected; } } }, onChange: function (optionElement, checked) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } if (fieldPath === undefined) { fieldPath = attrs.ngModel; fieldPath = fieldPath.substring(fieldPath.indexOf('.') + 1); } value = ngModel.$modelValue; if ((value !== null && value.length === 0) || value === null) { value = ""; } viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); element.change(); } }); scope.$watch("field.settings[0].value", function( newValue, oldValue ) { if (newValue !== oldValue) { var includeSelectedValues = function (newList, selectedValues) { var result, valueOnList = function (theList, val) { if (_.contains(theList, val)) { result = true; } else { result = false; } return (result); }; if(selectedValues !== null && selectedValues !== undefined && $.isArray(selectedValues) && selectedValues.length > 0) { $.each(selectedValues, function (i, val) { return (valueOnList(newList, val)); }); } else if ($.isArray(newList) && selectedValues !== null && selectedValues !== undefined && selectedValues.length > 0) { return (valueOnList(newList, selectedValues)); } else { result = true; } return result; }; if (!includeSelectedValues(newValue, ngModel.$viewValue)) { resetDefaultValue(); } if (scope.field.settings[0].value !== null && (scope.field.settings[0].value.length > 0 && scope.field.settings[0].value[0].toString().trim().length > 0)) { element.multiselect('enable'); } else { element.multiselect('disable'); } } }, true); resetDefaultValue = function () { fieldId = attrs.mdsFieldId; value = ''; viewScope.draft({ edit: true, values: { path: "basic.defaultValue", fieldId: fieldId, value: [value] } }); scope.field.basic.defaultValue = ''; $('#reset-default-value-combobox' + scope.field.id).fadeIn("slow"); setTimeout(function () { $('#reset-default-value-combobox' + scope.field.id).fadeOut("slow"); }, 8000); element.multiselect('updateButtonText'); element.children('option').each(function() { $(this).prop('selected', false); }); element.multiselect('refresh'); }; checkIfNeedReset = function () { return scope.field.basic.defaultValue !== null && scope.field.basic.defaultValue.length > 0 && scope.field.basic.defaultValue !== ''; }; scope.$watch(function () { return element[0].length; }, function () { element.multiselect('rebuild'); }); element.siblings('div').on('click', function () { element.multiselect('rebuild'); }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); $("#mdsfieldsettings_" + scope.field.id + '_1').on("click", function () { if (checkIfNeedReset()) { resetDefaultValue(); } }); $("#mdsfieldsettings_" + scope.field.id + '_2').on("click", function () { if (checkIfNeedReset()) { resetDefaultValue(); } }); } }; }); directives.directive('securityList', function () { return { restrict: 'A', require : 'ngModel', link: function (scope, element, attrs, ngModel) { element.multiselect({ buttonClass : 'btn btn-default', buttonWidth : 'auto', buttonContainer : '<div class="btn-group pull-left" />', maxHeight : false, numberDisplayed: 3, buttonText : function(options) { if (options.length === 0) { return scope.msg('mds.form.label.select'); } else { if (options.length > this.numberDisplayed) { return options.length + ' ' + scope.msg('mds.form.label.selected'); } else { var selected = ''; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); selected += label + ', '; }); return selected.substr(0, selected.length - 2); } } }, onChange: function (optionElement, checked) { optionElement.removeAttr('selected'); if (checked) { optionElement.prop('selected', true); } element.change(); } }); scope.$watch(function () { return element[0].length; }, function () { element.multiselect('rebuild'); }); element.siblings('div').on('click', function () { element.multiselect('rebuild'); }); scope.$watch(attrs.ngModel, function () { element.multiselect('refresh'); }); } }; }); directives.directive('integerValidity', function() { var INTEGER_REGEXP = new RegExp('^([-][1-9])?(\\d)*$'), TWOZERO_REGEXP = new RegExp('^(0+\\d+)$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || INTEGER_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('integer', true); originalValue = viewValue; viewValue = parseInt(viewValue, 10); if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('integer', false); return viewValue; } }); } }; }); directives.directive('shortValidity', function() { var INTEGER_REGEXP = new RegExp('^([-][1-9])?(\\d)*$'), TWOZERO_REGEXP = new RegExp('^(0+\\d+)$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || INTEGER_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('short', true); originalValue = viewValue; viewValue = parseInt(viewValue, 10); if (viewValue >= 32767 || viewValue <= -32768) { ctrl.$setValidity('short', false); } if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('short', false); return viewValue; } }); } }; }); directives.directive('decimalValidity', function() { var DECIMAL_REGEXP = new RegExp('^[-]?\\d+(\\.\\d+)?$'), TWOZERO_REGEXP = new RegExp('^[-]?0+\\d+(\\.\\d+)?$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || DECIMAL_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('decimal', true); originalValue = viewValue; viewValue = parseFloat(viewValue); if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('decimal', false); return viewValue; } }); } }; }); directives.directive('floatValidity', function() { var FLOAT_REGEXP = new RegExp('^[-]?\\d+(\\.\\d+)?$'), TWOZERO_REGEXP = new RegExp('^[-]?0+\\d+(\\.\\d+)?$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || FLOAT_REGEXP.test(viewValue)) { // it is valid ctrl.$setValidity('float', true); originalValue = viewValue; viewValue = parseFloat(viewValue); if (isNaN(viewValue)) { viewValue = ''; } if (TWOZERO_REGEXP.test(originalValue)) { setTimeout(function () { elm.val(viewValue); }, 1000); } return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('float', false); return viewValue; } }); } }; }); directives.directive('charValidity', function() { var CHAR_REGEXP = new RegExp('^.$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if(viewValue === '' || CHAR_REGEXP.test(viewValue)) { ctrl.$setValidity('char', true); originalValue = viewValue; return viewValue; } else { ctrl.$setValidity('char', false); return viewValue; } }); } }; }); directives.directive('uuidValidity', function() { var UUID_REGEXP = new RegExp('^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$'); return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), originalValue; ctrl.$parsers.unshift(function(viewValue) { if(viewValue === '' || UUID_REGEXP.test(viewValue)) { ctrl.$setValidity('uuid', true); return viewValue; } else { ctrl.$setValidity('uuid', false); return viewValue; } }); } }; }); directives.directive('insetValidity', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var inset = '', checkInset = function (inset, viewValue) { var result, insetParameters = inset.split(' '); if($.isArray(insetParameters)) { $.each(insetParameters, function (i, val) { if (parseFloat(val) === parseFloat(viewValue)) { result = true; } else { result = false; } return (!result); }); } else { result = false; } return result; }; if (scope.field.validation.criteria[attrs.insetValidity] !== undefined && scope.field.validation.criteria[attrs.insetValidity].enabled) { inset = scope.field.validation.criteria[attrs.insetValidity].value; } if (ctrl.$viewValue === '' || inset === '' || checkInset(inset, ctrl.$viewValue)) { ctrl.$setValidity('insetNum', true); return viewValue; } else { ctrl.$setValidity('insetNum', false); return viewValue; } }); } }; }); directives.directive('outsetValidity', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var outset = '', checkOutset = function (outset, viewValue) { var result, outsetParameters = outset.split(' '); if($.isArray(outsetParameters)) { $.each(outsetParameters, function (i, val) { if (parseFloat(val) === parseFloat(viewValue)) { result = true; } else { result = false; } return (!result); }); } else { result = false; } return result; }; if (scope.field.validation.criteria[attrs.outsetValidity] !== undefined && scope.field.validation.criteria[attrs.outsetValidity].enabled) { outset = scope.field.validation.criteria[attrs.outsetValidity].value; } if (ctrl.$viewValue === '' || outset === '' || !checkOutset(outset, ctrl.$viewValue)) { ctrl.$setValidity('outsetNum', true); return viewValue; } else { ctrl.$setValidity('outsetNum', false); return viewValue; } }); } }; }); directives.directive('maxValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var max = ''; if (scope.field.validation.criteria[attrs.maxValidity] !== undefined && scope.field.validation.criteria[attrs.maxValidity].enabled) { max = scope.field.validation.criteria[attrs.maxValidity].value; } if (ctrl.$viewValue === '' || max === '' || parseFloat(ctrl.$viewValue) <= parseFloat(max)) { ctrl.$setValidity('max', true); return viewValue; } else { ctrl.$setValidity('max', false); return viewValue; } }); } }; }); directives.directive('minValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var min = ''; if (scope.field.validation.criteria[attrs.minValidity] !== undefined && scope.field.validation.criteria[attrs.minValidity].enabled) { min = scope.field.validation.criteria[attrs.minValidity].value; } if (ctrl.$viewValue === '' || min === '' || parseFloat(ctrl.$viewValue) >= parseFloat(min)) { ctrl.$setValidity('min', true); return viewValue; } else { ctrl.$setValidity('min', false); return viewValue; } }); } }; }); directives.directive('illegalValueValidity', function() { var RESERVED_WORDS = [ 'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const*', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extends', 'false', 'final', 'finally', 'float', 'for', 'goto*', 'if', 'int', 'interface', 'instanceof', 'implements', 'import', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'strictfp', 'super', 'synchronized', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'void', 'volatile', 'while' ], LEGAL_REGEXP = /^[\w]+$/; return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var validateReservedWords; validateReservedWords = function (viewValue) { if (ctrl.$viewValue === '' || attrs.illegalValueValidity === 'true' || (LEGAL_REGEXP.test(ctrl.$viewValue) && $.inArray(ctrl.$viewValue, RESERVED_WORDS) === -1) ) { // it is valid ctrl.$setValidity('illegalvalue', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('illegalvalue', false); return ''; } }; ctrl.$parsers.unshift(validateReservedWords); scope.$watch("field.settings[1].value", function(newValue, oldValue) { if (newValue !== oldValue) { ctrl.$setViewValue(ctrl.$viewValue); } }); } }; }); directives.directive('showAddOptionInput', function() { return { restrict: 'A', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), showAddOptionInput = elm.siblings('span'); elm.on('click', function () { showAddOptionInput.removeClass('hidden'); showAddOptionInput.children('input').val(''); }); } }; }); directives.directive('addOptionCombobox', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var distinct, elm = angular.element(element), fieldSettings = scope.field.settings, modelValueArray = scope.getComboboxValues(fieldSettings), parent = elm.parent(); distinct = function(mvArray, inputValue) { var result; if ($.inArray(inputValue, mvArray) !== -1 && inputValue !== null) { result = false; } else { result = true; } return result; }; ctrl.$parsers.unshift(function(viewValue) { if (viewValue === '' || distinct(modelValueArray, viewValue)) { ctrl.$setValidity('uniqueValue', true); return viewValue; } else { ctrl.$setValidity('uniqueValue', false); return undefined; } }); elm.siblings('a').on('click', function () { scope.fieldValue = []; if (scope.field !== null && scope.newOptionValue !== undefined && scope.newOptionValue !== '') { if (scope.field.settings[2].value) { //if multiselect if (scope.field.value !== null) { if (!$.isArray(scope.field.value)) { scope.fieldValue = $.makeArray(scope.field.value); } else { angular.forEach(scope.field.value, function(val) { scope.fieldValue.push(val); }); } } else { scope.fieldValue = []; } scope.fieldValue.push(scope.newOptionValue); scope.field.value = scope.fieldValue; } else { scope.field.value = scope.newOptionValue; } scope.field.settings[0].value.push(scope.newOptionValue); scope.newOptionValue = ''; parent.addClass('hidden'); elm.resetForm(); } }); } }; }); directives.directive('mdsBasicUpdateMap', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldMapModel = attrs.mdsPath, fieldPath = fieldMapModel, fPath = fieldPath.substring(fieldPath.indexOf('.') + 1), fieldId = attrs.mdsFieldId, fieldMaps, value, entity, keyIndex; scope.$watch(attrs.ngModel, function (viewValue) { fieldMaps = scope.getMap(fieldId); value = scope.mapToString(fieldMaps.fieldMap); keyIndex = parseInt(attrs.mdsBasicUpdateMap, 10); var distinct = function(inputValue, mvArray) { var result; if ($.inArray(inputValue, mvArray) !== -1 && inputValue !== null) { result = false; } else { result = true; } return result; }, keysList = function () { var resultKeysList = []; angular.forEach(fieldMaps.fieldMap, function (map, index) { if (map !== null && map.key !== undefined && map.key.toString() !== '') { if (index !== keyIndex) { resultKeysList.push(map.key.toString()); } } }, resultKeysList); return resultKeysList; }; if ((!elm.parent().parent().find('.has-error').length && elm.hasClass('map-value')) || (viewValue === '' && elm.hasClass('map-key')) || (distinct(viewValue, keysList()) && elm.hasClass('map-key'))) { if ((value !== null && value.length === 0) || value === null) { value = ""; } if (scope.field.basic.defaultValue !== value) { scope.field.basic.defaultValue = value; viewScope.draft({ edit: true, values: { path: fPath, fieldId: fieldId, value: [value] } }); } } }); } }; }); directives.directive('mdsBasicDeleteMap', function () { return { link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fPath = fieldPath.substring(fieldPath.indexOf('.') + 1), fieldId = attrs.mdsFieldId, fieldMaps, value, entity, keyIndex; elm.on('click', function (viewValue) { keyIndex = parseInt(attrs.mdsBasicDeleteMap, 10); scope.deleteElementMap(fieldId, keyIndex); fieldMaps = scope.getMap(fieldId); value = scope.mapToString(fieldMaps.fieldMap); if ((value !== null && value.length === 0) || value === null) { value = ""; } scope.safeApply(function () { scope.field.basic.defaultValue = value; }); viewScope.draft({ edit: true, values: { path: fPath, fieldId: fieldId, value: [value] } }); }); } }; }); directives.directive('mdsUpdateMap', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), fieldId = attrs.mdsFieldId, fieldMaps, value, keyIndex, keysList, distinct; scope.$watch(attrs.ngModel, function (viewValue) { keyIndex = parseInt(attrs.mdsUpdateMap, 10); fieldMaps = scope.getMap(fieldId); value = scope.mapToMapObject(fieldMaps.fieldMap); var distinct = function(inputValue, mvArray) { var result; if ($.inArray(inputValue, mvArray) !== -1 && inputValue !== null) { result = false; } else { result = true; } return result; }, keysList = function () { var resultKeysList = []; angular.forEach(fieldMaps.fieldMap, function (map, index) { if (map !== null && map.key !== undefined && map.key.toString() !== '') { if (index !== keyIndex) { resultKeysList.push(map.key.toString()); } } }, resultKeysList); return resultKeysList; }; if ((elm.parent().parent().find('.has-error').length < 1 && elm.hasClass('map-value')) || (viewValue === '' && elm.hasClass('map-key')) || (distinct(viewValue, keysList()) && elm.hasClass('map-key'))) { if ((value !== null && value.length === 0) || value === null) { value = ""; } scope.field.value = value; } }); elm.siblings('a').on('click', function () { if (elm.hasClass('map-key')) { keyIndex = parseInt(attrs.mdsUpdateMap, 10); scope.deleteElementMap(fieldId, keyIndex); fieldMaps = scope.getMap(fieldId); value = scope.mapToMapObject(fieldMaps.fieldMap); if ((value !== null && value.length === 0) || value === null) { value = ""; } scope.safeApply(function () { scope.field.value = value; }); } }); } }; }); directives.directive('mapValidation', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var required = attrs.mapValidation; scope.$watch(attrs.ngModel, function (viewValue) { if (required.toString() === 'true') { if (viewValue !== '' || viewValue.toString().trim().length > 0) { ctrl.$setValidity('required', true); return viewValue; } else { ctrl.$setValidity('required', false); return viewValue; } } else { ctrl.$setValidity('required', true); return viewValue; } }); } }; }); directives.directive('patternValidity', function() { var PATTERN_REGEXP; return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { if (attrs.patternValidity !== undefined && scope.field.validation.criteria[attrs.patternValidity].enabled) { PATTERN_REGEXP = new RegExp(scope.field.validation.criteria[attrs.patternValidity].value); } else { PATTERN_REGEXP = new RegExp(''); } if (ctrl.$viewValue === '' || PATTERN_REGEXP.test(ctrl.$viewValue)) { // it is valid ctrl.$setValidity('pattern', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('pattern', false); return undefined; } }); } }; }); directives.directive('dateTimeValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), valueDate, valueTime; ctrl.$parsers.unshift(function(viewValue) { valueDate = ctrl.$viewValue.slice(0, 16); if (ctrl.$viewValue.length > 10) { valueTime = ctrl.$viewValue.slice(11, ctrl.$viewValue.length); } if (ctrl.$viewValue === '' || (moment(valueDate,'').isValid() && ($.datepicker.parseTime('HH:mm z', valueTime, '') !== false))) { // it is valid ctrl.$setValidity('datetime', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('datetime', false); return undefined; } }); } }; }); directives.directive('dateValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element); ctrl.$parsers.unshift(function(viewValue) { if (ctrl.$viewValue === '' || moment(ctrl.$viewValue,'').isValid()) { // it is valid ctrl.$setValidity('date', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('date', false); return undefined; } }); } }; }); directives.directive('timeValidity', function() { return { require: 'ngModel', link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), valueTime; ctrl.$parsers.unshift(function(viewValue) { valueTime = ctrl.$viewValue; if (ctrl.$viewValue === '' || $.datepicker.parseTime('HH:mm', valueTime, '') !== false) { // it is valid ctrl.$setValidity('time', true); return viewValue; } else { // it is invalid, return undefined (no model update) ctrl.$setValidity('time', false); return undefined; } }); } }; }); directives.directive('mdsBasicDeleteListValue', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = elm.parent().parent().attr('mds-path'), fieldId = attrs.mdsFieldId, value, keyIndex; elm.on('click', function (e) { keyIndex = parseInt(attrs.mdsBasicDeleteListValue, 10); value = scope.deleteElementList(ctrl.$viewValue, keyIndex); viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); }); } }; }); directives.directive('defaultFieldNameValid', function() { return { link: function(scope, element, attrs, ctrl) { var elm = angular.element(element), fieldName = attrs.defaultFieldNameValid; scope.defaultValueValid.push({ name: fieldName, valid: true }); scope.$watch(function () { return element[0].classList.length; }, function () { var fieldName = attrs.defaultFieldNameValid; if (element.hasClass('has-error') || element.hasClass('ng-invalid')) { scope.setBasicDefaultValueValid(false, fieldName); } else { scope.setBasicDefaultValueValid(true, fieldName); } }); } }; }); directives.directive('mdsUpdateCriterion', function () { return { require: 'ngModel', link: function(scope, element, attrs, ctrl, ngModel) { var elm = angular.element(element), viewScope = findCurrentScope(scope, 'draft'), fieldPath = attrs.mdsPath, fieldId = attrs.mdsFieldId, criterionId = attrs.mdsCriterionId, criterionName = attrs.mdsUpdateCriterion, value; scope.$watch(attrs.ngModel, function (viewValue) { if ((!elm.parent().parent().find('.has-error').length || viewValue === '') && (criterionName === 'mds.field.validation.cannotBeInSet' || criterionName === 'mds.field.validation.mustBeInSet')) { value = scope.getCriterionValues(fieldId, criterionName); if ((value !== null && value.length === 0) || value === null) { value = ""; } if (scope.field.validation.criteria[criterionId].value !== value) { scope.field.validation.criteria[criterionId].value = value; viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); } } }); elm.siblings('a').on('click', function () { value = scope.deleteValueList(fieldId, criterionName, parseInt(attrs.mdsValueIndex, 10)); if (scope.field.validation.criteria[criterionId].value !== value) { scope.safeApply(function () { scope.field.validation.criteria[criterionId].value = value; }); viewScope.draft({ edit: true, values: { path: fieldPath, fieldId: fieldId, value: [value] } }); } }); } }; }); directives.directive('mdsContentTooltip', function () { return { restrict: 'A', link: function (scope, element, attrs) { var elm = angular.element(element), fieldId = attrs.mdsFieldId, fieldType = attrs.mdsContentTooltip; $(element).popover({ placement: 'bottom', trigger: 'hover', html: true, title: scope.msg('mds.info.' + fieldType), content: function () { return $('#content' + fieldId).html(); } }); } }; }); directives.directive('mdsIndeterminate', function() { return { restrict: 'A', link: function(scope, element, attributes) { scope.$watch(attributes.mdsIndeterminate, function (value) { element.prop('indeterminate', !!value); }); } }; }); directives.directive('mdsVisitedInput', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ctrl) { var elm = angular.element(element), fieldId = attrs.mdsFieldId, fieldName = attrs.mdsFieldName, typingTimer, ngFormNameAttrSuffix = "form"; elm.on('keyup', function () { scope.$apply(function () { elm.siblings('#visited-hint-' + fieldId).addClass('hidden'); if (scope[fieldName + ngFormNameAttrSuffix] !== undefined) { scope[fieldName + ngFormNameAttrSuffix].$dirty = false; } }); clearTimeout(typingTimer); typingTimer = setTimeout( function() { elm.siblings('#visited-hint-' + fieldId).removeClass('hidden'); scope.$apply(function () { if (scope[fieldName + ngFormNameAttrSuffix] !== undefined) { scope[fieldName + ngFormNameAttrSuffix].$dirty = true; } }); }, 1500); }); elm.on("blur", function() { scope.$apply(function () { elm.siblings('#visited-hint-' + fieldId).removeClass('hidden'); if (scope[fieldName + ngFormNameAttrSuffix] !== undefined) { scope[fieldName + ngFormNameAttrSuffix].$dirty = true; } }); }); } }; }); directives.directive('mdsFileChanged', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('change', function(e){ scope.$apply(function(){ scope[attrs.mdsFileChanged](e.target.files[0]); }); }); } }; }); directives.directive('tabLayoutWithMdsGrid', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) { return function(scope, element, attrs) { $http.get('../mds/resources/partials/tabLayoutWithMdsGrid.html', { cache: $templateCache }).success(function(response) { var contents = element.html(response).contents(); element.replaceWith($compile(contents)(scope)); }); }; }]); directives.directive('embeddedMdsFilters', function($http, $templateCache, $compile) { return function(scope, element, attrs) { $http.get('../mds/resources/partials/embeddedMdsFilters.html', { cache: $templateCache }).success(function(response) { var contents = element.html(response).contents(); $compile(contents)(scope); }); }; }); directives.directive('preventNameConflicts', function($compile) { return { restrict: 'A', priority: 10000, terminal: true, link: function(scope, element, attrs) { attrs.$set('name', attrs.name + 'form'); attrs.$set('preventNameConflicts', null); $compile(element)(scope); } }; }); }());
koshalt/motech
platform/mds/mds-web/src/main/resources/webapp/js/directives.js
JavaScript
bsd-3-clause
161,992
/* line 1 "./ragel/tsdp_parser_header_M.jrl" */ /* * Copyright (C) 2012-2018 Doubango Telecom <http://www.doubango.org> * License: BSD * This file is part of Open Source sipML5 solution <http://www.sipml5.org> */ tsdp_header_M.prototype = Object.create(tsdp_header.prototype); /* line 49 "./ragel/tsdp_parser_header_M.jrl" */ /* line 17 "./src/headers/tsdp_header_M.js" */ _tsdp_machine_parser_header_M_actions = [ 0, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4 ]; _tsdp_machine_parser_header_M_key_offsets = [ 0, 0, 1, 3, 18, 33, 35, 39, 53, 54, 68, 70, 73, 88, 88, 103 ]; _tsdp_machine_parser_header_M_trans_keys = [ 109, 32, 61, 32, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 32, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 48, 57, 32, 47, 48, 57, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 10, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 48, 57, 32, 48, 57, 13, 32, 33, 37, 39, 47, 126, 42, 43, 45, 57, 65, 90, 95, 122, 13, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 13, 32, 33, 37, 39, 126, 42, 43, 45, 46, 48, 57, 65, 90, 95, 122, 0 ]; _tsdp_machine_parser_header_M_single_lengths = [ 0, 1, 2, 5, 5, 0, 2, 4, 1, 4, 0, 1, 7, 0, 5, 6 ]; _tsdp_machine_parser_header_M_range_lengths = [ 0, 0, 0, 5, 5, 1, 1, 5, 0, 5, 1, 1, 4, 0, 5, 5 ]; _tsdp_machine_parser_header_M_index_offsets = [ 0, 0, 2, 5, 16, 27, 29, 33, 43, 45, 55, 57, 60, 72, 73, 84 ]; _tsdp_machine_parser_header_M_indicies = [ 0, 1, 0, 2, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 6, 1, 7, 8, 9, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1, 11, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 1, 13, 1, 7, 14, 1, 15, 16, 12, 12, 12, 17, 12, 12, 12, 12, 12, 1, 1, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 1, 20, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 1, 0 ]; _tsdp_machine_parser_header_M_trans_targs = [ 2, 0, 3, 4, 5, 4, 6, 7, 10, 6, 12, 13, 12, 11, 11, 8, 14, 9, 8, 15, 8, 14, 15 ]; _tsdp_machine_parser_header_M_trans_actions = [ 0, 0, 0, 1, 3, 0, 1, 5, 5, 0, 1, 0, 0, 1, 0, 7, 7, 0, 0, 1, 9, 9, 0 ]; _tsdp_machine_parser_header_M_eof_actions = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 9 ]; tsdp_machine_parser_header_M_start = 1; tsdp_machine_parser_header_M_first_final = 12; tsdp_machine_parser_header_M_error = 0; tsdp_machine_parser_header_M_en_main = 1; /* line 53 "./ragel/tsdp_parser_header_M.jrl" */ function tsdp_header_M(s_media, i_port, s_proto){ tsdp_header.call(this, tsdp_header_type_e.M); this.s_media = s_media; this.i_port = i_port; this.i_nports = 0; // number of ports this.s_proto = s_proto; this.as_fmt = new Array(); this.o_hdr_I = null; this.o_hdr_C = null; this.ao_hdr_B = new Array(); this.o_hdr_K = null; this.ao_hdr_A = new Array(); this.ao_hdr_Dummy = new Array(); } tsdp_header_M.prototype.toString = function(s_endline){ if(!s_endline){ s_endline = "\r\n"; } /* IMPORTANT: Keep the order. m= (media name and transport address) i=* (media title) c=* (connection information -- optional if included at session level) b=* (zero or more bandwidth information lines) k=* (encryption key) a=* (zero or more media attribute lines) */ var s_str = tsk_string_format("{0} {1}{2}{3} {4}", this.s_media, this.i_port, this.i_nports ? "/" : "", this.i_nports ? this.i_nports : "", this.s_proto); // FMTs for(var i = 0; i < this.as_fmt.length; ++i){ s_str += " " + this.as_fmt[i]; } var b_single_line = !this.o_hdr_I && !this.o_hdr_C && this.ao_hdr_B.length==0 && !this.o_hdr_K && this.ao_hdr_A.length.length==0; if(b_single_line){ return s_str; } // close the "m=" line s_str += s_endline; // i=* (media title) if(this.o_hdr_I){ s_str += this.o_hdr_I.tostring_full(false, s_endline); } // c=* (connection information -- optional if included at session level) if(this.o_hdr_C){ s_str += this.o_hdr_C.tostring_full(false, s_endline); } // b=* (zero or more bandwidth information lines) for(var i = 0; i < this.ao_hdr_B.length; ++i){ s_str += this.ao_hdr_B[i].tostring_full(false, s_endline); } // k=* (encryption key) if(this.o_hdr_K){ s_str += this.o_hdr_K.tostring_full(false, s_endline); } // a=* (zero or more media attribute lines) for(var i = 0; i < this.ao_hdr_A.length; ++i){ s_str += this.ao_hdr_A[i].tostring_full(false, s_endline); } // dummies for(var i = 0; i < this.ao_hdr_Dummy.length; ++i){ s_str += this.ao_hdr_Dummy[i].tostring_full(false, s_endline); } return s_str.substring(0, s_str.length - s_endline.length); } // for A headers, use "tsdp_header_A_removeAll_by_field()" tsdp_header_M.prototype.remove_header = function(e_type){ switch(e_type){ case tsdp_header_type_e.I: { this.o_hdr_I = null; break; } case tsdp_header_type_e.C: { this.o_hdr_C = null; break; } case tsdp_header_type_e.B: { this.ao_hdr_B.splice(0, this.ao_hdr_B.length); break; } case tsdp_header_type_e.K: { this.o_hdr_K = null; break; } } return 0; } tsdp_header_M.prototype.add_header = function(o_header){ if(!o_header){ tsk_utils_log_error("Invalid argument"); return -1; } switch(o_header.e_type){ case tsdp_header_type_e.I: { this.o_hdr_I = o_header; break; } case tsdp_header_type_e.C: { this.o_hdr_C = o_header; break; } case tsdp_header_type_e.B: { this.ao_hdr_B.push(o_header); break; } case tsdp_header_type_e.K: { this.o_hdr_K = o_header; break; } case tsdp_header_type_e.A: { this.ao_hdr_A.push(o_header); break; } } return 0; } tsdp_header_M.prototype.add_fmt = function(s_fmt){ if(s_fmt){ this.as_fmt.push(s_fmt); } } // add_headers(...) tsdp_header_M.prototype.add_headers = function(){ for(var i = 0; i < arguments.length; ++i){ if(arguments[i]){ this.add_header(arguments[i]); } } } tsdp_header_M.prototype.find_a_at = function(s_field, i_index) { if(!s_field || i_index < 0){ tsk_utils_log_error("Invalid argument"); return null; } var i_pos = 0; for(var i = 0; i < this.ao_hdr_A.length; ++i){ if(this.ao_hdr_A[i].s_field == s_field){ if(i_pos++ >= i_index){ return this.ao_hdr_A[i]; } } } return null; } tsdp_header_M.prototype.find_a = function(s_field) { return this.find_a_at(s_field, 0); } tsdp_header_M.prototype.get_rtpmap = function(s_fmt){ var i_fmt_len = s_fmt ? s_fmt.length : 0; if(i_fmt_len <= 0 || i_fmt_len > 3/*'0-255' or '*'*/){ tsk_utils_log_error("Invalid argument"); return null; } var s_rtpmap = null; /* e.g. AMR-WB/16000 */ var i_A_len, i_index = 0; var i_indexof; var o_hdr_A; /* find "a=rtpmap" */ while((o_hdr_A = this.find_a_at(i_index++))){ /* A->value would be: "98 AMR-WB/16000" */ if((i_A_len = o_hdr_A.s_value ? o_hdr_A.s_value.length : 0) < (i_fmt_len + 1/*space*/)){ continue; } if((i_indexof = tsk_string_index_of(o_hdr_A.s_value, i_A_len, s_fmt)) == 0 && (o_hdr_A.s_value[i_fmt_len] == ' ')){ s_rtpmap = o_hdr_A.s_value.substring(i_fmt_len+1, A_len); break; } } return s_rtpmap; } tsdp_header_M.prototype.get_fmtp = function(s_fmt){ var i_fmt_len = s_fmt ? s_fmt.length : 0; if(i_fmt_len <= 0 || i_fmt_len > 3/*'0-255' or '*'*/){ tsk_utils_log_error("Invalid argument"); return null; } var s_fmtp= null; /* e.g. octet-align=1 */ var i_A_len, i_index = 0; var i_indexof; var o_hdr_A; /* find "a=rtpmap" */ while((o_hdr_A = this.find_a_at(i_index++))){ /* A->value would be: "98 octet-align=1" */ if((i_A_len = o_hdr_A.s_value ? o_hdr_A.s_value.length : 0) < (i_fmt_len + 1/*space*/)){ continue; } if((i_indexof = tsk_string_index_of(o_hdr_A.s_value, i_A_len, s_fmt)) == 0 && (o_hdr_A.s_value[i_fmt_len] == ' ')){ s_fmtp = o_hdr_A.s_value.substring(i_fmt_len+1, A_len); break; } } return s_fmtp; } /* as per 3GPP TS 34.610 */ tsdp_header_M.prototype.hold = function(b_local){ var o_hdr_A; if((o_hdr_A = this.find_a(b_local ? "recvonly" : "sendonly"))){ // an "inactive" SDP attribute if the stream was previously set to "recvonly" media stream o_hdr_A.s_field = b_local ? "inactive" : "recvonly"; } else if((o_hdr_A = this.find_a("sendrecv"))){ // a "sendonly" SDP attribute if the stream was previously set to "sendrecv" media stream o_hdr_A.s_field = b_local ? "sendonly" : "recvonly"; } else{ // default value is sendrecv. hold on default --> sendonly if(!(o_hdr_A = this.find_a(b_local ? "sendonly" : "recvonly")) && !(o_hdr_A = this.find_a("inactive"))){ var o_hdr_newA; if((o_hdr_newA = new tsdp_header_A(b_local ? "sendonly" : "recvonly", null))){ this.add_header(o_hdr_newA); } } } return 0; } /* as per 3GPP TS 34.610 */ tsdp_header_M.prototype.set_holdresume_att = function(b_lo_held, b_ro_held){ var o_hdr_A; var hold_resume_atts = [["sendrecv", "recvonly"],["sendonly", "inactive"]]; if((o_hdr_A = this.find_a("sendrecv")) || (o_hdr_A = this.find_a("sendonly")) || (o_hdr_A = this.find_a("recvonly")) || (o_hdr_A = this.find_a("inactive"))){ o_hdr_A.s_field = hold_resume_atts[b_lo_held ? 1 : 0][b_ro_held ? 1 : 0]; } else{ var o_hdr_newA; if((o_hdr_newA = new tsdp_header_A(hold_resume_atts[b_lo_held ? 1 : 0][b_ro_held ? 1 : 0], null))){ this.add_headers(o_hdr_newA); } } return 0; } tsdp_header_M.prototype.is_held = function(b_local){ /* both cases */ if(this.find_a("inactive")){ return true; } if(b_local){ return this.find_a("recvonly") ? true : false; } else{ return this.find_a("sendonly") ? true : false; } } /* as per 3GPP TS 34.610 */ tsdp_header_M.prototype.resume = function(b_local){ var o_hdr_A; if((o_hdr_A = this.find_a("inactive"))){ // a "recvonly" SDP attribute if the stream was previously an inactive media stream o_hdr_A.s_field = b_local ? "recvonly" : "sendonly"; } else if((o_hdr_A = this.find_a(b_local ? "sendonly" : "recvonly"))){ // a "sendrecv" SDP attribute if the stream was previously a sendonly media stream, or the attribute may be omitted, since sendrecv is the default o_hdr_A.s_field = sendrecv; } return 0; } tsdp_header_M.prototype.Parse = function(s_str){ var cs = 0; var p = 0; var pe = s_str.length; var eof = pe; var data = tsk_buff_str2ib(s_str); var i_tag_start; var hdr_M = new tsdp_header_M(null, 0, null); /* line 419 "./src/headers/tsdp_header_M.js" */ { cs = tsdp_machine_parser_header_M_start; } /* JSCodeGen::writeInit */ /* line 370 "./ragel/tsdp_parser_header_M.jrl" */ /* line 426 "./src/headers/tsdp_header_M.js" */ { var _klen, _trans, _keys, _ps, _widec, _acts, _nacts; var _goto_level, _resume, _eof_trans, _again, _test_eof; var _out; _klen = _trans = _keys = _acts = _nacts = null; _goto_level = 0; _resume = 10; _eof_trans = 15; _again = 20; _test_eof = 30; _out = 40; while (true) { _trigger_goto = false; if (_goto_level <= 0) { if (p == pe) { _goto_level = _test_eof; continue; } if (cs == 0) { _goto_level = _out; continue; } } if (_goto_level <= _resume) { _keys = _tsdp_machine_parser_header_M_key_offsets[cs]; _trans = _tsdp_machine_parser_header_M_index_offsets[cs]; _klen = _tsdp_machine_parser_header_M_single_lengths[cs]; _break_match = false; do { if (_klen > 0) { _lower = _keys; _upper = _keys + _klen - 1; while (true) { if (_upper < _lower) { break; } _mid = _lower + ( (_upper - _lower) >> 1 ); if (data[p] < _tsdp_machine_parser_header_M_trans_keys[_mid]) { _upper = _mid - 1; } else if (data[p] > _tsdp_machine_parser_header_M_trans_keys[_mid]) { _lower = _mid + 1; } else { _trans += (_mid - _keys); _break_match = true; break; }; } /* while */ if (_break_match) { break; } _keys += _klen; _trans += _klen; } _klen = _tsdp_machine_parser_header_M_range_lengths[cs]; if (_klen > 0) { _lower = _keys; _upper = _keys + (_klen << 1) - 2; while (true) { if (_upper < _lower) { break; } _mid = _lower + (((_upper-_lower) >> 1) & ~1); if (data[p] < _tsdp_machine_parser_header_M_trans_keys[_mid]) { _upper = _mid - 2; } else if (data[p] > _tsdp_machine_parser_header_M_trans_keys[_mid+1]) { _lower = _mid + 2; } else { _trans += ((_mid - _keys) >> 1); _break_match = true; break; } } /* while */ if (_break_match) { break; } _trans += _klen } } while (false); _trans = _tsdp_machine_parser_header_M_indicies[_trans]; cs = _tsdp_machine_parser_header_M_trans_targs[_trans]; if (_tsdp_machine_parser_header_M_trans_actions[_trans] != 0) { _acts = _tsdp_machine_parser_header_M_trans_actions[_trans]; _nacts = _tsdp_machine_parser_header_M_actions[_acts]; _acts += 1; while (_nacts > 0) { _nacts -= 1; _acts += 1; switch (_tsdp_machine_parser_header_M_actions[_acts - 1]) { case 0: /* line 14 "./ragel/tsdp_parser_header_M.jrl" */ i_tag_start = p; break; case 1: /* line 18 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.s_media = tsk_ragel_parser_get_string(s_str, p, i_tag_start); break; case 2: /* line 22 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.i_port= tsk_ragel_parser_get_int(s_str, p, i_tag_start); break; case 3: /* line 30 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.s_proto = tsk_ragel_parser_get_string(s_str, p, i_tag_start); break; case 4: /* line 34 "./ragel/tsdp_parser_header_M.jrl" */ tsk_ragel_parser_add_string(s_str, p, i_tag_start, hdr_M.as_fmt); break; /* line 535 "./src/headers/tsdp_header_M.js" */ } /* action switch */ } } if (_trigger_goto) { continue; } } if (_goto_level <= _again) { if (cs == 0) { _goto_level = _out; continue; } p += 1; if (p != pe) { _goto_level = _resume; continue; } } if (_goto_level <= _test_eof) { if (p == eof) { __acts = _tsdp_machine_parser_header_M_eof_actions[cs]; __nacts = _tsdp_machine_parser_header_M_actions[__acts]; __acts += 1; while (__nacts > 0) { __nacts -= 1; __acts += 1; switch (_tsdp_machine_parser_header_M_actions[__acts - 1]) { case 3: /* line 30 "./ragel/tsdp_parser_header_M.jrl" */ hdr_M.s_proto = tsk_ragel_parser_get_string(s_str, p, i_tag_start); break; case 4: /* line 34 "./ragel/tsdp_parser_header_M.jrl" */ tsk_ragel_parser_add_string(s_str, p, i_tag_start, hdr_M.as_fmt); break; /* line 573 "./src/headers/tsdp_header_M.js" */ } /* eof action switch */ } if (_trigger_goto) { continue; } } } if (_goto_level <= _out) { break; } } } /* line 371 "./ragel/tsdp_parser_header_M.jrl" */ if( cs < /* line 590 "./src/headers/tsdp_header_M.js" */ 12 /* line 372 "./ragel/tsdp_parser_header_M.jrl" */ ){ tsk_utils_log_error("Failed to parse \"m=\" header: " + s_str); return null; } return hdr_M; }
DoubangoTelecom/sipml5
src/tinySDP/src/headers/tsdp_header_M.js
JavaScript
bsd-3-clause
15,015
(function ($) { "use strict"; /* DEFINE VARIABLES */ var fu = $("#media-upload"), // FOR JQUERY FILE UPLOAD fc = $("#file-container"), // FILE CONTAINER DISPLAY md = $("#media-detail"), // FOR DETAIL ITEM mf = $("#media-form"), // FOR FORM OF THE SELECTED ITEM ad = $('#address'), me = {"files": []}, // JSON OBJECT OF MEDIA ITEM se = {}; // JSON OBJECT OF SELECTED ITEM /* FILE UPLOAD CONFIGURATION */ fu.fileupload({ url: fu.data("url"), dropZone: $(".dropzone"), autoUpload: true, filesContainer: "#file-container", prependFiles: true }); fu.fileupload("option", "redirect", window.location.href.replace(/\/[^\/]*$/, "/cors/result.html?%s")); fu.addClass("fileupload-processing"); /* DRAG AND DROP */ $(document).bind("dragover", function (e) { var dropZone = $(".dropzone"), foundDropzone, timeout = window.dropZoneTimeout; if (!timeout) dropZone.addClass("in"); else clearTimeout(timeout); var found = false, node = e.target; do { if ($(node).hasClass("dropzone")) { found = true; foundDropzone = $(node); break; } node = node.parentNode; } while (node !== null); dropZone.removeClass("in hover"); if (found) { foundDropzone.addClass("hover"); } window.dropZoneTimeout = setTimeout(function () { window.dropZoneTimeout = null; dropZone.removeClass("in hover"); }, 100); }); /* ADD NEW UPLOADED FILE TO MEDIA JSON */ fu.bind("fileuploaddone", function (e, data) { $.each(data.result, function (index, file) { me.files[me.files.length] = file[0]; }); }); /* GET MEDIA DATA THAT APPEAR ON MEDIA WITHOUT FILTERING */ $.ajax({ url: ad.data('json-url'), dataType: "json", success: function (response) { me = response; $.ajax({ url: ad.data('pagination-url'), success: function (response) { $('#media-pagination').html(response); } }); fc.html(tmpl("template-download", response)); } }); /* SIDEBAR NAVIGATION */ $(document).on('click', '.media-popup-nav', function (e) { e.preventDefault(); var $this = $(this); $this.closest("ul").find("li").removeClass("active"); $this.parent("li").addClass("active"); if ($this.hasClass('all')) { $('.pagination-item').removeAttr('data-post_id'); } else { $('.pagination-item').attr('data-post_id', $(this).data("post_id")); } $.ajax({ url: ad.data('json-url'), data: {post_id: $this.data('post_id')}, dataType: "json", success: function (response) { me = response; $.ajax({ url: ad.data('pagination-url'), data: {post_id: $this.data('post_id')}, success: function (response) { var mp = $(".media-pagination"); mp.html(response); } }); fc.html(tmpl("template-download", response)); } }); }); /* PAGINATION CLICK */ $(document).on('click', '.pagination-item', function (e) { e.preventDefault(); var $this = $(this), p1 = $(this).data('page'), p2 = p1 + 1; $.ajax({ url: $this.attr('href'), data: {post_id: $this.data('post_id')}, dataType: "json", success: function (response) { me = response; $.ajax({ url: ad.data('pagination-url'), data: {post_id: $this.data('post_id'), page: p2, 'per-page': $this.data('per-page')}, success: function (response) { var mp = $(".media-pagination"); mp.html(response); } }); fc.html(tmpl("template-download", response)); } }); }); /* SHOW DETAIL ITEM */ fc.selectable({ filter: "li", tolerance: "fit", selected: function (event, ui) { $.each(me.files, function (i, file) { if ($(ui.selected).data('id') === file.id) { md.html(tmpl('template-media-detail', file)); mf.html(tmpl('template-media-form', file)); se[$(ui.selected).data("id")] = $("#media-form-inner").serializeObject(); } }); }, unselected: function (event, ui) { delete se[$(ui.unselected).data('id')]; } }); /* UPDATE SELECTED */ $(document).on("blur", "#media-form-inner [id^='media-']", function () { var parent = $(this).parents('#media-form-inner'), id = parent.data("id"); se[id] = parent.serializeObject(); }); /* UPDATE TITLE, EXCERPT, CONTENT OF MEDIA VIA AJAX CALL */ $(document).on("blur", "#media-media_title, #media-media_excerpt, #media-media_content", function () { var mfi = $(this).closest('#media-form-inner'); $.ajax({ url: mfi.data("update-url"), type: "POST", data: { id: mfi.data("id"), attribute: $(this).data('attr'), attribute_value: $(this).val(), _csrf: yii.getCsrfToken() }, success: function(response){ console.log(response); } }); }); /* UPDATE LINK TO */ $(document).on('change', '#media-media_link_to', function () { var link_value = $('#media-media_link_to_value'); if ($(this).val() === 'none') { link_value.val(''); link_value.attr('readonly', true); } else if ($(this).val() === 'custom') { link_value.val('http://'); link_value.attr('readonly', false); } else { link_value.val($(this).val()); } }); /* DELETE MEDIA ITEM ON MEDIA POP UP */ $(document).on("click", '#delete-media', function (e) { e.preventDefault(); e.stopImmediatePropagation(); var $this = $(this); if (confirm($this.data('confirm'))) { $.ajax({ url: $this.data('url'), type: "POST", success: function (data) { $('.media-item[data-id="' + $this.data('id') + '"]').closest('li').remove(); md.html(''); mf.html(''); delete se[$this.data('id')]; } }); } }); /* MEDIA FILTER SUBMIT */ $(document).on("submit", "#media-filter", function(e){ e.preventDefault(); e.stopImmediatePropagation(); var data = $(this).serialize(); $.ajax({ url: ad.data('json-url'), data: data, dataType: "json", success: function(response){ me = response; $.ajax({ url: ad.data('pagination-url'), data: data, success: function (response) { var mp = $(".media-pagination"); mp.html(response); } }); fc.html(tmpl("template-download", me)); } }); }); /* INSERT INTO TINY MCE */ $(document).on("click", "#insert-media", function (e) { e.preventDefault(); if(top.tinymce !== undefined){ $.ajax({ url: $(this).data('insert-url'), data: {media: se, _csrf: yii.getCsrfToken()}, type: 'POST', success: function(response){ top.tinymce.activeEditor.execCommand("mceInsertContent", false, response); top.tinymce.activeEditor.windowManager.close(); } }); }else{ $.ajax({ url: $(this).data('insert-url'), data: {media: se, _csrf: yii.getCsrfToken()}, type: 'POST', success: function(response){ alert(response); } }); } }); }(jQuery));
cloud-github/Yii2-cms
admin/js/media.popup.js
JavaScript
bsd-3-clause
9,054
var NAVTREEINDEX17 = { "classIoss_1_1Tet4.html#ae945be949a6165bf9cebf2b770699ebd":[4,0,69,135,22], "classIoss_1_1Tet4.html#af2f9d7a80f796ded6a5ddfe374ed808e":[4,0,69,135,19], "classIoss_1_1Tet7.html":[4,0,69,136], "classIoss_1_1Tet7.html#a13df36e1096ef89227119e5d308ed628":[4,0,69,136,16], "classIoss_1_1Tet7.html#a16e6fa628f011addd36fc7322faa42c0":[4,0,69,136,19], "classIoss_1_1Tet7.html#a1e12d6c712675de8a1c8fc33b0b8c92d":[4,0,69,136,9], "classIoss_1_1Tet7.html#a29e1874549c01fd3c4be76ce3e4a9f67":[4,0,69,136,4], "classIoss_1_1Tet7.html#a37e0a7bce58a5da950d1ffb58ccbe8c4":[4,0,69,136,23], "classIoss_1_1Tet7.html#a497597e125f4502ff0a59a50b97ee0d9":[4,0,69,136,0], "classIoss_1_1Tet7.html#a508d1b597207d3872de42f3adf5b57fe":[4,0,69,136,2], "classIoss_1_1Tet7.html#a5b51028e307e1d244a5e6d17086f172e":[4,0,69,136,14], "classIoss_1_1Tet7.html#a5d0ff7276306ce77f9f6aa3ff1a04c68":[4,0,69,136,17], "classIoss_1_1Tet7.html#a6185f51cb7d94cb95220d98027ebaca0":[4,0,69,136,5], "classIoss_1_1Tet7.html#a64e46d81e51eda112c26105ec99c6cfe":[4,0,69,136,1], "classIoss_1_1Tet7.html#a8a12f05296d24f424b8466da9441bf0c":[4,0,69,136,22], "classIoss_1_1Tet7.html#a8bc616e8c2c9f2a493317979c67fa047":[4,0,69,136,7], "classIoss_1_1Tet7.html#a93b1ed3d1f0c22a79a794971845787f8":[4,0,69,136,12], "classIoss_1_1Tet7.html#aa99a6537359811e7ff5e8303c058faa2":[4,0,69,136,3], "classIoss_1_1Tet7.html#aad6a34b82fd2536894803cb9a6d3770a":[4,0,69,136,25], "classIoss_1_1Tet7.html#ab39e17b1fc522bfd33eccda8a0d770b8":[4,0,69,136,11], "classIoss_1_1Tet7.html#ab6ea8527499e31b590ff96a6f167adb0":[4,0,69,136,21], "classIoss_1_1Tet7.html#ac0cec8c082b6b0dd48b12849b3925792":[4,0,69,136,24], "classIoss_1_1Tet7.html#ac70c36c3acc282ddf505e21d263c5e70":[4,0,69,136,6], "classIoss_1_1Tet7.html#aca98ce328e3342d199d61e775601f966":[4,0,69,136,18], "classIoss_1_1Tet7.html#acdf346236e1c828a7f2465d3d90647c1":[4,0,69,136,20], "classIoss_1_1Tet7.html#ad2abb9b07e6f3cf751e664b9c8b8d597":[4,0,69,136,8], "classIoss_1_1Tet7.html#ad3c34a488797fe95f2ed9fa15d6421e9":[4,0,69,136,15], "classIoss_1_1Tet7.html#aeef6548bb945ed9834a9ceef46a0c20e":[4,0,69,136,13], "classIoss_1_1Tet7.html#af07d90322884ef186c3e2c777ed13084":[4,0,69,136,10], "classIoss_1_1Tet8.html":[4,0,69,137], "classIoss_1_1Tet8.html#a00b61be09130b0410063302f64f43bcc":[4,0,69,137,5], "classIoss_1_1Tet8.html#a011bc0eff2c9265228cdf52b83678c9b":[4,0,69,137,7], "classIoss_1_1Tet8.html#a03b2292e8a7cdd7351e603e73134d34e":[4,0,69,137,15], "classIoss_1_1Tet8.html#a25457b776295b67a48a9ca00674f0d94":[4,0,69,137,13], "classIoss_1_1Tet8.html#a2e8a36b032da95bed6b7e1571428964f":[4,0,69,137,1], "classIoss_1_1Tet8.html#a30f56430f429096f36a3972a0b80cbd1":[4,0,69,137,16], "classIoss_1_1Tet8.html#a35ecd3d481252dff9eb20dc4dc49e36c":[4,0,69,137,20], "classIoss_1_1Tet8.html#a3ed02b12943ee78a551128eb1c40544f":[4,0,69,137,17], "classIoss_1_1Tet8.html#a4c7f31adf0bc54963f73e7514a0848e4":[4,0,69,137,12], "classIoss_1_1Tet8.html#a548e6882af1baf769ff64113da6a3570":[4,0,69,137,14], "classIoss_1_1Tet8.html#a5e8d00b887f319058205ed9248ea492b":[4,0,69,137,21], "classIoss_1_1Tet8.html#a6669f4ba0986fb3a72da72a81759bd16":[4,0,69,137,23], "classIoss_1_1Tet8.html#a7de7e6c605fb27d31a803cd374c5e40e":[4,0,69,137,0], "classIoss_1_1Tet8.html#a9137b19a3fb4cec9a75d932a19fb88a4":[4,0,69,137,3], "classIoss_1_1Tet8.html#a9885a8df8a5deb1ebe64d055e0381edf":[4,0,69,137,2], "classIoss_1_1Tet8.html#a9cfdf666e5e3997eb04d6b64fca2aafe":[4,0,69,137,9], "classIoss_1_1Tet8.html#ab10481a406a6e6c21b9ad1927edea4f0":[4,0,69,137,4], "classIoss_1_1Tet8.html#ac3213933e5e7534d6e57785451788dd1":[4,0,69,137,8], "classIoss_1_1Tet8.html#ad8b8917b2d07797175cde71693211f70":[4,0,69,137,10], "classIoss_1_1Tet8.html#ae1058c79432e4ad3819aa6d1dc289da4":[4,0,69,137,22], "classIoss_1_1Tet8.html#ae34777703a05db0dea75a51fd4c9369f":[4,0,69,137,11], "classIoss_1_1Tet8.html#af22d74d02ec643002e8f29ed43afd1af":[4,0,69,137,6], "classIoss_1_1Tet8.html#afaf24cab8a279fa5198dd013d24435ca":[4,0,69,137,18], "classIoss_1_1Tet8.html#afd832344bca83f1bb0b6d6501b6d0403":[4,0,69,137,19], "classIoss_1_1Tracer.html":[4,0,69,138], "classIoss_1_1Tracer.html#a0424194979de9618ae5aa5ace9238059":[4,0,69,138,2], "classIoss_1_1Tracer.html#a162b60918f354c5b578dd176db7d18b5":[4,0,69,138,1], "classIoss_1_1Tracer.html#a77abfa36452763455cfae5f9b3dbec3c":[4,0,69,138,0], "classIoss_1_1Transform.html":[4,0,69,139], "classIoss_1_1Transform.html#a037d9cb9194d128d62c078c76e2a3e9c":[4,0,69,139,4], "classIoss_1_1Transform.html#a08b3d25e81aad971319e5226dbe6c5d4":[4,0,69,139,8], "classIoss_1_1Transform.html#a0a04fddfb90aa8093846bca0bfd5bae9":[4,0,69,139,9], "classIoss_1_1Transform.html#a2e07c7b72c70b6571745cad8c19829aa":[4,0,69,139,2], "classIoss_1_1Transform.html#a2ed9cede3ba9cca42682290603977b66":[4,0,69,139,1], "classIoss_1_1Transform.html#a38a16d4864b0c5b0fd9748a4546167a5":[4,0,69,139,6], "classIoss_1_1Transform.html#a73a8a80e4a4ff6a3c8b3a7c8ca6173c3":[4,0,69,139,3], "classIoss_1_1Transform.html#abf6cd01b7fdc9b09b9f956da4904e242":[4,0,69,139,5], "classIoss_1_1Transform.html#ad567453635ee4e6bcc3bb20279ddc74e":[4,0,69,139,0], "classIoss_1_1Transform.html#ae6af4e1c07b4dbbc84cc12ff1485b062":[4,0,69,139,7], "classIoss_1_1Tri3.html":[4,0,69,140], "classIoss_1_1Tri3.html#a00497b28142b0128564efc4485abac40":[4,0,69,140,21], "classIoss_1_1Tri3.html#a0afecfcc2808957fe70dc8eff7859d23":[4,0,69,140,13], "classIoss_1_1Tri3.html#a0c1427196558a2add60569c581948044":[4,0,69,140,7], "classIoss_1_1Tri3.html#a1dd94af979b99b166e4a97399d4aaa18":[4,0,69,140,3], "classIoss_1_1Tri3.html#a3fcd8ca13ccdb29ddde6b26a30800f09":[4,0,69,140,5], "classIoss_1_1Tri3.html#a44fb0127fc9e6387d76a56fdbb6aea36":[4,0,69,140,2], "classIoss_1_1Tri3.html#a5af625ebd0a0f5856791f94a6b19326b":[4,0,69,140,9], "classIoss_1_1Tri3.html#a70d571e1b83b73d99e2e2eb558e19f4c":[4,0,69,140,6], "classIoss_1_1Tri3.html#a70e465e12ad1fdd7e71d8d45a2cbf624":[4,0,69,140,20], "classIoss_1_1Tri3.html#a7d3559610a65520e9219ce2c6f596083":[4,0,69,140,12], "classIoss_1_1Tri3.html#a97ebfc797a34a6a75effb91965372580":[4,0,69,140,1], "classIoss_1_1Tri3.html#a99a9fcf57e733edceb2c868f3e670f3f":[4,0,69,140,14], "classIoss_1_1Tri3.html#a9d0a293948f686a44a6fc33ca79e59d3":[4,0,69,140,18], "classIoss_1_1Tri3.html#a9d3a5e2ff52cfa2d372963388fc4c8b9":[4,0,69,140,22], "classIoss_1_1Tri3.html#abcf3977487f14331b788a2244e5dfeed":[4,0,69,140,15], "classIoss_1_1Tri3.html#acd35db085d490501cc1861eaa15dd1de":[4,0,69,140,19], "classIoss_1_1Tri3.html#ad2193f85fe82211f182eda2e22f2d3b7":[4,0,69,140,10], "classIoss_1_1Tri3.html#ad2aeaef685733064c58871168b2da196":[4,0,69,140,16], "classIoss_1_1Tri3.html#ad58d40594c44f55f78620daf1e9beddd":[4,0,69,140,8], "classIoss_1_1Tri3.html#add8e943c4537c3ae5b8d5bd12a1412c9":[4,0,69,140,0], "classIoss_1_1Tri3.html#aeecc1f6ad221d7c624b3e255bbcfd25c":[4,0,69,140,11], "classIoss_1_1Tri3.html#afbfec6c87e7f29b04e226a6b921eb4b5":[4,0,69,140,4], "classIoss_1_1Tri3.html#afd12cfff5e317ce895ad210afaddac44":[4,0,69,140,17], "classIoss_1_1Tri4.html":[4,0,69,141], "classIoss_1_1Tri4.html#a013db626c1488d5b9aeefd90ded56274":[4,0,69,141,3], "classIoss_1_1Tri4.html#a089412d62e838525bae41dd2b3c8a863":[4,0,69,141,10], "classIoss_1_1Tri4.html#a0c3f8b9c919e0a203797a30e86989076":[4,0,69,141,4], "classIoss_1_1Tri4.html#a240083abc5d59f707bde11529a5e0251":[4,0,69,141,21], "classIoss_1_1Tri4.html#a2e741315708bd0bd49860bcc8a737677":[4,0,69,141,14], "classIoss_1_1Tri4.html#a35d4c4b88da6fbc2a012165929da6eda":[4,0,69,141,22], "classIoss_1_1Tri4.html#a5068f545c8885247fd7335f7558d6f3d":[4,0,69,141,12], "classIoss_1_1Tri4.html#a58650889ae52b5b76902bbbeb90ebd9b":[4,0,69,141,1], "classIoss_1_1Tri4.html#a5b5f986611e5685a1534813de33a673f":[4,0,69,141,0], "classIoss_1_1Tri4.html#a67f786bb5cfec7bec072ec06f32c0915":[4,0,69,141,18], "classIoss_1_1Tri4.html#a6a45356f2540b9387c5fbc22b3fba97d":[4,0,69,141,13], "classIoss_1_1Tri4.html#a71ef18b101d0c8d03890792977480271":[4,0,69,141,11], "classIoss_1_1Tri4.html#a8694a27fd6128adf1bbb3169eb71843e":[4,0,69,141,8], "classIoss_1_1Tri4.html#a8d04a744ec919be6705975b5410757e1":[4,0,69,141,9], "classIoss_1_1Tri4.html#a9559b34bd82633bcf034903c815fa0b6":[4,0,69,141,17], "classIoss_1_1Tri4.html#aa0c9dd8db3639cb06366eae3d7fba154":[4,0,69,141,6], "classIoss_1_1Tri4.html#ab6d214f03ef7b7f8438c04d08a6693f4":[4,0,69,141,16], "classIoss_1_1Tri4.html#ac5ef86f7468ed92ebd47434108b0e793":[4,0,69,141,15], "classIoss_1_1Tri4.html#ac8a61b40a3db3a2b4d35b2726b582d69":[4,0,69,141,2], "classIoss_1_1Tri4.html#ad4ae0392238aa94bf74cbd1fb4d72e39":[4,0,69,141,7], "classIoss_1_1Tri4.html#ae019a32790a14f676230d55bc11bcd23":[4,0,69,141,5], "classIoss_1_1Tri4.html#ae423f11a0fb84600efddb6bd11277112":[4,0,69,141,19], "classIoss_1_1Tri4.html#afe46a478baaa7c441ecec0924be27480":[4,0,69,141,20], "classIoss_1_1Tri4a.html":[4,0,69,142], "classIoss_1_1Tri4a.html#a25910996f609d6f00a3ba71f7ccb5fc3":[4,0,69,142,5], "classIoss_1_1Tri4a.html#a2815b2cd0b48f3dfc6f1c5a2b61d1178":[4,0,69,142,1], "classIoss_1_1Tri4a.html#a2a97cb506ec29eb05fc5130982610f92":[4,0,69,142,8], "classIoss_1_1Tri4a.html#a424c58fabd60b466719d6faaf0003f1f":[4,0,69,142,20], "classIoss_1_1Tri4a.html#a51beb2b1f3bc2ad9081722e8bb9d75cd":[4,0,69,142,19], "classIoss_1_1Tri4a.html#a59649ebbd2ddf4a5e14a6ae3f645f20e":[4,0,69,142,2], "classIoss_1_1Tri4a.html#a5dfe322ed0a094e93eaa992f99cec871":[4,0,69,142,12], "classIoss_1_1Tri4a.html#a6814569dd48827ad9762bf043666ccdf":[4,0,69,142,21], "classIoss_1_1Tri4a.html#a6c328ee45b3fe18d94942c14002d7dc4":[4,0,69,142,3], "classIoss_1_1Tri4a.html#a6e1d4ff5e717b1ab4db9cd36ae560c4e":[4,0,69,142,0], "classIoss_1_1Tri4a.html#a76478395a1e3567f128cf1cdbf9d2838":[4,0,69,142,17], "classIoss_1_1Tri4a.html#a77ed4a87c304c42a5a95baed8e64741b":[4,0,69,142,23], "classIoss_1_1Tri4a.html#a7bb3df352e69e1b9dae27f72dd45de04":[4,0,69,142,4], "classIoss_1_1Tri4a.html#a8056802fee146e9590b4f503cc151990":[4,0,69,142,22], "classIoss_1_1Tri4a.html#a8de8b020910eaeff60e169696a31b081":[4,0,69,142,10], "classIoss_1_1Tri4a.html#a9db31edf11f7f67633f8e4472e651558":[4,0,69,142,15], "classIoss_1_1Tri4a.html#ac4a6e2c1e1a9128dc0103b3dd5f60648":[4,0,69,142,7], "classIoss_1_1Tri4a.html#ac76ddceb4fb6b8e63abdb7973c00577f":[4,0,69,142,16], "classIoss_1_1Tri4a.html#ac8b593d930d34b65e8b229fc7b831163":[4,0,69,142,6], "classIoss_1_1Tri4a.html#ade855f124f71b4632990cc8a94715243":[4,0,69,142,14], "classIoss_1_1Tri4a.html#ae11cd6b6c936f596284fd30d427ede78":[4,0,69,142,18], "classIoss_1_1Tri4a.html#ae189248fdfffb9723f0940a28fba0f59":[4,0,69,142,13], "classIoss_1_1Tri4a.html#aecb707faf827cfa3d7674a50cd8a0e01":[4,0,69,142,11], "classIoss_1_1Tri4a.html#af7a441282b97165a2efc948dacd45d34":[4,0,69,142,9], "classIoss_1_1Tri6.html":[4,0,69,143], "classIoss_1_1Tri6.html#a1742a5d223acd57dd35601558a8e88ea":[4,0,69,143,18], "classIoss_1_1Tri6.html#a22e045b48cdd439d6ca9ada864f7c0fa":[4,0,69,143,12], "classIoss_1_1Tri6.html#a2342fb9e4e320d5d5aae6121ada1dda9":[4,0,69,143,19], "classIoss_1_1Tri6.html#a3100ba4a5d131f86c926b1159704d0f2":[4,0,69,143,5], "classIoss_1_1Tri6.html#a32453b699308c9fb01137085fffecc8f":[4,0,69,143,4], "classIoss_1_1Tri6.html#a4f08c83b56ff296e11f39206148703f9":[4,0,69,143,1], "classIoss_1_1Tri6.html#a770e5eaa73aeed57ea57a9b38f57de69":[4,0,69,143,16], "classIoss_1_1Tri6.html#a7f8deedf41a215512a738cd93eaaa0e1":[4,0,69,143,21], "classIoss_1_1Tri6.html#a879f00a93ef7588a1cd0fcff818e6230":[4,0,69,143,15], "classIoss_1_1Tri6.html#a9cd8881347532603f209a71824381589":[4,0,69,143,20], "classIoss_1_1Tri6.html#aa8b6274f991d8bd4cf3271d6ab727604":[4,0,69,143,17], "classIoss_1_1Tri6.html#aab22eefd376744d44ceebff8c26f1d44":[4,0,69,143,7], "classIoss_1_1Tri6.html#aab2eb3ab749d58b54e324f0ce144444e":[4,0,69,143,9], "classIoss_1_1Tri6.html#ab799c277be6ff03318328af89be88dc2":[4,0,69,143,2], "classIoss_1_1Tri6.html#ab8509e9f199d876eb3daca8296f544d9":[4,0,69,143,13], "classIoss_1_1Tri6.html#abe906bca33957d2182597376f861d14b":[4,0,69,143,14], "classIoss_1_1Tri6.html#ad2bccfaad6094b531d2f5819b61365e9":[4,0,69,143,0], "classIoss_1_1Tri6.html#ae7fd816d324b8f623f374926204233dd":[4,0,69,143,11], "classIoss_1_1Tri6.html#ae85c16cbeb78fca3f21009c965151e2a":[4,0,69,143,6], "classIoss_1_1Tri6.html#aec005d92c3ed3ea2c11934e4e717193c":[4,0,69,143,22], "classIoss_1_1Tri6.html#af2afd7e564e1fe0bcfee313bdaed11b8":[4,0,69,143,3], "classIoss_1_1Tri6.html#af445874fc040863b4b365dffb4cd42ba":[4,0,69,143,8], "classIoss_1_1Tri6.html#afeaf081098bce861ca91adfddc120341":[4,0,69,143,10], "classIoss_1_1Tri7.html":[4,0,69,144], "classIoss_1_1Tri7.html#a023e98ceb4d292a9eb7e859393c73133":[4,0,69,144,20], "classIoss_1_1Tri7.html#a08c0d7df5d23b5d167b3da41c471c5a8":[4,0,69,144,10], "classIoss_1_1Tri7.html#a0fd12222086391d13953446553357e24":[4,0,69,144,1], "classIoss_1_1Tri7.html#a177a84df7606246e26d4fdf6a45ccdff":[4,0,69,144,14], "classIoss_1_1Tri7.html#a1b46841ac4427ba6a7250ad01e48fd85":[4,0,69,144,17], "classIoss_1_1Tri7.html#a1caacfbbd85dacdfcea7456d4f34785b":[4,0,69,144,16], "classIoss_1_1Tri7.html#a243a435eb0062b91461ed2a13defc420":[4,0,69,144,19], "classIoss_1_1Tri7.html#a2767210d1ab21177f2fb73fa80701bcf":[4,0,69,144,6], "classIoss_1_1Tri7.html#a2e36fa4800efaa5612e5b603bbcd1bd8":[4,0,69,144,12], "classIoss_1_1Tri7.html#a2e3a4a6d48b34a490df162de77a51988":[4,0,69,144,9], "classIoss_1_1Tri7.html#a398c635a1787e692ab31c4cad5add040":[4,0,69,144,2], "classIoss_1_1Tri7.html#a47d03409072406d0d2a45f0cc2d7b86b":[4,0,69,144,5], "classIoss_1_1Tri7.html#a4fe80cae1ee5fd3070c1b17cade5e59f":[4,0,69,144,8], "classIoss_1_1Tri7.html#a651838ca5b586bd9419b6f98766c4365":[4,0,69,144,7], "classIoss_1_1Tri7.html#a6f48eb90ab2f175b55eafc66d0fffff1":[4,0,69,144,11], "classIoss_1_1Tri7.html#a8de757a487f8f32ae082a216078abaf2":[4,0,69,144,4], "classIoss_1_1Tri7.html#a9797e1b785695a4d26ee4fe2a67677c9":[4,0,69,144,18], "classIoss_1_1Tri7.html#a9e2e5de42b3a3efa1ddd9c7a6633f30d":[4,0,69,144,13], "classIoss_1_1Tri7.html#abfd7a5ef7840894f75b65ae35d45710a":[4,0,69,144,21], "classIoss_1_1Tri7.html#ac4c3eb039489a5f276e9a1492267502e":[4,0,69,144,3], "classIoss_1_1Tri7.html#ac4dbf0f7cae3c70328909d204084eba2":[4,0,69,144,0], "classIoss_1_1Tri7.html#ac60c95c0d3b0f4b380ad7456934c759e":[4,0,69,144,22], "classIoss_1_1Tri7.html#afc03e1ed3e41a9bd3f691ab2a5a83287":[4,0,69,144,15], "classIoss_1_1TriShell3.html":[4,0,69,145], "classIoss_1_1TriShell3.html#a036e26dedc61661127a9b1895218d946":[4,0,69,145,7], "classIoss_1_1TriShell3.html#a0dc6bebf7ea7657abc2e63a12bd0bddb":[4,0,69,145,16], "classIoss_1_1TriShell3.html#a190b3a5b0e4d4f626ad19c35b7fe4d01":[4,0,69,145,19], "classIoss_1_1TriShell3.html#a1e14fe5ed3c3f79ef106dc7a4245154e":[4,0,69,145,14], "classIoss_1_1TriShell3.html#a2c179e48f700166e5470c36a4d7b1c55":[4,0,69,145,13], "classIoss_1_1TriShell3.html#a3a2e43db0446b70dae125cea9103e250":[4,0,69,145,21], "classIoss_1_1TriShell3.html#a504a11c3dbb30648fbcf8cca05eb6496":[4,0,69,145,2], "classIoss_1_1TriShell3.html#a5bf8fbe762cbb91d057a644aecacea34":[4,0,69,145,17], "classIoss_1_1TriShell3.html#a5c399b2094722db9709c3f80540b50a8":[4,0,69,145,0], "classIoss_1_1TriShell3.html#a6e9c7dd07e5e92a148701b33061d1dd4":[4,0,69,145,8], "classIoss_1_1TriShell3.html#a71d65344c4cc54507ad01c5999f89e35":[4,0,69,145,23], "classIoss_1_1TriShell3.html#a830f20e54dba1b40d77ad72bee5e5836":[4,0,69,145,11], "classIoss_1_1TriShell3.html#a849f39ba598476953e68b20eb68afcf5":[4,0,69,145,15], "classIoss_1_1TriShell3.html#a8945846e559d73a82c949926ddbe8bd8":[4,0,69,145,5], "classIoss_1_1TriShell3.html#a982f9f10c322d7eed5f2f16e6f7a914e":[4,0,69,145,9], "classIoss_1_1TriShell3.html#ab0089b7b18ba4646977b43755c73f2c3":[4,0,69,145,6], "classIoss_1_1TriShell3.html#ab25e33b89086a7ee7d639919d5d8f107":[4,0,69,145,3], "classIoss_1_1TriShell3.html#abc756a25684952aa129837486d155744":[4,0,69,145,12], "classIoss_1_1TriShell3.html#ac85c51dd7e794a921c51cb7da9966fc9":[4,0,69,145,10], "classIoss_1_1TriShell3.html#ae7df765f22e03ab1e76c30e0b77fcdf5":[4,0,69,145,1], "classIoss_1_1TriShell3.html#aed8950ad60c701b815b8496a0c50e690":[4,0,69,145,20], "classIoss_1_1TriShell3.html#af4adcf209c460b2ebd782db1597601d0":[4,0,69,145,22], "classIoss_1_1TriShell3.html#afa185d68a0c59bd01751a48b97fcfd98":[4,0,69,145,18], "classIoss_1_1TriShell3.html#aff6973b37150283884832ca0a9564dab":[4,0,69,145,4], "classIoss_1_1TriShell4.html":[4,0,69,146], "classIoss_1_1TriShell4.html#a002a93c56b3124909307580a2a7316ae":[4,0,69,146,2], "classIoss_1_1TriShell4.html#a1988b9ea1ca6ff408342c89f2678101e":[4,0,69,146,3], "classIoss_1_1TriShell4.html#a1b9c25f1f7d7b7f995ce4717cdb56102":[4,0,69,146,17], "classIoss_1_1TriShell4.html#a20be75da2c06aaf57c3b4e051a8f9d63":[4,0,69,146,16], "classIoss_1_1TriShell4.html#a34f96eabcb67dd336f4bba6eae6547ae":[4,0,69,146,10], "classIoss_1_1TriShell4.html#a420e5437756539fceb08c38a614cea47":[4,0,69,146,1], "classIoss_1_1TriShell4.html#a4287b9b457030b490a4383ac36087439":[4,0,69,146,8], "classIoss_1_1TriShell4.html#a45d002b40c8e4f7001bf1cea049d7a0e":[4,0,69,146,5], "classIoss_1_1TriShell4.html#a4abc705677e620df0497c6e78b63e7ec":[4,0,69,146,12], "classIoss_1_1TriShell4.html#a4c20572cd3c4110a436a1e1cbfb2f8a9":[4,0,69,146,21], "classIoss_1_1TriShell4.html#a6d01004f3fc5053893de464fe61056f8":[4,0,69,146,14], "classIoss_1_1TriShell4.html#a7afc1d0da6821aefbe1eb103ff50dab4":[4,0,69,146,11], "classIoss_1_1TriShell4.html#a82ddc1635b0291c35c8498122d7e5dc1":[4,0,69,146,4], "classIoss_1_1TriShell4.html#a84d116f292724ce2e2112fa850f9b322":[4,0,69,146,20], "classIoss_1_1TriShell4.html#a87258b7f488a85a8138f0603e9d0acdc":[4,0,69,146,0], "classIoss_1_1TriShell4.html#a888eba93c31eb1b815559d1a77602c38":[4,0,69,146,7], "classIoss_1_1TriShell4.html#a98a21bb0323cb09b92909e66f9ed073c":[4,0,69,146,9], "classIoss_1_1TriShell4.html#aa7e22e4178c14763a481339179b4e137":[4,0,69,146,15], "classIoss_1_1TriShell4.html#aa87c9628c2332642aa96d1e405883238":[4,0,69,146,19], "classIoss_1_1TriShell4.html#aadb36aeda57340bd17137d8783b44e93":[4,0,69,146,22], "classIoss_1_1TriShell4.html#aaf10025253ad5d01cd9db87f4d916991":[4,0,69,146,18], "classIoss_1_1TriShell4.html#ad7afb332445b43a4788a44c63250ee42":[4,0,69,146,6], "classIoss_1_1TriShell4.html#ae9ce2d0c366d5d5c875a5cdda558c3d4":[4,0,69,146,23], "classIoss_1_1TriShell4.html#af1eb529200e7724ca1df486ab1aca437":[4,0,69,146,13], "classIoss_1_1TriShell6.html":[4,0,69,147], "classIoss_1_1TriShell6.html#a0ce4c50290a2f86e7df1e6399b03f046":[4,0,69,147,5], "classIoss_1_1TriShell6.html#a0ea48813e987a2edf0eb2782f0490532":[4,0,69,147,10], "classIoss_1_1TriShell6.html#a24313d5b5259f993b77f5b97d6f2e546":[4,0,69,147,7], "classIoss_1_1TriShell6.html#a2c2ab11aa74661eb2f1f419ca3c380e6":[4,0,69,147,2], "classIoss_1_1TriShell6.html#a3fea7f1a6bca3646c964f3dacb0865c9":[4,0,69,147,21], "classIoss_1_1TriShell6.html#a4641861d7b4a840480f4c237089faef9":[4,0,69,147,11], "classIoss_1_1TriShell6.html#a46b0355e6ca9e177b1b5b346062a8356":[4,0,69,147,4], "classIoss_1_1TriShell6.html#a6962dd09041216a482023cfa6f88c01a":[4,0,69,147,22], "classIoss_1_1TriShell6.html#a6addf0ab034e091a17d078ff745e1d47":[4,0,69,147,16] };
nschloe/seacas
docs/ioss_html/navtreeindex17.js
JavaScript
bsd-3-clause
18,862
/** * The Affix Component * * @module aui-affix */ var win = A.config.win; /** * A base class for Affix. * * Check the [live demo](http://alloyui.com/examples/affix/). * * @class A.Affix * @extends Base * @param {Object} config Object literal specifying scrollspy configuration * properties. * @constructor */ A.Affix = A.Base.create('affix', A.Base, [], { /** * Holds the scroll event handle. * * @type {Node} * @private */ _eventHandle: null, /** * Holds the last event (bottom, default, top). * @type {String} * @private */ _lastPosition: null, /** * Constructor for the Affix component. * * @method initializer * @protected */ initializer: function() { this.publish({ bottom: { defaultFn: this._defAffixBottomFn }, 'default': { defaultFn: this._defAffixFn }, top: { defaultFn: this._defAffixTopFn } }); this.after({ offsetBottomChange: this._afterOffsetChange, offsetTopChange: this._afterOffsetChange }); this.refresh(); this._eventHandle = A.one(win).on('scroll', this._onScroll, this); }, /** * Destructor for the Affix component * @method destructor * @private */ destructor: function() { this._eventHandle.detach(); }, /** * Refreshes the affix component to its current state. * * @method refresh */ refresh: function() { var scrollY = A.DOM.docScrollY(), offsetBottom = this.get('offsetBottom'), offsetTop = this.get('offsetTop'), targetRegion; if ((offsetTop >= 0) && (offsetTop >= scrollY)) { this._handleAffixEvent(A.Affix.EVENTS.TOP); return; } targetRegion = this.get('target').get('region'); if ((offsetBottom >= 0) && ((A.DOM.docHeight() - A.DOM.winHeight() - offsetBottom) <= targetRegion.bottom)) { this._handleAffixEvent(A.Affix.EVENTS.BOTTOM); return; } this._handleAffixEvent(A.Affix.EVENTS.DEFAULT); }, /** * Call the refresh method after changing the offset * * @method _afterOffsetChange * @private */ _afterOffsetChange: function() { this.refresh(); }, /** * Affix bottom position syncing callback function. * * @method _defAffixBottomFn * @private */ _defAffixBottomFn: function() { this._syncClassesUI(A.Affix.EVENTS.BOTTOM); }, /** * Affix default position syncing callback function. * * @method _defAffixFn * @private */ _defAffixFn: function() { this._syncClassesUI(A.Affix.EVENTS.DEFAULT); }, /** * Affix top position syncing callback function. * * @method _defAffixTopFn * @private */ _defAffixTopFn: function() { this._syncClassesUI(A.Affix.EVENTS.TOP); }, /** * Get the `offset` attribute. * * @method _getOffset * @param {Number | Number.NEGATIVE_INFINITY} val * @protected */ _getOffset: function(val) { if (A.Lang.isFunction(val)) { val = val.call(this); } return val; }, /** * Safeguard function for firing the affix change event only when necessary. * * @method _handleAffixEvent * @param {String} Position value, could be 'bottom', 'default' or 'top'. * @private */ _handleAffixEvent: function(position) { if (position !== this._lastPosition) { this.fire(position); } }, /** * Scroll event listener function. * * @method _onScroll * @private */ _onScroll: function() { this.refresh(); }, /** * Sync the target element class based on the affix positioning. * * @method _syncClassesUI * @param {String} Position value, could be 'bottom', 'default' or 'top'. * @private */ _syncClassesUI: function(position) { var target = this.get('target'); target.toggleClass(A.Affix.CSS_CLASSES.BOTTOM, position === A.Affix.EVENTS.BOTTOM); target.toggleClass(A.Affix.CSS_CLASSES.DEFAULT, position === A.Affix.EVENTS.DEFAULT); target.toggleClass(A.Affix.CSS_CLASSES.TOP, position === A.Affix.EVENTS.TOP); this._lastPosition = position; }, /** * Validate the offset type. * * @method _validateOffset * @param {Function | Number | Number.NEGATIVE_INFINITY} val */ _validateOffset: function(val) { if (A.Lang.isFunction(val)) { val = val.call(this); } return A.Lang.isNumber(val) || A.Lang.isFunction(val) || (val === Number.NEGATIVE_INFINITY); } }, { ATTRS: { /** * Defines the bottom offset. * * @attribute offsetBottom * @type {Function | Number} */ offsetBottom: { getter: '_getOffset', validator: '_validateOffset', value: Number.NEGATIVE_INFINITY }, /** * Defines the top offset. * * @attribute offsetTop * @type {Function | Number} */ offsetTop: { getter: '_getOffset', validator: '_validateOffset', value: Number.NEGATIVE_INFINITY }, /** * Defines the target element. * * @attribute target * @type {Node | String} */ target: { setter: A.one } }, /** * Map of events containing `BOTTOM`, `DEFAULT` or `TOP` keys. * * @type {Object} */ EVENTS: { BOTTOM: 'bottom', DEFAULT: 'default', TOP: 'top' }, /** * Map of class names containing `BOTTOM`, `DEFAULT` or `TOP` keys. * * @type {Object} */ CSS_CLASSES: { BOTTOM: A.getClassName('affix', 'bottom'), DEFAULT: A.getClassName('affix'), TOP: A.getClassName('affix', 'top') } });
adorjan/alloy-ui
src/aui-affix/js/aui-affix.js
JavaScript
bsd-3-clause
6,261
export default function(path, width, height) { this._images.push({path:path, width: width, height:height}) return this; };
magjac/d3-graphviz
src/images.js
JavaScript
bsd-3-clause
133
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; const chalk = require('chalk'); const {KEYS} = require('../constants'); const runJestMock = jest.fn(); let terminalWidth; jest.mock('ansi-escapes', () => ({ clearScreen: '[MOCK - clearScreen]', cursorDown: (count = 1) => `[MOCK - cursorDown(${count})]`, cursorHide: '[MOCK - cursorHide]', cursorRestorePosition: '[MOCK - cursorRestorePosition]', cursorSavePosition: '[MOCK - cursorSavePosition]', cursorShow: '[MOCK - cursorShow]', cursorTo: (x, y) => `[MOCK - cursorTo(${x}, ${y})]`, })); jest.mock( '../search_source', () => class { findMatchingTests(pattern) { return {paths: []}; } }, ); jest.doMock('chalk', () => new chalk.constructor({enabled: false})); jest.doMock('strip-ansi'); require('strip-ansi').mockImplementation(str => str); jest.doMock( '../run_jest', () => function() { const args = Array.from(arguments); const [{onComplete}] = args; runJestMock.apply(null, args); // Call the callback onComplete({ snapshot: {}, testResults: [ { testResults: [{title: 'should return the correct index when'}], }, { testResults: [{title: 'should allow test siblings to modify'}], }, { testResults: [{title: 'might get confusing'}], }, { testResults: [ {title: 'should handle length properties that cannot'}, ], }, { testResults: [{title: 'should recognize various types'}], }, { testResults: [{title: 'should recognize null and undefined'}], }, { testResults: [{title: 'should not output colors to pipe'}], }, { testResults: [{title: 'should convert string to a RegExp'}], }, { testResults: [ {title: 'should escape and convert string to a RegExp'}, ], }, { testResults: [{title: 'should convert grep string to a RegExp'}], }, ], }); return Promise.resolve(); }, ); jest.doMock('../lib/terminal_utils', () => ({ getTerminalWidth: () => terminalWidth, })); const watch = require('../watch'); const toHex = char => Number(char.charCodeAt(0)).toString(16); const globalConfig = { watch: true, }; afterEach(runJestMock.mockReset); describe('Watch mode flows', () => { let pipe; let hasteMapInstances; let contexts; let stdin; beforeEach(() => { terminalWidth = 80; pipe = {write: jest.fn()}; hasteMapInstances = [{on: () => {}}]; contexts = [{config: {}}]; stdin = new MockStdin(); }); it('Pressing "T" enters pattern mode', () => { contexts[0].config = {rootDir: ''}; watch(globalConfig, contexts, pipe, hasteMapInstances, stdin); // Write a enter pattern mode stdin.emit(KEYS.T); expect(pipe.write).toBeCalledWith(' pattern › '); const assertPattern = hex => { pipe.write.mockReset(); stdin.emit(hex); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); }; // Write a pattern ['c', 'o', 'n', ' ', '1', '2'].map(toHex).forEach(assertPattern); [KEYS.BACKSPACE, KEYS.BACKSPACE].forEach(assertPattern); ['*'].map(toHex).forEach(assertPattern); // Runs Jest again runJestMock.mockReset(); stdin.emit(KEYS.ENTER); expect(runJestMock).toBeCalled(); // globalConfig is updated with the current pattern expect(runJestMock.mock.calls[0][0].globalConfig).toMatchObject({ onlyChanged: false, testNamePattern: 'con *', watch: true, watchAll: false, }); }); it('can select a specific test name from the typeahead results', () => { contexts[0].config = {rootDir: ''}; watch(globalConfig, contexts, pipe, hasteMapInstances, stdin); // Write a enter pattern mode stdin.emit(KEYS.T); // Write a pattern ['c', 'o', 'n'] .map(toHex) .concat([ KEYS.ARROW_DOWN, KEYS.ARROW_DOWN, KEYS.ARROW_DOWN, KEYS.ARROW_UP, ]) .forEach(key => stdin.emit(key)); stdin.emit(KEYS.ENTER); expect(runJestMock.mock.calls[1][0].globalConfig.testNamePattern).toBe( 'should convert string to a RegExp', ); }); it('Results in pattern mode get truncated appropriately', () => { contexts[0].config = {rootDir: ''}; watch(globalConfig, contexts, pipe, hasteMapInstances, stdin); stdin.emit(KEYS.T); [50, 30].forEach(width => { terminalWidth = width; stdin.emit(KEYS.BACKSPACE); pipe.write.mockReset(); stdin.emit(KEYS.T); expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot(); }); }); }); class MockStdin { constructor() { this._callbacks = []; } setRawMode() {} resume() {} setEncoding() {} on(evt, callback) { this._callbacks.push(callback); } emit(key) { this._callbacks.forEach(cb => cb(key)); } }
skovhus/jest
packages/jest-cli/src/__tests__/watch_test_name_pattern_mode.test.js
JavaScript
bsd-3-clause
5,369
/** * DOCUMENTANTION * ---------------------------------------------------------------------------- * Each key in the .eslintrc corresponds to a page in the rules directory. * [Rules on eslint.org]{@link http://eslint.org/docs/rules/} * * The rest of the otpiosn can be found here: * [Eslint Options][@link http://eslint.org/docs/user-guide/configuring] */ import project from './project'; // Read the eslintrc into JSON let config = project.getJSONConfig('.eslintrc'); /** * Add new rules to the linter */ Object.assign(config.rules, { /** * Since this tool will be used on linting production ready code * lets make it an error to have console statements in the code. */ 'no-console': 2 }); export default config;
jayzawrotny/gulp-casper-concat
gulp/config/eslint.js
JavaScript
bsd-3-clause
742
var url = document.URL; var array = url.split("/"); var base = array[3]; if (array[2] == 'localhost') { var staticurl = '/' + base + '/client/dashboard/reporting'; //var url_action = array[6].split("?")[0]; } else { var staticurl = '/client/dashboard/reporting'; // var url_action = array[5].split("?")[0]; } $(document).ready(function(){ $('.basic_info_menu').click(function(){ $url = $(this).find('a').attr("href"); var res = $url.split("#"); var hash = '#'+res[1]; window.location.hash = hash; leftNavigation(); // now scroll to element with that id }); $('#selectall').click(function(){ var select = $("#selectall").is(":checked"); if(select) { $('.permission_check').prop('checked', true); $('.permission_check').css("pointer-events", "none"); } else { $('.permission_check').prop('checked', false); $('.permission_check').css("pointer-events", "auto"); } }); $('#select_all_0').click(function(){ var select = $("#select_all_0").is(":checked"); if(select) { $('#select_all_0').removeClass('permission_check'); $('.permission_check').prop('checked', true); $('.permission_check').css("pointer-events", "none"); } else { $('.permission_check').prop('checked', false); $('.permission_check').css("pointer-events", "auto"); } }); $('.benefit_plan_info').click(function(){ $url = $(this).find('a').attr("href"); var res = $url.split("#"); var hash = '#'+res[1]; window.location.hash = hash; benefitNavigation(); // now scroll to element with that id }); });
skyinsurance/acars
js/basicscroll.js
JavaScript
bsd-3-clause
1,662
//= require ../store (function () { "use strict"; var AppJobs = FlynnDashboard.Stores.AppJobs = FlynnDashboard.Store.createClass({ displayName: "Stores.AppJobs", getState: function () { return this.state; }, willInitialize: function () { this.props = { appId: this.id.appId }; }, didInitialize: function () {}, didBecomeActive: function () { this.__fetchJobs(); }, getInitialState: function () { return { processes: [] }; }, handleEvent: function () { }, __fetchJobs: function () { FlynnDashboard.client.getAppJobs(this.props.appId).then(function (args) { var res = args[0]; this.setState({ processes: res.map(function (item) { if (item.hasOwnProperty("State")) { item.state = item.State; } return item; }) }); }.bind(this)); } }, Marbles.State); AppJobs.registerWithDispatcher(FlynnDashboard.Dispatcher); })();
flynn-archive/flynn-dashboard-web
lib/javascripts/stores/app-jobs.js
JavaScript
bsd-3-clause
899
$( document ).ready(function() { $('.switch').bootstrapSwitch({onText: 'вкл', offText: 'выкл'}).on('switchChange.bootstrapSwitch', function () { var checkbox = $(this); checkbox.bootstrapSwitch('disabled', true); $.getJSON(checkbox.data('link') + '?' + 'status=' + (checkbox.is(':checked') ? 1 : 0) + '&id=' + checkbox.data('id'), function (response) { if (response.result === 'error') { alert(response.error); } else { checkbox.bootstrapSwitch('disabled', false); } }); }); });
Per1phery/wholetthedogout
web/js/backend/main.js
JavaScript
bsd-3-clause
607
// Restrict output in a codecell to a maximum length define([ 'base/js/namespace', 'jquery', 'notebook/js/outputarea', 'base/js/dialog', 'notebook/js/codecell', 'services/config', 'base/js/utils' ], function(IPython, $, oa, dialog, cc, configmod, utils) { "use strict"; var base_url = utils.get_body_data("baseUrl"); var config = new configmod.ConfigSection('notebook', {base_url: base_url}); // define default values for config parameters var params = { // maximum number of characters the output area is allowed to print limit_output : 10000, // message to print when output is limited limit_ouput_message : "**OUTPUT MUTED**" }; // to be called once config is loaded, this updates default config vals // with the ones specified by the server's config file var update_params = function() { for (var key in params) { if (config.data.hasOwnProperty(key) ){ params[key] = config.data[key]; } } }; function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function makePrintCounter() { var count = 0, currentCount = 0, lastWasCR = false; // Libraries like TQDM don't nessessarily send messages on clean // boundaries (i.e. line breaks). This makes counting stateful! var printCounter = function(str) { for(var i=0; i<str.length; i+=1){ switch(str[i]) { case '\b': lastWasCR = false; currentCount -= 1; break; case '\r': // See if this sets up a CR without an LF. lastWasCR = true; currentCount += 1; break; case '\n': lastWasCR = false; count += currentCount + 1; currentCount = 0; break; default: if(lastWasCR) { currentCount = 1; } else { currentCount += 1; } lastWasCR = false; } } return count + currentCount; }; return printCounter; } config.loaded.then(function() { var MAX_CHARACTERS = params.limit_output; update_params(); if (isNumber(params.limit_output)) MAX_CHARACTERS = params.limit_output; oa.OutputArea.prototype._handle_output = oa.OutputArea.prototype.handle_output; oa.OutputArea.prototype.handle_output = function (msg) { if (this.count === undefined) { this.count=0; } if (this.counter === undefined) { this.counter = makePrintCounter(); } if (this.max_count === undefined) { this.max_count = MAX_CHARACTERS; } console.log("}}}}" + String(msg.content.text)); if(msg.content.text !== undefined) { this.count = this.counter(String(msg.content.text)); console.log(">>>" + String(msg.content.text)); if(this.count > this.max_count) { if (this.drop) return; console.log("limit_output: output exceeded", this.max_count, "characters. Further output muted."); msg.content.text = msg.content.text.substr(0, this.max_count) + params.limit_ouput_message; this.drop = true; } } return this._handle_output(msg); }; cc.CodeCell.prototype._execute = cc.CodeCell.prototype.execute; cc.CodeCell.prototype.execute = function() { // reset counter on execution. this.output_area.count = 0; this.output_area.drop = false; return this._execute(); }; }); var load_ipython_extension = function() { config.load(); }; var extension = { load_ipython_extension : load_ipython_extension }; return extension; });
jbn/IPython-notebook-extensions
nbextensions/usability/limit_output/main.js
JavaScript
bsd-3-clause
4,242
(function(config, models, views, routers, utils, templates) { // This is the top-level piece of UI. views.Application = Backbone.View.extend({ // Events // ------ events: { 'click .toggle-view': 'toggleView' }, toggleView: function (e) { e.preventDefault(); e.stopPropagation(); var link = $(e.currentTarget), route = link.attr('href').replace(/^\//, ''); $('.toggle-view.active').removeClass('active'); link.addClass('active'); router.navigate(route, true); }, // Initialize // ---------- initialize: function () { _.bindAll(this); var that = this; this.header = new views.Header({model: this.model}); // No longer needed // $(window).on('scroll', function() { // if ($(window).scrollTop()>60) { // $('#post').addClass('sticky-menu'); // } else { // $('#post').removeClass('sticky-menu'); // } // }); function calculateLayout() { if (that.mainView && that.mainView.refreshCodeMirror) { that.mainView.refreshCodeMirror(); } } var lazyLayout = _.debounce(calculateLayout, 300); $(window).resize(lazyLayout); }, // Should be rendered just once render: function () { $(this.header.render().el).prependTo(this.el); return this; }, // Helpers // ------- replaceMainView: function (name, view) { $('body').removeClass().addClass('current-view '+name); // Make sure the header gets shown if (name !== "start") $('#header').show(); if (this.mainView) { this.mainView.remove(); } else { $('#main').empty(); } this.mainView = view; $(view.el).appendTo(this.$('#main')); }, // Main Views // ---------- static: function() { this.header.render(); // No-op ;-) }, posts: function (user, repo, branch, path) { this.loading('Loading posts ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { this.loaded(); if (err) return this.notify('error', 'The requested resource could not be found.'); this.header.render(); this.replaceMainView("posts", new views.Posts({ model: data, id: 'posts' }).render()); }, this)); }, post: function (user, repo, branch, path, file, mode) { this.loading('Loading post ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { if (err) return this.notify('error', 'The requested resource could not be found.'); loadPost(user, repo, branch, path, file, _.bind(function (err, data) { this.loaded(); this.header.render(); if (err) return this.notify('error', 'The requested resource could not be found.'); data.preview = !(mode === "edit") || !window.authenticated; data.lang = _.mode(file); this.replaceMainView(window.authenticated ? "post" : "read-post", new views.Post({ model: data, id: 'post' }).render()); var that = this; }, this)); this.header.render(); }, this)); }, newPost: function (user, repo, branch, path) { this.loading('Creating file ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { emptyPost(user, repo, branch, path, _.bind(function(err, data) { this.loaded(); data.jekyll = _.jekyll(path, data.file); data.preview = false; data.markdown = _.markdown(data.file); this.replaceMainView("post", new views.Post({ model: data, id: 'post' }).render()); this.mainView._makeDirty(); app.state.file = data.file; this.header.render(); }, this)); }, this)); }, profile: function(username) { var that = this; app.state.title = username; this.loading('Loading profile ...'); loadRepos(username, function(err, data) { that.header.render(); that.loaded(); data.authenticated = !!window.authenticated; that.replaceMainView("start", new views.Profile({id: "start", model: data}).render()); }); }, start: function(username) { var that = this; app.state.title = ""; this.header.render(); this.replaceMainView("start", new views.Start({ id: "start", model: _.extend(this.model, { authenticated: !!window.authenticated} ) }).render()); }, notify: function(type, message) { this.header.render(); this.replaceMainView("notification", new views.Notification(type, message).render()); }, loading: function(msg) { $('#main').html('<div class="loading"><span>'+ msg || 'Loading ...' +'</span></div>'); }, loaded: function() { $('#main .loading').remove(); } }); }).apply(this, window.args);
dilbapat/dilbapat.github.com
_includes/views/application.js
JavaScript
bsd-3-clause
4,667
/* 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 20a23.74 23.74 0 00-23.73 23.85c0 16.48 17 31.59 22.23 35.59a2.44 2.44 0 003.12 0c5.25-4.12 22.11-19.11 22.11-35.59A23.74 23.74 0 0050 20zm0 42a18.25 18.25 0 1118.24-18.27A18.3 18.3 0 0150 62z"},{"d":"M43 33.23a5.07 5.07 0 105.08 5.07A5.07 5.07 0 0043 33.23zM43 41a2.66 2.66 0 112.66-2.66A2.66 2.66 0 0143 41zM45.28 54.63a.47.47 0 01-.34.22h-1.62a.43.43 0 01-.37-.22.36.36 0 010-.42l11.68-21.4a.48.48 0 01.37-.21h1.74a.42.42 0 01.2.57zM57 44.13a5.07 5.07 0 105.08 5.06A5.08 5.08 0 0057 44.13zm0 7.72a2.65 2.65 0 112.66-2.64A2.65 2.65 0 0157 51.85z"}]};
salesforce/design-system-react
icons/standard/field_sales.js
JavaScript
bsd-3-clause
800