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 |
|---|---|---|---|---|---|
/*!
* Cooki v1.0.0
* http://k-legrand.fr
*
* Copyright 2014 Contributors
* Released under the MIT license
* https://github.com/Manoz/Cooki/blob/master/LICENSE
*/
/*!
* Your website scripts below
*/
| Manoz/Cooki | dist/js/cooki.js | JavaScript | mit | 207 |
/*jslint node: true */
/*global module, require*/
'use strict';
var subjectType = require('./type');
var subjectValue = require('./value');
/**
* Given the parts of speech, this returns an subjects type & value.
* @param {Object} parts The parts of speech.
* @return {Object} The parsed subjects type & value.
*/
module.exports = function subject(parts) {
return {
type: subjectType(parts),
value: subjectValue(parts)
};
};
| defstream/nl3 | lib/subject/index.js | JavaScript | mit | 453 |
/**
* Sample content to test the concat and minify grunt plugins.
*/
function sampleA() {
'use strict';
window.console.log("Sample A");
}
sampleA();
/**
* Sample content to test the concat and minify grunt plugins.
*/
function sampleB() {
'use strict';
window.console.log("Sample B");
}
sampleB();
| gemrecas/portfolio-gemma | src/scripts/sample1.js | JavaScript | mit | 313 |
'use strict';
describe('Service: header', function () {
// load the service's module
beforeEach(module('musicyaoBackendApp'));
// instantiate service
var header;
beforeEach(inject(function (_header_) {
header = _header_;
}));
it('should do something', function () {
expect(!!header).toBe(true);
});
});
| yaoshining/musicyao-backend | test/spec/services/header.js | JavaScript | mit | 332 |
var Q = require('q');
var uuid = require('uuid');
var crypto = require('../../../../crypto/crypto');
function Connect() {
}
var connect = new Connect();
module.exports = connect;
Connect.prototype.init = function(letter, handler) {
console.log(letter);
var deferred = Q.defer();
var back_letter = {
signature: letter.signature,
directive: {
connect: {
init: null
}
}
};
deferred.resolve(back_letter);
return deferred.promise;
};
Connect.prototype.crypto = function(letter, handler) {
let deferred = Q.defer();
let public_str = letter.crypto.public_str;
// 使用uuid 作为密码
// let secret = uuid.v4();
let secret = '12345678';
let encryptSecret = crypto.publicEncrypt(public_str, secret);
let json = encryptSecret.toJSON();
console.log('密码为:');
console.log(secret);
// console.log(encryptSecret.toString());
letter.crypto.encryptSecret = JSON.stringify(encryptSecret.toJSON());
deferred.resolve(letter);
setTimeout(function() {
handler.crypto = true;
handler.encryptSecret = secret;
let letter = {
directive: {
test: null
}
};
letter = JSON.stringify(letter);
letter = crypto.cipher(letter, secret);
handler.evenEmitter.emit('letter', letter);
}, 5000);
return deferred.promise;
};
| xunull/letter | lib/core/directive/net.connect/client/connect.js | JavaScript | mit | 1,450 |
let EventEmitter = require('events').EventEmitter;
let telecom;
describe("Interface Unit Tests", function () {
it('should create a new interface', function () {
telecom = new Telecom();
expect(telecom).to.be.an.instanceOf(EventEmitter);
expect(telecom).to.have.property('parallelize');
expect(telecom).to.have.property('pipeline');
expect(telecom).to.have.property('isMaster', true);
});
it('should return bundled interfaces', function () {
expect(telecom.interfaces).to.be.an.Object;
expect(telecom.interfaces).to.have.property('TCP');
});
it('should create a new pipeline', function () {
let intf = new telecom.interfaces.TCP(8000);
expect(intf).to.be.an.instanceOf(Interface);
let pipeline = telecom.pipeline(intf);
expect(pipeline).to.be.an.instanceOf(Pipeline);
});
}); | schahriar/telecom | test/Telecom.unit.js | JavaScript | mit | 835 |
// Copyright 2015-2018 FormBucket LLC
// ISURL returns true when the value matches the regex for a uniform resource locator.
export default function isurl(str) {
// credit: http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url
var pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
); // fragment locator
return pattern.test(str);
}
| FunctionFoundry/functionfoundry | src/isurl.js | JavaScript | mit | 652 |
/*
MIT License
Copyright (c) 2016 Christian Rafael
JS Object to CSS String Parser
christian@paradix.com.br
*/
function parseCSS( object_css ) {
function parseClass( _class, properties ) {
return String().concat( _class, " { ", parseProperties( properties ), " } " );
}
function parseProperties( properties ) {
var css_properties = String();
for (var prop in properties) {
css_properties = css_properties.concat(
typeof properties[ prop ] === "object" && parseClass( prop, properties[ prop ] ) || String().concat( prop, " : ", properties[ prop ] ),
typeof properties[ prop ] !== "object" && ";" || ""
);
}
return css_properties;
}
var css_str = String();
for ( var _class in object_css ) {
css_str = css_str.concat( parseClass( _class, object_css[ _class ] ) );
}
return css_str;
}
| christianrss/object-css-parser | object-css-parser.js | JavaScript | mit | 934 |
'use strict';
const fetchUrl = require('./fetchUrl');
/**
* @param {Function} fetch - fetch API compatible function
* @param {string} source
* @param {Object} [fetchOptions={}]
* @returns {Promise.<DefinitionProvider>}
*/
function urlProviderFactory (fetch, source, fetchOptions = {}) {
let urlProvider = source;
if (typeof source === 'string') {
urlProvider = () => source;
}
/**
* @param {Function} [callback]
*/
return (progressCallback) => {
const deferredUrls = urlProvider();
return Promise.resolve(deferredUrls)
.then((oneOrMoreUrls) => {
if (typeof oneOrMoreUrls === 'object') {
const result = {
null: {}
};
return Object.keys(oneOrMoreUrls).reduce((prev, key) => prev.then(() => {
const url = oneOrMoreUrls[key];
return fetchUrl(fetch, url, fetchOptions).then((urlResult) => {
result[key] = urlResult;
if (progressCallback) {
progressCallback();
}
});
}), Promise.resolve()).then(() => result);
} else if (typeof oneOrMoreUrls === 'string') {
return fetchUrl(fetch, oneOrMoreUrls, fetchOptions)
.then(urlResult => ({ null: urlResult }));
}
throw new Error('Unsupported url type');
});
};
}
module.exports = urlProviderFactory;
| Storyous/features-js | src/urlProviderFactory.js | JavaScript | mit | 1,632 |
'use strict';
/**
* @ngdoc function
* @name yeoprojectApp.controller:MiembrosCtrl
* @description
* # MiembrosCtrl
* Controller of the yeoprojectApp
*/
angular.module('yeoprojectApp')
.controller('MiembrosCtrl', function ($scope,$http,$modal) {
$http.get('http://localhost:9000/miembros.json').success(function (data) {
$scope.miembros= data;
});
$scope.gridOptions={
data:'miembros',
showGroupPanel: true,
showFilter:true,
enableCellSelection: true,
enableRowSelection: false,
enableCellEdit: true,
columnDefs:[
{field:'no', displayName:'Nº.'},
{field:'nombre', displayName:'Nombre'},
{field:'fidelidad', displayName:'Puntos Fidelidad'},
{field:'fechaUnion', displayName:'Fecha de Unión'},
{field:'tipoMiembro', displayName:'Tipo de Miembro'}]
};
$scope.showModal=function () {
$scope.nuevoMiembro={}; //objeto vacio para almacenar
var modalInstance= $modal.open({
templateUrl: 'views/add-miembros.html',
controller:'AddNuevoMiembroCtrl',
resolve:{
nuevoMiembro: function () {
return $scope.nuevoMiembro;
}
}
});
modalInstance.result.then(function(selectedItem){
$scope.miembros.push({
no: $scope.miembros.length + 1,
nombre: $scope.nuevoMiembro.nombre,
tipoMiembro: $scope.nuevoMiembro.tipoMiembro,
fidelidad: $scope.nuevoMiembro.fidelidad,
fechaUnion: $scope.nuevoMiembro.fechaUnion
});
});
};
})
.controller('AddNuevoMiembroCtrl',function ($scope,$modalInstance,nuevoMiembro) {
$scope.nuevoMiembro= nuevoMiembro;
$scope.salvarNuevoMiembro=function () {
$modalInstance.close(nuevoMiembro);
};
$scope.cancel= function () {
$modalInstance.dismiss('cancel');
};
});
| superjosan/PrototipoYeoman | yeoproject/app/scripts/controllers/miembros.js | JavaScript | mit | 1,789 |
/// <reference path="jquery-ui-1.10.3.js" />
/// <reference path="jquery-2.0.3.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
/// <reference path="knockout-2.1.0.debug.js" />
/// <reference path="modernizr-2.5.3.js" />
/// <reference path="bootstrap.js"/>
| alastairs/cgowebsite | src/CGO.Web/Scripts/_references.js | JavaScript | mit | 326 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'removeformat', 'sv', {
toolbar: 'Radera formatering'
} );
| otto-torino/gino | ckeditor/plugins/removeformat/lang/sv.js | JavaScript | mit | 259 |
(function(DOM, COMPONENT_CLASS) {
"use strict";
if ("orientation" in window) return; // skip mobile/tablet browsers
// polyfill timeinput for desktop browsers
var htmlEl = DOM.find("html"),
timeparts = function(str) {
str = str.split(":");
if (str.length === 2) {
str[0] = parseFloat(str[0]);
str[1] = parseFloat(str[1]);
} else {
str = [];
}
return str;
},
zeropad = function(value) { return ("00" + value).slice(-2) },
ampm = function(pos, neg) { return htmlEl.get("lang") === "en-US" ? pos : neg },
formatISOTime = function(hours, minutes, ampm) {
return zeropad(ampm === "PM" ? hours + 12 : hours) + ":" + zeropad(minutes);
};
DOM.extend("input[type=time]", {
constructor: function() {
var timeinput = DOM.create("input[type=hidden name=${name}]", {name: this.get("name")}),
ampmspan = DOM.create("span.${c}-meridian>(select>option>{AM}^option>{PM})+span>{AM}", {c: COMPONENT_CLASS}),
ampmselect = ampmspan.child(0);
this
// drop native implementation and clear name attribute
.set({type: "text", maxlength: 5, name: null})
.addClass(COMPONENT_CLASS)
.on("change", this.onChange.bind(this, timeinput, ampmselect))
.on("keydown", this.onKeydown, ["which", "shiftKey"])
.after(ampmspan, timeinput);
ampmselect.on("change", this.onMeridianChange.bind(this, timeinput, ampmselect));
// update value correctly on form reset
this.parent("form").on("reset", this.onFormReset.bind(this, timeinput, ampmselect));
// patch set method to update visible input as well
timeinput.set = this.onValueChanged.bind(this, timeinput.set, timeinput, ampmselect);
// update hidden input value and refresh all visible controls
timeinput.set(this.get()).data("defaultValue", timeinput.get());
// update default values to be formatted
this.set("defaultValue", this.get());
ampmselect.next().data("defaultValue", ampmselect.get());
if (this.matches(":focus")) timeinput.fire("focus");
},
onValueChanged: function(setter, timeinput, ampmselect) {
var parts, hours, minutes;
setter.apply(timeinput, Array.prototype.slice.call(arguments, 3));
if (arguments.length === 4) {
parts = timeparts(timeinput.get());
hours = parts[0];
minutes = parts[1];
// select appropriate AM/PM
ampmselect.child((hours -= 12) > 0 ? 1 : Math.min(hours += 12, 0)).set("selected", true);
// update displayed AM/PM
ampmselect.next().set(ampmselect.get());
// update visible input value, need to add zero padding to minutes
this.set(hours < ampm(13, 24) && minutes < 60 ? hours + ":" + zeropad(minutes) : "");
}
return timeinput;
},
onKeydown: function(which, shiftKey) {
return which === 186 && shiftKey || which < 58;
},
onChange: function(timeinput, ampmselect) {
var parts = timeparts(this.get()),
hours = parts[0],
minutes = parts[1],
value = "";
if (hours < ampm(13, 24) && minutes < 60) {
// refresh hidden input with new value
value = formatISOTime(hours, minutes, ampmselect.get());
} else if (parts.length === 2) {
// restore previous valid value
value = timeinput.get();
}
timeinput.set(value);
},
onMeridianChange: function(timeinput, ampmselect) {
// update displayed AM/PM
ampmselect.next().set(ampmselect.get());
// adjust time in hidden input
timeinput.set(function(el) {
var parts = timeparts(el.get()),
hours = parts[0],
minutes = parts[1];
if (ampmselect.get() === "AM") hours -= 12;
return formatISOTime(hours, minutes, ampmselect.get());
});
},
onFormReset: function(timeinput, ampmselect) {
timeinput.set(timeinput.data("defaultValue"));
ampmselect.next().set(ampmselect.data("defaultValue"));
}
});
}(window.DOM, "better-timeinput"));
| chemerisuk/better-timeinput-polyfill | src/better-timeinput-polyfill.js | JavaScript | mit | 4,655 |
var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
// require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
// Specify flash path.
// On Windows, it might be /path/to/pepflashplayer.dll
// On Mac, /path/to/PepperFlashPlayer.plugin
// On Linux, /path/to/libpepflashplayer.so
// app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so');
app.commandLine.appendSwitch('ppapi-flash-path', '/Applications/Google Chrome.app/Contents/Versions/44.0.2403.125/Google Chrome Framework.framework/Internet Plug-Ins/PepperFlash/PepperFlashPlayer.plugin');
// Specify flash version, for example, v17.0.0.169
app.commandLine.appendSwitch('ppapi-flash-version', '18.0.0.209');
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({
'accept-first-mouse': true,
'always-on-top': true,
'auto-hide-menu-bar': true,
'dark-theme': true,
'frame': false,
'height': 600,
'resizable': true,
'show': false,
'title': 'StreamShell',
'width': 800,
'web-preferences': {
'plugins': true
}
});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object
mainWindow = null;
});
// Display the window only once the DOM is ready
mainWindow.webContents.on('did-finish-load', function() {
setTimeout(function() {
mainWindow.show();
// mainWindow.openDevTools({detach: true});
}, 40);
});
});
| robinbolton/StreamShell | app/main.js | JavaScript | mit | 2,241 |
import React from 'react';
import {shallow} from 'enzyme';
import AboutPage from './AboutPage';
describe('<AboutPage />', () => {
it('should have a header called \'About\'', () => {
const wrapper = shallow(<AboutPage />);
const actual = wrapper.find('h2').text();
const expected = 'About';
expect(actual).toEqual(expected);
});
it('should have a header with \'alt-header\' class', () => {
const wrapper = shallow(<AboutPage />);
const actual = wrapper.find('h2').prop('className');
const expected = 'alt-header';
expect(actual).toEqual(expected);
});
it('should link to an unknown route path', () => {
const wrapper = shallow(<AboutPage />);
const actual = wrapper.findWhere(n => n.prop('to') === '/badlink').length;
const expected = 1;
expect(actual).toEqual(expected);
});
});
| marinbgd/coolbeer | src/components/About/AboutPage.spec.js | JavaScript | mit | 815 |
// Generated on 2015-03-17 using generator-angular 0.11.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
server: {
options: {
map: true,
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
]
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'sounds/{,*/}*.{wav,mp3}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
},
{
expand: true,
dot: true,
cwd: 'bower_components/fontawesome',
src: ['fonts/*.*'],
dest: '<%= yeoman.dist %>'
},
{
//for bootstrap fonts
expand: true,
dot: true,
cwd: 'bower_components/bootstrap/dist',
src: ['fonts/*.*'],
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
},
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
| kokeshii/UrgeZapper | Gruntfile.js | JavaScript | mit | 11,066 |
/*jslint node: true */
"use strict";
var async = require('async');
var db = require('./db.js');
var constants = require('./constants.js');
var conf = require('./conf.js');
var objectHash = require('./object_hash.js');
var ecdsaSig = require('./signature.js');
var _ = require('lodash');
var storage = require('./storage.js');
var composer = require('./composer.js');
var Definition = require("./definition.js");
var ValidationUtils = require("./validation_utils.js");
var eventBus = require("./event_bus.js");
function repeatString(str, times){
if (str.repeat)
return str.repeat(times);
return (new Array(times+1)).join(str);
}
// with bNetworkAware=true, last_ball_unit is added, the definition is taken at this point, and the definition is added only if necessary
function signMessage(message, from_address, signer, bNetworkAware, handleResult){
if (typeof bNetworkAware === 'function') {
handleResult = bNetworkAware;
bNetworkAware = false;
}
var objAuthor = {
address: from_address,
authentifiers: {}
};
var objUnit = {
version: constants.version,
signed_message: message,
authors: [objAuthor]
};
function setDefinitionAndLastBallUnit(cb) {
if (bNetworkAware) {
composer.composeAuthorsAndMciForAddresses(db, [from_address], signer, function (err, authors, last_ball_unit) {
if (err)
return handleResult(err);
objUnit.authors = authors;
objUnit.last_ball_unit = last_ball_unit;
cb();
});
}
else {
signer.readDefinition(db, from_address, function (err, arrDefinition) {
if (err)
throw Error("signMessage: can't read definition: " + err);
objAuthor.definition = arrDefinition;
cb();
});
}
}
var assocSigningPaths = {};
signer.readSigningPaths(db, from_address, function(assocLengthsBySigningPaths){
var arrSigningPaths = Object.keys(assocLengthsBySigningPaths);
assocSigningPaths[from_address] = arrSigningPaths;
for (var j=0; j<arrSigningPaths.length; j++)
objAuthor.authentifiers[arrSigningPaths[j]] = repeatString("-", assocLengthsBySigningPaths[arrSigningPaths[j]]);
setDefinitionAndLastBallUnit(function(){
var text_to_sign = objectHash.getSignedPackageHashToSign(objUnit);
async.each(
objUnit.authors,
function(author, cb2){
var address = author.address;
async.each( // different keys sign in parallel (if multisig)
assocSigningPaths[address],
function(path, cb3){
if (signer.sign){
signer.sign(objUnit, {}, address, path, function(err, signature){
if (err)
return cb3(err);
// it can't be accidentally confused with real signature as there are no [ and ] in base64 alphabet
if (signature === '[refused]')
return cb3('one of the cosigners refused to sign');
author.authentifiers[path] = signature;
cb3();
});
}
else{
signer.readPrivateKey(address, path, function(err, privKey){
if (err)
return cb3(err);
author.authentifiers[path] = ecdsaSig.sign(text_to_sign, privKey);
cb3();
});
}
},
function(err){
cb2(err);
}
);
},
function(err){
if (err)
return handleResult(err);
console.log(require('util').inspect(objUnit, {depth:null}));
handleResult(null, objUnit);
}
);
});
});
}
function validateSignedMessage(conn, objSignedMessage, address, handleResult) {
if (!handleResult) {
handleResult = objSignedMessage;
objSignedMessage = conn;
conn = db;
}
if (typeof objSignedMessage !== 'object')
return handleResult("not an object");
if (ValidationUtils.hasFieldsExcept(objSignedMessage, ["signed_message", "authors", "last_ball_unit", "timestamp", "version"]))
return handleResult("unknown fields");
if (!('signed_message' in objSignedMessage))
return handleResult("no signed message");
if ("version" in objSignedMessage && constants.supported_versions.indexOf(objSignedMessage.version) === -1)
return handleResult("unsupported version: " + objSignedMessage.version);
var authors = objSignedMessage.authors;
if (!ValidationUtils.isNonemptyArray(authors))
return handleResult("no authors");
if (!address && !ValidationUtils.isArrayOfLength(authors, 1))
return handleResult("authors not an array of len 1");
var the_author;
for (var i = 0; i < authors.length; i++){
var author = authors[i];
if (ValidationUtils.hasFieldsExcept(author, ['address', 'definition', 'authentifiers']))
return handleResult("foreign fields in author");
if (author.address === address)
the_author = author;
else if (!ValidationUtils.isValidAddress(author.address))
return handleResult("not valid address");
if (!ValidationUtils.isNonemptyObject(author.authentifiers))
return handleResult("no authentifiers");
}
if (!the_author) {
if (address)
return cb("not signed by the expected address");
the_author = authors[0];
}
var objAuthor = the_author;
var bNetworkAware = ("last_ball_unit" in objSignedMessage);
if (bNetworkAware && !ValidationUtils.isValidBase64(objSignedMessage.last_ball_unit, constants.HASH_LENGTH))
return handleResult("invalid last_ball_unit");
function validateOrReadDefinition(cb, bRetrying) {
var bHasDefinition = ("definition" in objAuthor);
if (bNetworkAware) {
conn.query("SELECT main_chain_index, timestamp FROM units WHERE unit=?", [objSignedMessage.last_ball_unit], function (rows) {
if (rows.length === 0) {
var network = require('./network.js');
if (!conf.bLight && !network.isCatchingUp() || bRetrying)
return handleResult("last_ball_unit " + objSignedMessage.last_ball_unit + " not found");
if (conf.bLight)
network.requestHistoryFor([objSignedMessage.last_ball_unit], [objAuthor.address], function () {
validateOrReadDefinition(cb, true);
});
else
eventBus.once('catching_up_done', function () {
// no retry flag, will retry multiple times until the catchup is over
validateOrReadDefinition(cb);
});
return;
}
bRetrying = false;
var last_ball_mci = rows[0].main_chain_index;
var last_ball_timestamp = rows[0].timestamp;
storage.readDefinitionByAddress(conn, objAuthor.address, last_ball_mci, {
ifDefinitionNotFound: function (definition_chash) { // first use of the definition_chash (in particular, of the address, when definition_chash=address)
if (!bHasDefinition) {
if (!conf.bLight || bRetrying)
return handleResult("definition expected but not provided");
var network = require('./network.js');
return network.requestHistoryFor([], [objAuthor.address], function () {
validateOrReadDefinition(cb, true);
});
}
if (objectHash.getChash160(objAuthor.definition) !== definition_chash)
return handleResult("wrong definition: "+objectHash.getChash160(objAuthor.definition) +"!=="+ definition_chash);
cb(objAuthor.definition, last_ball_mci, last_ball_timestamp);
},
ifFound: function (arrAddressDefinition) {
if (bHasDefinition)
return handleResult("should not include definition");
cb(arrAddressDefinition, last_ball_mci, last_ball_timestamp);
}
});
});
}
else {
if (!bHasDefinition)
return handleResult("no definition");
try {
if (objectHash.getChash160(objAuthor.definition) !== objAuthor.address)
return handleResult("wrong definition: " + objectHash.getChash160(objAuthor.definition) + "!==" + objAuthor.address);
} catch (e) {
return handleResult("failed to calc address definition hash: " + e);
}
cb(objAuthor.definition, -1, 0);
}
}
validateOrReadDefinition(function (arrAddressDefinition, last_ball_mci, last_ball_timestamp) {
var objUnit = _.clone(objSignedMessage);
objUnit.messages = []; // some ops need it
try {
var objValidationState = {
unit_hash_to_sign: objectHash.getSignedPackageHashToSign(objSignedMessage),
last_ball_mci: last_ball_mci,
last_ball_timestamp: last_ball_timestamp,
bNoReferences: !bNetworkAware
};
}
catch (e) {
return handleResult("failed to calc unit_hash_to_sign: " + e);
}
// passing db as null
Definition.validateAuthentifiers(
conn, objAuthor.address, null, arrAddressDefinition, objUnit, objValidationState, objAuthor.authentifiers,
function (err, res) {
if (err) // error in address definition
return handleResult(err);
if (!res) // wrong signature or the like
return handleResult("authentifier verification failed");
handleResult(null, last_ball_mci);
}
);
});
}
// inconsistent for multisig addresses
function validateSignedMessageSync(objSignedMessage){
var err;
var bCalledBack = false;
validateSignedMessage(objSignedMessage, function(_err){
err = _err;
bCalledBack = true;
});
if (!bCalledBack)
throw Error("validateSignedMessage is not sync");
return err;
}
exports.signMessage = signMessage;
exports.validateSignedMessage = validateSignedMessage;
exports.validateSignedMessageSync = validateSignedMessageSync;
| kakysha/byteballcore | signed_message.js | JavaScript | mit | 9,071 |
'use strict';
require('require-dir')('./tasks'); | Appchord/servicenow-build | gulpfile.js | JavaScript | mit | 51 |
'use strict';
//Games service used for games REST endpoint
angular.module('mean.games').factory('Games', ['$resource',
function($resource) {
return $resource('games/:gameid', {
gameid: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
| EugeneZ/dungeonlords | packages/games/public/services/games.js | JavaScript | mit | 318 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Array.prototype.es6
* @polyfill
* @nolint
*/
/* eslint-disable no-bitwise, no-extend-native, radix, no-self-compare */
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
function findIndex(predicate, context) {
if (this == null) {
throw new TypeError(
'Array.prototype.findIndex called on null or undefined'
);
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
const list = Object(this);
const length = list.length >>> 0;
for (let i = 0; i < length; i++) {
if (predicate.call(context, list[i], i, list)) {
return i;
}
}
return -1;
}
if (!Array.prototype.findIndex) {
Object.defineProperty(Array.prototype, 'findIndex', {
enumerable: false,
writable: true,
configurable: true,
value: findIndex,
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
enumerable: false,
writable: true,
configurable: true,
value(predicate, context) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
const index = findIndex.call(this, predicate, context);
return index === -1 ? undefined : this[index];
},
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
enumerable: false,
writable: true,
configurable: true,
value(searchElement) {
const O = Object(this);
const len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
const n = parseInt(arguments[1]) || 0;
let k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
let currentElement;
while (k < len) {
currentElement = O[k];
if (
searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)
) {
return true;
}
k++;
}
return false;
},
});
}
| callstack-io/haul | packages/haul-preset-0.59/vendor/polyfills/Array.prototype.es6.js | JavaScript | mit | 2,507 |
//var application = require("application");
//application.mainModule = "main-page";
//application.cssFile = "./app.css";
var map = new Map();
map.set("a", "b");
log(map);
application.start();
//var application = new System.Windows.Application();
//application.Run(new System.Windows.Window()); | zhongzf/nativescript-dotnet-runtime | chakra-runtime/app/app.js | JavaScript | mit | 299 |
const R = require('aws-response');
const f = require('../contactGetRequests/index');
exports.handler = R(f);
| AWS-Zombie-No-Team/core | functions/contactgetrequests.js | JavaScript | mit | 110 |
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'fakeobjects', 'en-au', {
anchor: 'Anchor',
flash: 'Flash Animation',
hiddenfield: 'Hidden Field',
iframe: 'IFrame',
unknown: 'Unknown Object'
} );
| otto-torino/gino | ckeditor/plugins/fakeobjects/lang/en-au.js | JavaScript | mit | 356 |
Ext.define('Ext.slider.Widget', {
extend: 'Ext.Widget',
alias: 'widget.sliderwidget',
// Required to pull in the styles
requires: [
'Ext.slider.Multi'
],
cachedConfig: {
vertical: false,
cls: Ext.baseCSSPrefix + 'slider',
baseCls: Ext.baseCSSPrefix + 'slider'
},
config: {
/**
* @cfg {Boolean} clickToChange
* Determines whether or not clicking on the Slider axis will change the slider.
*/
clickToChange : true,
ui: 'widget',
value: 0,
minValue: 0,
maxValue: 100
},
defaultBindProperty: 'value',
thumbCls: Ext.baseCSSPrefix + 'slider-thumb',
horizontalProp: 'left',
getElementConfig: function() {
return {
reference: 'element',
cls: Ext.baseCSSPrefix + 'slider',
listeners: {
mousedown: 'onMouseDown',
dragstart: 'cancelDrag',
drag: 'cancelDrag',
dragend: 'cancelDrag'
},
children: [{
reference: 'endEl',
cls: Ext.baseCSSPrefix + 'slider-end',
children: [{
reference: 'innerEl',
cls: Ext.baseCSSPrefix + 'slider-inner'
}]
}]
};
},
applyValue: function(value) {
var i, len;
if (Ext.isArray(value)) {
value = Ext.Array.map(Ext.Array.from(value), Number);
for (i = 0, len = value.length; i < len; ++i) {
this.setThumbValue(i, value[i]);
}
} else {
this.setThumbValue(0, value);
}
return value;
},
updateVertical: function(vertical, oldVertical) {
this.element.removeCls(Ext.baseCSSPrefix + 'slider-' + (oldVertical ? 'vert' : 'horz'));
this.element.addCls( Ext.baseCSSPrefix + 'slider-' + (vertical ? 'vert' : 'horz'));
},
doSetHeight: function(height) {
this.callParent(arguments);
this.endEl.dom.style.height = this.innerEl.dom.style.height = '100%';
},
cancelDrag: function(e) {
// prevent the touch scroller from scrolling when the slider is being dragged
e.stopPropagation();
},
getThumb: function(ordinal) {
var me = this,
thumbConfig,
result = (me.thumbs || (me.thumbs = []))[ordinal];
if (!result) {
thumbConfig = {
cls: me.thumbCls,
style: {}
};
thumbConfig['data-thumbIndex'] = ordinal;
result = me.thumbs[ordinal] = me.innerEl.createChild(thumbConfig);
}
return result;
},
getThumbPositionStyle: function() {
return this.getVertical() ? 'bottom' : (this.rtl && Ext.rtl ? 'right' : 'left');
},
// TODO: RTL? How in this paradigm?
getRenderTree: function() {
var me = this,
rtl = me.rtl;
if (rtl && Ext.rtl) {
me.baseCls += ' ' + (Ext.rtl.util.Renderable.prototype._rtlCls);
me.horizontalProp = 'right';
} else if (rtl === false) {
me.addCls(Ext.rtl.util.Renderable.prototype._ltrCls);
}
return me.callParent();
},
update: function() {
var me = this,
values = me.getValue(),
len = values.length,
i;
for (i = 0; i < len; i++) {
this.thumbs[i].dom.style[me.getThumbPositionStyle()] = me.calculateThumbPosition(values[i]) + '%';
}
},
onMouseDown: function(e) {
var me = this,
thumb,
trackPoint = e.getXY(),
delta;
if (!me.disabled && e.button === 0) {
thumb = e.getTarget('.' + me.thumbCls, null, true);
if (thumb) {
me.promoteThumb(thumb);
me.captureMouse(me.onMouseMove, me.onMouseUp, [thumb], 1);
delta = me.pointerOffset = thumb.getXY();
// Work out the delta of the pointer from the dead centre of the thumb.
// Slider.getTrackPoint positions the centre of the slider at the reported
// pointer position, so we have to correct for that in getValueFromTracker.
delta[0] += Math.floor(thumb.getWidth() / 2) - trackPoint[0];
delta[1] += Math.floor(thumb.getHeight() / 2) - trackPoint[1];
} else {
if (me.getClickToChange()) {
trackPoint = me.getTrackpoint(trackPoint);
if (trackPoint != null) {
me.onClickChange(trackPoint);
}
}
}
}
},
/**
* @private
* Moves the thumb to the indicated position.
* Only changes the value if the click was within this.clickRange.
* @param {Number} trackPoint local pixel offset **from the origin** (left for horizontal and bottom for vertical) along the Slider's axis at which the click event occured.
*/
onClickChange : function(trackPoint) {
var me = this,
thumb, index;
// How far along the track *from the origin* was the click.
// If vertical, the origin is the bottom of the slider track.
//find the nearest thumb to the click event
thumb = me.getNearest(trackPoint);
index = parseInt(thumb.getAttribute('data-thumbIndex'), 10);
me.setThumbValue(index, Ext.util.Format.round(me.reversePixelValue(trackPoint), me.decimalPrecision), undefined, true);
},
/**
* @private
* Returns the nearest thumb to a click event, along with its distance
* @param {Number} trackPoint local pixel position along the Slider's axis to find the Thumb for
* @return {Object} The closest thumb object and its distance from the click event
*/
getNearest: function(trackPoint) {
var me = this,
clickValue = me.reversePixelValue(trackPoint),
nearestDistance = me.getRange() + 5, //add a small fudge for the end of the slider
nearest = null,
thumbs = me.thumbs,
i = 0,
len = thumbs.length,
thumb,
value,
dist;
for (; i < len; i++) {
thumb = thumbs[i];
value = me.reversePercentageValue(parseInt(thumb.dom.style[me.getThumbPositionStyle()], 10));
dist = Math.abs(value - clickValue);
if (Math.abs(dist) <= nearestDistance) {
nearest = thumb;
nearestDistance = dist;
}
}
return nearest;
},
/**
* @private
* Moves the given thumb above all other by increasing its z-index. This is called when as drag
* any thumb, so that the thumb that was just dragged is always at the highest z-index. This is
* required when the thumbs are stacked on top of each other at one of the ends of the slider's
* range, which can result in the user not being able to move any of them.
* @param {Ext.slider.Thumb} topThumb The thumb to move to the top
*/
promoteThumb: function(topThumb) {
var thumbs = this.thumbs,
ln = thumbs.length,
thumb, i;
topThumb = Ext.getDom(topThumb);
for (i = 0; i < ln; i++) {
thumb = thumbs[i];
thumb.setStyle('z-index', thumb.dom === topThumb ? 1000 : '');
}
},
onMouseMove: function(e, thumb) {
var me = this,
trackerXY = e.getXY(),
trackPoint,
newValue;
trackerXY[0] += this.pointerOffset[0];
trackerXY[1] += this.pointerOffset[1];
trackPoint = me.getTrackpoint(trackerXY);
// If dragged out of range, value will be undefined
if (trackPoint != null) {
newValue = me.reversePixelValue(trackPoint);
me.setThumbValue(thumb.getAttribute('data-thumbIndex'), newValue, false);
}
},
onMouseUp: function(e, thumb) {
var me = this,
trackerXY = e.getXY(),
trackPoint,
newValue;
trackerXY[0] += this.pointerOffset[0];
trackerXY[1] += this.pointerOffset[1];
trackPoint = me.getTrackpoint(trackerXY);
// If dragged out of range, value will be undefined
if (trackPoint != null) {
newValue = me.reversePixelValue(trackPoint);
me.setThumbValue(thumb.getAttribute('data-thumbIndex'), newValue, false, true);
}
},
/**
* Programmatically sets the value of the Slider. Ensures that the value is constrained within the minValue and
* maxValue.
*
* Setting a single value:
* // Set the second slider value, don't animate
* mySlider.setThumbValue(1, 50, false);
*
* Setting multiple values at once
* // Set 3 thumb values, animate
* mySlider.setThumbValue([20, 40, 60], true);
*
* @param {Number/Number[]} index Index of the thumb to move. Alternatively, it can be an array of values to set
* for each thumb in the slider.
* @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue)
* @param {Boolean} [animate=true] Turn on or off animation
* @return {Ext.slider.Multi} this
*/
setThumbValue : function(index, value, animate, changeComplete) {
var me = this,
thumb, thumbValue, len, i, values;
if (Ext.isArray(index)) {
values = index;
animate = value;
for (i = 0, len = values.length; i < len; ++i) {
me.setThumbValue(i, values[i], animate);
}
return me;
}
thumb = me.getThumb(index);
thumbValue = me.reversePercentageValue(parseInt(thumb.dom.style[me.getThumbPositionStyle()], 10));
// ensures value is contstrained and snapped
value = me.normalizeValue(value);
if (value !== thumbValue && me.fireEvent('beforechange', me, value, thumbValue, thumb) !== false) {
if (me.element.dom) {
// TODO this only handles a single value; need a solution for exposing multiple values to aria.
// Perhaps this should go on each thumb element rather than the outer element.
me.element.set({
'aria-valuenow': value,
'aria-valuetext': value
});
me.moveThumb(thumb, me.calculateThumbPosition(value), Ext.isDefined(animate) ? animate !== false : me.animate);
me.fireEvent('change', me, value, thumb);
}
}
return me;
},
/**
* Returns the current value of the slider
* @param {Number} index The index of the thumb to return a value for
* @return {Number/Number[]} The current value of the slider at the given index, or an array of all thumb values if
* no index is given.
*/
getValue : function(index) {
var me = this;
return Ext.isNumber(index) ? me.reversePercentageValue(parseInt(me.thumbs[index].dom.style[me.getThumbPositionStyle()], 10)) : me.getValues();
},
/**
* Returns an array of values - one for the location of each thumb
* @return {Number[]} The set of thumb values
*/
getValues: function() {
var me = this,
values = [],
i = 0,
thumbs = me.thumbs,
len = thumbs.length;
for (; i < len; i++) {
values.push(me.reversePercentageValue(parseInt(me.thumbs[i].dom.style[me.getThumbPositionStyle()], 10)));
}
return values;
},
/**
* @private
* move the thumb
*/
moveThumb: function(thumb, v, animate) {
var me = this,
styleProp = me.getThumbPositionStyle(),
to,
from;
v += '%';
if (!animate) {
thumb.dom.style[styleProp] = v;
} else {
to = {};
to[styleProp] = v;
if (!Ext.supports.GetPositionPercentage) {
from = {};
from[styleProp] = thumb.dom.style[styleProp];
}
new Ext.fx.Anim({
target: thumb,
duration: 350,
from: from,
to: to
});
}
},
/**
* @private
* Returns a snapped, constrained value when given a desired value
* @param {Number} value Raw number value
* @return {Number} The raw value rounded to the correct d.p. and constrained within the set max and min values
*/
normalizeValue : function(v) {
var me = this,
snapFn = me.zeroBasedSnapping ? 'snap' : 'snapInRange';
v = Ext.Number[snapFn](v, me.increment, me.minValue, me.maxValue);
v = Ext.util.Format.round(v, me.decimalPrecision);
v = Ext.Number.constrain(v, me.minValue, me.maxValue);
return v;
},
/**
* @private
* Given an `[x, y]` position within the slider's track (Points outside the slider's track are coerced to either the minimum or maximum value),
* calculate how many pixels **from the slider origin** (left for horizontal Sliders and bottom for vertical Sliders) that point is.
*
* If the point is outside the range of the Slider's track, the return value is `undefined`
* @param {Number[]} xy The point to calculate the track point for
*/
getTrackpoint : function(xy) {
var me = this,
vertical = me.getVertical(),
sliderTrack = me.innerEl,
trackLength, result,
positionProperty;
if (vertical) {
positionProperty = 'top';
trackLength = sliderTrack.getHeight();
} else {
positionProperty = 'left';
trackLength = sliderTrack.getWidth();
}
xy = me.transformTrackPoints(sliderTrack.translatePoints(xy));
result = Ext.Number.constrain(xy[positionProperty], 0, trackLength);
return vertical ? trackLength - result : result;
},
transformTrackPoints: Ext.identityFn,
/**
* @private
* Given a value within this Slider's range, calculates a Thumb's percentage CSS position to map that value.
*/
calculateThumbPosition : function(v) {
var me = this,
pos = (v - me.getMinValue()) / me.getRange() * 100;
if (isNaN(pos)) {
pos = 0;
}
return pos;
},
/**
* @private
* Returns the ratio of pixels to mapped values. e.g. if the slider is 200px wide and maxValue - minValue is 100,
* the ratio is 2
* @return {Number} The ratio of pixels to mapped values
*/
getRatio : function() {
var me = this,
innerEl = me.innerEl,
trackLength = me.getVertical() ? innerEl.getHeight() : innerEl.getWidth(),
valueRange = me.getRange();
return valueRange === 0 ? trackLength : (trackLength / valueRange);
},
getRange: function() {
return this.getMaxValue() - this.getMinValue();
},
/**
* @private
* Given a pixel location along the slider, returns the mapped slider value for that pixel.
* E.g. if we have a slider 200px wide with minValue = 100 and maxValue = 500, reversePixelValue(50)
* returns 200
* @param {Number} pos The position along the slider to return a mapped value for
* @return {Number} The mapped value for the given position
*/
reversePixelValue : function(pos) {
return this.getMinValue() + (pos / this.getRatio());
},
/**
* @private
* Given a Thumb's percentage position along the slider, returns the mapped slider value for that pixel.
* E.g. if we have a slider 200px wide with minValue = 100 and maxValue = 500, reversePercentageValue(25)
* returns 200
* @param {Number} pos The percentage along the slider track to return a mapped value for
* @return {Number} The mapped value for the given position
*/
reversePercentageValue : function(pos) {
return this.getMinValue() + this.getRange() * (pos / 100);
},
captureMouse: function(onMouseMove, onMouseUp, args, appendArgs) {
var me = this,
onMouseupWrap,
listeners;
onMouseMove = onMouseMove && Ext.Function.bind(onMouseMove, me, args, appendArgs);
onMouseUp = onMouseUp && Ext.Function.bind(onMouseUp, me, args, appendArgs);
onMouseupWrap = function() {
Ext.getDoc().un(listeners);
if (onMouseUp) {
onMouseUp.apply(me, arguments);
}
};
listeners = {
mousemove: onMouseMove,
mouseup: onMouseupWrap
};
// Funnel mousemove events and the final mouseup event back into the gadget
Ext.getDoc().on(listeners);
}
}); | lucas-solutions/work-server | ext/src/slider/Widget.js | JavaScript | mit | 17,103 |
#!/usr/bin/env node
var util = require('util'),
http = require('http'),
fs = require('fs'),
url = require('url');
var DEFAULT_PORT = 8000;
function main(argv) {
new HttpServer({
'GET': createServlet(StaticServlet),
'HEAD': createServlet(StaticServlet)
}).start(Number(argv[2]) || DEFAULT_PORT);
}
function escapeHtml(value) {
return value.toString().
replace('<', '<').
replace('>', '>').
replace('"', '"');
}
function createServlet(Class) {
var servlet = new Class();
return servlet.handleRequest.bind(servlet);
}
/**
* An Http server implementation that uses a map of methods to decide
* action routing.
*
* @param {Object} Map of method => Handler function
*/
function HttpServer(handlers) {
this.handlers = handlers;
this.server = http.createServer(this.handleRequest_.bind(this));
}
HttpServer.prototype.start = function(port) {
this.port = port;
this.server.listen(port);
util.puts('Http Server running at http://128.178.5.173:' + port + '/');
};
HttpServer.prototype.parseUrl_ = function(urlString) {
var parsed = url.parse(urlString);
parsed.pathname = url.resolve('/', parsed.pathname);
return url.parse(url.format(parsed), true);
};
HttpServer.prototype.handleRequest_ = function(req, res) {
var logEntry = req.method + ' ' + req.url;
if (req.headers['user-agent']) {
logEntry += ' ' + req.headers['user-agent'];
}
util.puts(logEntry);
req.url = this.parseUrl_(req.url);
var handler = this.handlers[req.method];
if (!handler) {
res.writeHead(501);
res.end();
} else {
handler.call(this, req, res);
}
};
/**
* Handles static content.
*/
function StaticServlet() {}
StaticServlet.MimeMap = {
'txt': 'text/plain',
'html': 'text/html',
'css': 'text/css',
'xml': 'application/xml',
'json': 'application/json',
'js': 'application/javascript',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'png': 'image/png',
'svg': 'image/svg+xml'
};
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
StaticServlet.prototype.sendError_ = function(req, res, error) {
res.writeHead(500, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>Internal Server Error</title>\n');
res.write('<h1>Internal Server Error</h1>');
res.write('<pre>' + escapeHtml(util.inspect(error)) + '</pre>');
util.puts('500 Internal Server Error');
util.puts(util.inspect(error));
};
StaticServlet.prototype.sendMissing_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(404, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>404 Not Found</title>\n');
res.write('<h1>Not Found</h1>');
res.write(
'<p>The requested URL ' +
escapeHtml(path) +
' was not found on this server.</p>'
);
res.end();
util.puts('404 Not Found: ' + path);
};
StaticServlet.prototype.sendForbidden_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(403, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>403 Forbidden</title>\n');
res.write('<h1>Forbidden</h1>');
res.write(
'<p>You do not have permission to access ' +
escapeHtml(path) + ' on this server.</p>'
);
res.end();
util.puts('403 Forbidden: ' + path);
};
StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) {
res.writeHead(301, {
'Content-Type': 'text/html',
'Location': redirectUrl
});
res.write('<!doctype html>\n');
res.write('<title>301 Moved Permanently</title>\n');
res.write('<h1>Moved Permanently</h1>');
res.write(
'<p>The document has moved <a href="' +
redirectUrl +
'">here</a>.</p>'
);
res.end();
util.puts('301 Moved Permanently: ' + redirectUrl);
};
StaticServlet.prototype.sendFile_ = function(req, res, path) {
var self = this;
var file = fs.createReadStream(path);
res.writeHead(200, {
'Content-Type': StaticServlet.
MimeMap[path.split('.').pop()] || 'text/plain'
});
if (req.method === 'HEAD') {
res.end();
} else {
file.on('data', res.write.bind(res));
file.on('close', function() {
res.end();
});
file.on('error', function(error) {
self.sendError_(req, res, error);
});
}
};
StaticServlet.prototype.sendDirectory_ = function(req, res, path) {
var self = this;
if (path.match(/[^\/]$/)) {
req.url.pathname += '/';
var redirectUrl = url.format(url.parse(url.format(req.url)));
return self.sendRedirect_(req, res, redirectUrl);
}
fs.readdir(path, function(err, files) {
if (err)
return self.sendError_(req, res, error);
if (!files.length)
return self.writeDirectoryIndex_(req, res, path, []);
var remaining = files.length;
files.forEach(function(fileName, index) {
fs.stat(path + '/' + fileName, function(err, stat) {
if (err)
return self.sendError_(req, res, err);
if (stat.isDirectory()) {
files[index] = fileName + '/';
}
if (!(--remaining))
return self.writeDirectoryIndex_(req, res, path, files);
});
});
});
};
StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) {
path = path.substring(1);
res.writeHead(200, {
'Content-Type': 'text/html'
});
if (req.method === 'HEAD') {
res.end();
return;
}
res.write('<!doctype html>\n');
res.write('<title>' + escapeHtml(path) + '</title>\n');
res.write('<style>\n');
res.write(' ol { list-style-type: none; font-size: 1.2em; }\n');
res.write('</style>\n');
res.write('<h1>Directory: ' + escapeHtml(path) + '</h1>');
res.write('<ol>');
files.forEach(function(fileName) {
if (fileName.charAt(0) !== '.') {
res.write('<li><a href="' +
escapeHtml(fileName) + '">' +
escapeHtml(fileName) + '</a></li>');
}
});
res.write('</ol>');
res.end();
};
// Must be last,
main(process.argv);
| go-lab/smart-device | BeagleBoneBlack/servo-beaglebone-black/websocket-client/web-server.js | JavaScript | mit | 6,528 |
import {
domReady,
transitionFromClass,
transitionToClass,
readFileAsText
} from '../utils';
import Spinner from './spinner';
import { EventEmitter } from 'events';
export default class MainMenu extends EventEmitter {
constructor() {
super();
this.allowHide = false;
this._spinner = new Spinner();
domReady.then(() => {
this.container = document.querySelector('.main-menu');
this._loadFileInput = document.querySelector('.load-file-input');
this._pasteInput = document.querySelector('.paste-input');
this._loadDemoBtn = document.querySelector('.load-demo');
this._loadFileBtn = document.querySelector('.load-file');
this._pasteLabel = document.querySelector('.menu-input');
this._overlay = this.container.querySelector('.overlay');
this._menu = this.container.querySelector('.menu');
document.querySelector('.menu-btn')
.addEventListener('click', e => this._onMenuButtonClick(e));
this._overlay.addEventListener('click', e => this._onOverlayClick(e));
this._loadFileBtn.addEventListener('click', e => this._onLoadFileClick(e));
this._loadDemoBtn.addEventListener('click', e => this._onLoadDemoClick(e));
this._loadFileInput.addEventListener('change', e => this._onFileInputChange(e));
this._pasteInput.addEventListener('input', e => this._onTextInputChange(e));
});
}
show() {
this.container.classList.remove('hidden');
transitionFromClass(this._overlay, 'hidden');
transitionFromClass(this._menu, 'hidden');
}
hide() {
if (!this.allowHide) return;
this.stopSpinner();
this.container.classList.add('hidden');
transitionToClass(this._overlay, 'hidden');
transitionToClass(this._menu, 'hidden');
}
stopSpinner() {
this._spinner.hide();
}
showFilePicker() {
this._loadFileInput.click();
}
_onOverlayClick(event) {
event.preventDefault();
this.hide();
}
_onMenuButtonClick(event) {
event.preventDefault();
this.show();
}
_onTextInputChange(event) {
const val = this._pasteInput.value.trim();
if (val.includes('</svg>')) {
this._pasteInput.value = '';
this._pasteInput.blur();
this._pasteLabel.appendChild(this._spinner.container);
this._spinner.show();
this.emit('svgDataLoad', {
data: val,
filename: 'image.svg'
});
}
}
_onLoadFileClick(event) {
event.preventDefault();
event.target.blur();
this.showFilePicker();
}
async _onFileInputChange(event) {
const file = this._loadFileInput.files[0];
if (!file) return;
this._loadFileBtn.appendChild(this._spinner.container);
this._spinner.show();
this.emit('svgDataLoad', {
data: await readFileAsText(file),
filename: file.name
});
}
async _onLoadDemoClick(event) {
event.preventDefault();
event.target.blur();
this._loadDemoBtn.appendChild(this._spinner.container);
this._spinner.show();
try {
this.emit('svgDataLoad', {
data: await fetch('test-svgs/car-lite.svg').then(r => r.text()),
filename: 'car-lite.svg'
});
}
catch (err) {
// This extra scope is working around a babel-minify bug.
// It's fixed in Babel 7.
{
this.stopSpinner();
let error;
if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
error = Error("Demo not available offline");
}
else {
error = Error("Couldn't fetch demo SVG");
}
this.emit('error', { error });
}
}
}
}
| joshlevi/svgomg | src/js/page/ui/main-menu.js | JavaScript | mit | 3,618 |
// Karma configuration
// Generated on Fri May 29 2015 12:25:53 GMT-0500 (CDT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'src/index.coffee',
'test/test.coffee'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.coffee': ['coffee']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
| ryanbagwell/with-google-maps | karma.conf.js | JavaScript | mit | 1,641 |
var _ = require('underscore');
var nolp = require('./lib/nolp/nolp.js');
var ups = require('./lib/ups/ups.js');
/**
* available delivery services
*
* @var array of strings
* @private
*/
var availableServices = [
"dhl",
"ups"
];
/**
* retrieves the status of a package sent with packet delivery service.
*
* A callback will be called with an tracking object:
*
* {
* // contains the status of the tracking request
* // is true on success, false otherwise
* // use the issues array for human-readable error messages on failure.
* "status": <boolean>
*
* // contains tracking data to the packet
* "data": {
*
* // flag to sign wether packet has arrived ord not.
* "arrived": <boolean>,
*
* // a string containing the current delivery state (delivery service dependent)
* "status": <string>,
*
* // an array of objects explaining the progress in detail
* // there can be zero to Math.Infinity entries here.
* "steps": [
* {
* "date": <string> // Unix Timestamp
* "location": <string> // location of the step
* "status": <string> // message
* }
* ]
* },
*
* // an array containing strings with problems and errors on failure.
* "issues": [
* ]
* }
*
* @param object packet {"service": <string>, "id": <string>}
* @param function callback get called with a status object
* @returns boolean true on succesful call, false otherwise
* @access public
* @final
*/
this.track = function track (packet, callback) {
if (typeof packet == "undefined") {
console.log("No packet definition given.");
return false;
}
if (typeof packet.id == "undefined") {
console.log("No packet id given.");
return false;
}
if (typeof packet.service != "string") {
console.log("No packet service given.");
return false;
}
if (!this.isAvailableService(packet.service)) {
console.log("Delivery service " + packet.service + " is not available.");
return false;
}
if (typeof callback != "function") {
console.log("No callback function given.");
return false;
}
var deliveryService = getDeliveryService(packet.service);
deliveryService.get(packet.id, function (error, page) {
if (error !== null) {
callback({
"status": false,
"data": {
// no data sadly :(
},
"issues": [
"Could not retrieve status page."
]
});
return;
}
deliveryService.parse(page, function (error, track) {
if (error !== null) {
callback({
"status": false,
"data": {
// no data sadly :(
},
"issues": [
"Could not parse status page."
]
});
return;
}
deliveryService.normalize(track, function (error, model) {
if (error !== null) {
callback({
"status": false,
"data": {
// no data sadly :(
},
"issues": [
"Could not normalize parsed data."
]
});
return;
}
callback({
"status": true,
"data": model,
"issues": [
// no issues \o/
]
});
});
});
});
return true;
};
/**
* checks if service is available.
*
* @param string service name of service
* @return boolean
* @access public
* @final
*/
this.isAvailableService = function isAvailableService (service) {
if (typeof service == "undefined") {
return false;
}
if (_.indexOf(availableServices, service) === -1) {
return false;
}
return true;
}
/**
* gives the delivery service
*
* @param string serviceName name of delivery service
* @return controller|null іf serviceName could not map
* @access private
* @final
*/
function getDeliveryService (serviceName) {
switch (serviceName) {
case "dhl":
return nolp;
case "ups":
return ups;
}
return null;
}
| gofaster-git/gofasterapp | node_modules/dhl/index.js | JavaScript | mit | 4,699 |
import './Text1';
| lelandrichardson/react-primitives | example/stories/Text/index.js | JavaScript | mit | 18 |
var Shapes;
(function (Shapes) {
var Polygons;
(function (Polygons) {
var Triangle = (function () {
function Triangle() {
}
return Triangle;
})();
Polygons.Triangle = Triangle;
var Square = (function () {
function Square() {
}
return Square;
})();
Polygons.Square = Square;
})(Polygons = Shapes.Polygons || (Shapes.Polygons = {}));
})(Shapes || (Shapes = {}));
var polygons = Shapes.Polygons;
var sq = new polygons.Square();
| codelegant/TypeScript | modules/alias/basic-aliasing.js | JavaScript | mit | 557 |
var assert = require('assert'),
_ = require('underscore'),
request = require('request'),
config = require('../../config/'),
apiHost = 'http://localhost:' + config.port + '/api';
describe('api', function () {
describe('users', function () {
// assuming that there are
// 200+ testing records
describe('finds list', function () {
var url = apiHost + '/users';
it('with offset/limit', function (done) {
request(url, {
qs: {
offset: 50,
limit: 5
}
}, function (err, res, json) {
var users = JSON.parse(json);
assert.equal(users.length, 5);
done();
});
});
it('with page/limit', function (done) {
request(url, {
qs: {
page: 3,
limit: 7
}
}, function (err, res, json) {
var users = JSON.parse(json);
assert.equal(users.length, 7);
done();
});
});
});
describe('finds one', function () {
it('that exists', function (done) {
var url = apiHost + '/users/2';
request(url, function (err, res, json) {
var user = JSON.parse(json);
assert.equal(user.id, 2);
done();
});
});
it('that does not exist', function (done) {
var url = apiHost + '/users/-1';
request(url, function (err, res, json) {
var error = JSON.parse(json)
assert.ok(error.request);
assert.ok(error.errCode);
assert.ok(error.errMsg);
done();
});
});
});
});
}); | Jayin/SiyuanGroup | node/test/units/api.js | JavaScript | mit | 1,478 |
// Generated on 2015-04-11 using
// generator-webapp 0.5.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
jstest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
open: true,
livereload: 35729,
// Change this to '0.0.0.0' to access the server from outside
hostname: '0.0.0.0'
},
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
test: {
options: {
open: false,
port: 9001,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
dist: {
options: {
base: '<%= config.dist %>',
livereload: false
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
// Jasmine testing framework configuration options
jasmine: {
all: {
options: {
specs: 'test/spec/{,*/}*.js'
}
}
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the HTML file
wiredep: {
app: {
ignorePath: /^\/|\.\.\//,
src: ['<%= config.app %>/index.html'],
exclude: ['bower_components/bootstrap/dist/js/bootstrap.js']
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: [
'<%= config.dist %>',
'<%= config.dist %>/images',
'<%= config.dist %>/styles'
]
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},
// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*'
]
}, {
src: 'node_modules/apache-server-configs/dist/.htaccess',
dest: '<%= config.dist %>/.htaccess'
}, {
expand: true,
dot: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= config.dist %>'
}]
},
styles: {
expand: true,
dot: true,
cwd: '<%= config.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
}
});
grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
if (grunt.option('allow-remote')) {
grunt.config.set('connect.options.hostname', '0.0.0.0');
}
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});
grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'autoprefixer'
]);
}
grunt.task.run([
'connect:test',
'jasmine'
]);
});
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'cssmin',
'uglify',
'copy:dist',
'rev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
| spaceselfie/spaceselfie | Gruntfile.js | JavaScript | mit | 9,376 |
angular.module('gitphaser').controller('ProfileController', ProfileCtrl);
/**
* @ngdoc object
* @module gitphaser
* @name gitphaser.object:ProfileCtrl
* @description Exposes GitHub.me profile object or account object to the profile template.
* Governs the `/tab/profile` and `others/:username` routes.
*/
function ProfileCtrl ($scope, $stateParams, $state, $cordovaInAppBrowser, GitHub, account) {
var self = this;
self.browser = $cordovaInAppBrowser;
/**
* @ngdoc object
* @propertyOf gitphaser.object:ProfileCtrl
* @name gitphaser..object:ProfileCtrl.modalOpen
* @description `Boolean`: Triggers appearance changes in the template when
* a contact modal opens. See 'contact' directive.
*/
self.modalOpen = false;
// Arbitrary profile
if (account) {
self.user = account.info;
self.repos = account.repos;
self.events = account.events;
self.viewTitle = account.info.login;
self.state = $state;
self.nav = true;
self.canFollow = GitHub.canFollow(account.info.login);
// The user's own profile
} else {
self.user = GitHub.me;
self.repos = GitHub.repos;
self.events = GitHub.events;
self.viewTitle = GitHub.me.login;
self.canFollow = false;
self.nav = false;
}
// Info logic: There are four optional profile fields
// and two spaces to show them in. In order of importance:
// 1. Company, 2. Blog, 3. Email, 4. Location
self.company = self.user.company;
self.email = self.user.email;
self.blog = self.user.blog;
self.location = self.user.location;
// Case: both exist - no space
if (self.company && self.email) {
self.blog = false;
self.location = false;
// Case: One exists - one space, pick blog, or location
} else if ((!self.company && self.email) || (self.company && !self.email)) {
(self.blog) ? self.location = false : true;
}
/**
* @ngdoc method
* @methodOf gitphaser.object:ProfileCtrl
* @name gitphaser.object:ProfileCtrl.back
* @description Navigates back to `$stateParams.origin`. For nav back arrow visible in the `others`
* route.
*/
self.back = function () {
if ($stateParams.origin === 'nearby') $state.go('tab.nearby');
if ($stateParams.origin === 'notifications') $state.go('tab.notifications');
};
/**
* @ngdoc method
* @methodOf gitphaser.object:ProfileCtrl
* @name gitphaser.object:ProfileCtrl.follow
* @description Wraps `GitHub.follow` and hides the follow button when clicked.
*/
self.follow = function () {
self.canFollow = false;
GitHub.follow(self.user);
};
}
| git-phaser/git-phaser | www/js/Controllers/profile.js | JavaScript | mit | 2,628 |
if (typeof exports === 'object') {
var assert = require('assert');
var alasql = require('..');
}
/*
Test for issue #379
*/
var test = 428;
describe('Test ' + test + ' UUID()', function () {
before(function () {
alasql('CREATE DATABASE test' + test + ';USE test' + test);
});
after(function () {
alasql('DROP DATABASE test' + test);
});
it('1. Simple test GUID', function (done) {
var res = alasql('=UUID()');
assert(
!!res.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)
);
done();
});
it('2. DEFAULT GUID', function (done) {
alasql('CREATE TABLE one (a INT, b STRING DEFAULT UUID())');
alasql('INSERT INTO one(a) VALUES (1)');
var res = alasql('SELECT * FROM one');
assert(
!!res[0].b.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)
);
done();
});
});
| agershun/alasql | test/test428.js | JavaScript | mit | 873 |
/**
AnalyzeController.js
*/
application.controller('AnalyzeController', ['$scope', '$stateParams', 'PathService', function ($scope, $stateParams, PathService) {
$scope.path = {};
PathService.path({
Type: "SUBMISSION",
EntityId: $stateParams.submissionId
})
.success(function (data, status, headers, config) {
$scope.path = data;
});
}]); | bond95/IBP2013 | js/controllers/AnalyzeController.js | JavaScript | mit | 387 |
/**
* Extend Object works like Object.assign(...) but recurses into the nested properties
*
* @param {object} base - an object to extend
* @param {...object} args - a series of objects to extend
* @returns {object} extended object
*/
function extend(base, ...args) {
args.forEach(current => {
if (!Array.isArray(current) && base instanceof Object && current instanceof Object && base !== current) {
for (const x in current) {
base[x] = extend(base[x], current[x]);
}
}
else {
base = current;
}
});
return base;
}
module.exports = extend;
| 5app/dare | src/utils/extend.js | JavaScript | mit | 579 |
/*
*
* HomeItemPage constants
*
*/
export const DEFAULT_ACTION = 'app/HomeItemPage/DEFAULT_ACTION';
| yoohan-dex/myBlog | app/containers/HomeItemPage/constants.js | JavaScript | mit | 105 |
'use strict';
var browserify = require('browserify');
var go = module.exports = function () {
return browserify()
.require(require.resolve('./main'), { entry: true })
.bundle({ debug: true });
};
// Test
if (!module.parent) {
go().pipe(process.stdout);
}
| thlorenz/level-json-edit | example/build.js | JavaScript | mit | 270 |
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/node
const apiKeySid = 'SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const apiKeySecret = 'your_api_key_secret';
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const Twilio = require('twilio');
const client = new Twilio(apiKeySid, apiKeySecret, { accountSid: accountSid });
client.video.rooms('RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch().then(room => {
console.log(room.uniqueName);
});
| teoreteetik/api-snippets | video/rest/rooms/retrieve-room-by-sid/retrieve-room-by-sid.3.x.js | JavaScript | mit | 578 |
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
create() {
this.get('model').save().then((user) => {
this.transitionToRoute('admin.users.show', user);
})
}
}
});
| NotGrm/holidayz-web | app/controllers/admin/users/new.js | JavaScript | mit | 226 |
var Avenger = require('mongoose').model('Avenger');
exports.getAvengers = function (req, res) {
Avenger.find({}).exec(function (err, collection) {
res.send(collection);
});
};
exports.getAvengerById = function (req, res) {
Avenger.findOne({_id:req.params.id}).exec(function (err, avenger) {
res.send(avenger);
});
}; | anthonymjones/MultiVision | server/controllers/avengers.js | JavaScript | mit | 350 |
// # Templates
//
// Figure out which template should be used to render a request
// based on the templates which are allowed, and what is available in the theme
// TODO: consider where this should live as it deals with channels, singles, and errors
var _ = require('lodash'),
path = require('path'),
config = require('../../config'),
themes = require('../../themes'),
_private = {};
/**
* ## Get Error Template Hierarchy
*
* Fetch the ordered list of templates that can be used to render this error statusCode.
*
* The default is the
*
* @param {integer} statusCode
* @returns {String[]}
*/
_private.getErrorTemplateHierarchy = function getErrorTemplateHierarchy(statusCode) {
var errorCode = _.toString(statusCode),
templateList = ['error'];
// Add error class template: E.g. error-4xx.hbs or error-5xx.hbs
templateList.unshift('error-' + errorCode[0] + 'xx');
// Add statusCode specific template: E.g. error-404.hbs
templateList.unshift('error-' + errorCode);
return templateList;
};
/**
* ## Get Channel Template Hierarchy
*
* Fetch the ordered list of templates that can be used to render this request.
* 'index' is the default / fallback
* For channels with slugs: [:channelName-:slug, :channelName, index]
* For channels without slugs: [:channelName, index]
* Channels can also have a front page template which is used if this is the first page of the channel, e.g. 'home.hbs'
*
* @param {Object} channelOpts
* @returns {String[]}
*/
_private.getChannelTemplateHierarchy = function getChannelTemplateHierarchy(channelOpts) {
var templateList = ['index'];
if (channelOpts.name && channelOpts.name !== 'index') {
templateList.unshift(channelOpts.name);
if (channelOpts.slugTemplate && channelOpts.slugParam) {
templateList.unshift(channelOpts.name + '-' + channelOpts.slugParam);
}
}
if (channelOpts.frontPageTemplate && channelOpts.postOptions.page === 1) {
templateList.unshift(channelOpts.frontPageTemplate);
}
return templateList;
};
/**
* ## Get Entry Template Hierarchy
*
* Fetch the ordered list of templates that can be used to render this request.
* 'post' is the default / fallback
* For posts: [post-:slug, custom-*, post]
* For pages: [page-:slug, custom-*, page, post]
*
* @param {Object} postObject
* @returns {String[]}
*/
_private.getEntryTemplateHierarchy = function getEntryTemplateHierarchy(postObject) {
var templateList = ['post'],
slugTemplate = 'post-' + postObject.slug;
if (postObject.page) {
templateList.unshift('page');
slugTemplate = 'page-' + postObject.slug;
}
if (postObject.custom_template) {
templateList.unshift(postObject.custom_template);
}
templateList.unshift(slugTemplate);
return templateList;
};
/**
* ## Pick Template
*
* Taking the ordered list of allowed templates for this request
* Cycle through and find the first one which has a match in the theme
*
* @param {Array|String} templateList
* @param {String} fallback - a fallback template
*/
_private.pickTemplate = function pickTemplate(templateList, fallback) {
var template;
if (!_.isArray(templateList)) {
templateList = [templateList];
}
if (!themes.getActive()) {
template = fallback;
} else {
template = _.find(templateList, function (template) {
return themes.getActive().hasTemplate(template);
});
}
if (!template) {
template = fallback;
}
return template;
};
_private.getTemplateForEntry = function getTemplateForEntry(postObject) {
var templateList = _private.getEntryTemplateHierarchy(postObject),
fallback = templateList[templateList.length - 1];
return _private.pickTemplate(templateList, fallback);
};
_private.getTemplateForChannel = function getTemplateForChannel(channelOpts) {
var templateList = _private.getChannelTemplateHierarchy(channelOpts),
fallback = templateList[templateList.length - 1];
return _private.pickTemplate(templateList, fallback);
};
_private.getTemplateForError = function getTemplateForError(statusCode) {
var templateList = _private.getErrorTemplateHierarchy(statusCode),
fallback = path.resolve(config.get('paths').defaultViews, 'error.hbs');
return _private.pickTemplate(templateList, fallback);
};
module.exports.setTemplate = function setTemplate(req, res, data) {
var routeConfig = res._route || {};
if (res._template && !req.err) {
return;
}
if (req.err) {
res._template = _private.getTemplateForError(res.statusCode);
return;
}
switch (routeConfig.type) {
case 'custom':
res._template = _private.pickTemplate(routeConfig.templateName, routeConfig.defaultTemplate);
break;
case 'channel':
res._template = _private.getTemplateForChannel(res.locals.channel);
break;
case 'entry':
res._template = _private.getTemplateForEntry(data.post);
break;
default:
res._template = 'index';
}
};
| kpsuperplane/personal-website | versions/1.19.0/core/server/controllers/frontend/templates.js | JavaScript | mit | 5,174 |
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; })();
/*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
WebInspector.TimelineDataGrid = function (treeOutline, columns, delegate, editCallback, deleteCallback) {
WebInspector.DataGrid.call(this, columns, editCallback, deleteCallback);
this._treeOutlineDataGridSynchronizer = new WebInspector.TreeOutlineDataGridSynchronizer(treeOutline, this, delegate);
this.element.classList.add(WebInspector.TimelineDataGrid.StyleClassName);
this._filterableColumns = [];
// Check if any of the cells can be filtered.
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.columns[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _step$value = _slicedToArray(_step.value, 2);
var identifier = _step$value[0];
var column = _step$value[1];
var scopeBar = column.scopeBar;
if (!scopeBar) continue;
this._filterableColumns.push(identifier);
scopeBar.columnIdentifier = identifier;
scopeBar.addEventListener(WebInspector.ScopeBar.Event.SelectionChanged, this._scopeBarSelectedItemsDidChange, this);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"]) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (this._filterableColumns.length > 1) {
console.error("Creating a TimelineDataGrid with more than one filterable column is not yet supported.");
return;
}
if (this._filterableColumns.length) {
var items = [new WebInspector.FlexibleSpaceNavigationItem(), this.columns.get(this._filterableColumns[0]).scopeBar, new WebInspector.FlexibleSpaceNavigationItem()];
this._navigationBar = new WebInspector.NavigationBar(null, items);
var container = this.element.appendChild(document.createElement("div"));
container.className = "navigation-bar-container";
container.appendChild(this._navigationBar.element);
this._updateScopeBarForcedVisibility();
}
this.addEventListener(WebInspector.DataGrid.Event.SelectedNodeChanged, this._dataGridSelectedNodeChanged, this);
this.addEventListener(WebInspector.DataGrid.Event.SortChanged, this._sort, this);
window.addEventListener("resize", this._windowResized.bind(this));
};
WebInspector.TimelineDataGrid.StyleClassName = "timeline";
WebInspector.TimelineDataGrid.HasNonDefaultFilterStyleClassName = "has-non-default-filter";
WebInspector.TimelineDataGrid.DelayedPopoverShowTimeout = 250;
WebInspector.TimelineDataGrid.DelayedPopoverHideContentClearTimeout = 500;
WebInspector.TimelineDataGrid.Event = {
FiltersDidChange: "timelinedatagrid-filters-did-change"
};
WebInspector.TimelineDataGrid.createColumnScopeBar = function (prefix, dictionary) {
prefix = prefix + "-timeline-data-grid-";
var keys = Object.keys(dictionary).filter(function (key) {
return typeof dictionary[key] === "string" || dictionary[key] instanceof String;
});
var scopeBarItems = keys.map(function (key) {
var value = dictionary[key];
var id = prefix + value;
var label = dictionary.displayName(value, true);
var item = new WebInspector.ScopeBarItem(id, label);
item.value = value;
return item;
});
scopeBarItems.unshift(new WebInspector.ScopeBarItem(prefix + "type-all", WebInspector.UIString("All"), true));
return new WebInspector.ScopeBar(prefix + "scope-bar", scopeBarItems, scopeBarItems[0]);
};
WebInspector.TimelineDataGrid.prototype = {
constructor: WebInspector.TimelineDataGrid,
__proto__: WebInspector.DataGrid.prototype,
// Public
reset: function reset() {
// May be overridden by subclasses. If so, they should call the superclass.
this._hidePopover();
},
shown: function shown() {
// May be overridden by subclasses. If so, they should call the superclass.
this._treeOutlineDataGridSynchronizer.synchronize();
},
hidden: function hidden() {
// May be overridden by subclasses. If so, they should call the superclass.
this._hidePopover();
},
treeElementForDataGridNode: function treeElementForDataGridNode(dataGridNode) {
return this._treeOutlineDataGridSynchronizer.treeElementForDataGridNode(dataGridNode);
},
dataGridNodeForTreeElement: function dataGridNodeForTreeElement(treeElement) {
return this._treeOutlineDataGridSynchronizer.dataGridNodeForTreeElement(treeElement);
},
callFramePopoverAnchorElement: function callFramePopoverAnchorElement() {
// Implemented by subclasses.
return null;
},
updateLayout: function updateLayout() {
WebInspector.DataGrid.prototype.updateLayout.call(this);
if (this._navigationBar) this._navigationBar.updateLayout();
},
treeElementMatchesActiveScopeFilters: function treeElementMatchesActiveScopeFilters(treeElement) {
var dataGridNode = this._treeOutlineDataGridSynchronizer.dataGridNodeForTreeElement(treeElement);
console.assert(dataGridNode);
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this._filterableColumns[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var identifier = _step2.value;
var scopeBar = this.columns.get(identifier).scopeBar;
if (!scopeBar || scopeBar.defaultItem.selected) continue;
var value = dataGridNode.data[identifier];
var matchesFilter = scopeBar.selectedItems.some(function (scopeBarItem) {
return scopeBarItem.value === value;
});
if (!matchesFilter) return false;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2["return"]) {
_iterator2["return"]();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return true;
},
addRowInSortOrder: function addRowInSortOrder(treeElement, dataGridNode, parentElement) {
this._treeOutlineDataGridSynchronizer.associate(treeElement, dataGridNode);
parentElement = parentElement || this._treeOutlineDataGridSynchronizer.treeOutline;
parentNode = parentElement.root ? this : this._treeOutlineDataGridSynchronizer.dataGridNodeForTreeElement(parentElement);
console.assert(parentNode);
if (this.sortColumnIdentifier) {
var insertionIndex = insertionIndexForObjectInListSortedByFunction(dataGridNode, parentNode.children, this._sortComparator.bind(this));
// Insert into the parent, which will cause the synchronizer to insert into the data grid.
parentElement.insertChild(treeElement, insertionIndex);
} else {
// Append to the parent, which will cause the synchronizer to append to the data grid.
parentElement.appendChild(treeElement);
}
},
shouldIgnoreSelectionEvent: function shouldIgnoreSelectionEvent() {
return this._ignoreSelectionEvent || false;
},
// Protected
dataGridNodeNeedsRefresh: function dataGridNodeNeedsRefresh(dataGridNode) {
if (!this._dirtyDataGridNodes) this._dirtyDataGridNodes = new Set();
this._dirtyDataGridNodes.add(dataGridNode);
if (this._scheduledDataGridNodeRefreshIdentifier) return;
this._scheduledDataGridNodeRefreshIdentifier = requestAnimationFrame(this._refreshDirtyDataGridNodes.bind(this));
},
// Private
_refreshDirtyDataGridNodes: function _refreshDirtyDataGridNodes() {
if (this._scheduledDataGridNodeRefreshIdentifier) {
cancelAnimationFrame(this._scheduledDataGridNodeRefreshIdentifier);
delete this._scheduledDataGridNodeRefreshIdentifier;
}
if (!this._dirtyDataGridNodes) return;
var selectedNode = this.selectedNode;
var sortComparator = this._sortComparator.bind(this);
var treeOutline = this._treeOutlineDataGridSynchronizer.treeOutline;
this._treeOutlineDataGridSynchronizer.enabled = false;
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = this._dirtyDataGridNodes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var dataGridNode = _step3.value;
dataGridNode.refresh();
if (!this.sortColumnIdentifier) continue;
if (dataGridNode === selectedNode) this._ignoreSelectionEvent = true;
var treeElement = this._treeOutlineDataGridSynchronizer.treeElementForDataGridNode(dataGridNode);
console.assert(treeElement);
treeOutline.removeChild(treeElement);
this.removeChild(dataGridNode);
var insertionIndex = insertionIndexForObjectInListSortedByFunction(dataGridNode, this.children, sortComparator);
treeOutline.insertChild(treeElement, insertionIndex);
this.insertChild(dataGridNode, insertionIndex);
// Adding the tree element back to the tree outline subjects it to filters.
// Make sure we keep the hidden state in-sync while the synchronizer is disabled.
dataGridNode.element.classList.toggle("hidden", treeElement.hidden);
if (dataGridNode === selectedNode) {
selectedNode.revealAndSelect();
delete this._ignoreSelectionEvent;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3["return"]) {
_iterator3["return"]();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
this._treeOutlineDataGridSynchronizer.enabled = true;
delete this._dirtyDataGridNodes;
},
_sort: function _sort() {
var sortColumnIdentifier = this.sortColumnIdentifier;
if (!sortColumnIdentifier) return;
var selectedNode = this.selectedNode;
this._ignoreSelectionEvent = true;
this._treeOutlineDataGridSynchronizer.enabled = false;
var treeOutline = this._treeOutlineDataGridSynchronizer.treeOutline;
if (treeOutline.selectedTreeElement) treeOutline.selectedTreeElement.deselect(true);
// Collect parent nodes that need their children sorted. So this in two phases since
// traverseNextNode would get confused if we sort the tree while traversing it.
var parentDataGridNodes = [this];
var currentDataGridNode = this.children[0];
while (currentDataGridNode) {
if (currentDataGridNode.children.length) parentDataGridNodes.push(currentDataGridNode);
currentDataGridNode = currentDataGridNode.traverseNextNode(false, null, true);
}
// Sort the children of collected parent nodes.
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = parentDataGridNodes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var parentDataGridNode = _step4.value;
var parentTreeElement = parentDataGridNode === this ? treeOutline : this._treeOutlineDataGridSynchronizer.treeElementForDataGridNode(parentDataGridNode);
console.assert(parentTreeElement);
var childDataGridNodes = parentDataGridNode.children.slice();
parentDataGridNode.removeChildren();
parentTreeElement.removeChildren();
childDataGridNodes.sort(this._sortComparator.bind(this));
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = childDataGridNodes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var dataGridNode = _step5.value;
var treeElement = this._treeOutlineDataGridSynchronizer.treeElementForDataGridNode(dataGridNode);
console.assert(treeElement);
parentTreeElement.appendChild(treeElement);
parentDataGridNode.appendChild(dataGridNode);
// Adding the tree element back to the tree outline subjects it to filters.
// Make sure we keep the hidden state in-sync while the synchronizer is disabled.
dataGridNode.element.classList.toggle("hidden", treeElement.hidden);
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5["return"]) {
_iterator5["return"]();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4["return"]) {
_iterator4["return"]();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
this._treeOutlineDataGridSynchronizer.enabled = true;
if (selectedNode) selectedNode.revealAndSelect();
delete this._ignoreSelectionEvent;
},
_sortComparator: function _sortComparator(node1, node2) {
var sortColumnIdentifier = this.sortColumnIdentifier;
if (!sortColumnIdentifier) return 0;
var sortDirection = this.sortOrder === WebInspector.DataGrid.SortOrder.Ascending ? 1 : -1;
var value1 = node1.data[sortColumnIdentifier];
var value2 = node2.data[sortColumnIdentifier];
if (typeof value1 === "number" && typeof value2 === "number") {
if (isNaN(value1) && isNaN(value2)) return 0;
if (isNaN(value1)) return -sortDirection;
if (isNaN(value2)) return sortDirection;
return (value1 - value2) * sortDirection;
}
if (typeof value1 === "string" && typeof value2 === "string") return value1.localeCompare(value2) * sortDirection;
if (value1 instanceof WebInspector.CallFrame || value2 instanceof WebInspector.CallFrame) {
// Sort by function name if available, then fall back to the source code object.
value1 = value1 && value1.functionName ? value1.functionName : value1 && value1.sourceCodeLocation ? value1.sourceCodeLocation.sourceCode : "";
value2 = value2 && value2.functionName ? value2.functionName : value2 && value2.sourceCodeLocation ? value2.sourceCodeLocation.sourceCode : "";
}
if (value1 instanceof WebInspector.SourceCode || value2 instanceof WebInspector.SourceCode) {
value1 = value1 ? value1.displayName || "" : "";
value2 = value2 ? value2.displayName || "" : "";
}
// For everything else (mostly booleans).
return (value1 < value2 ? -1 : value1 > value2 ? 1 : 0) * sortDirection;
},
_updateScopeBarForcedVisibility: function _updateScopeBarForcedVisibility() {
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = this._filterableColumns[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var identifier = _step6.value;
var scopeBar = this.columns.get(identifier).scopeBar;
if (scopeBar) {
this.element.classList.toggle(WebInspector.TimelineDataGrid.HasNonDefaultFilterStyleClassName, scopeBar.hasNonDefaultItemSelected());
break;
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6["return"]) {
_iterator6["return"]();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
},
_scopeBarSelectedItemsDidChange: function _scopeBarSelectedItemsDidChange(event) {
this._updateScopeBarForcedVisibility();
var columnIdentifier = event.target.columnIdentifier;
this.dispatchEventToListeners(WebInspector.TimelineDataGrid.Event.FiltersDidChange, { columnIdentifier: columnIdentifier });
},
_dataGridSelectedNodeChanged: function _dataGridSelectedNodeChanged(event) {
if (!this.selectedNode) {
this._hidePopover();
return;
}
var record = this.selectedNode.record;
if (!record || !record.callFrames || !record.callFrames.length) {
this._hidePopover();
return;
}
this._showPopoverForSelectedNodeSoon();
},
_windowResized: function _windowResized(event) {
if (this._popover && this._popover.visible) this._updatePopoverForSelectedNode(false);
},
_showPopoverForSelectedNodeSoon: function _showPopoverForSelectedNodeSoon() {
if (this._showPopoverTimeout) return;
function delayedWork() {
if (!this._popover) this._popover = new WebInspector.Popover();
this._updatePopoverForSelectedNode(true);
}
this._showPopoverTimeout = setTimeout(delayedWork.bind(this), WebInspector.TimelineDataGrid.DelayedPopoverShowTimeout);
},
_hidePopover: function _hidePopover() {
if (this._showPopoverTimeout) {
clearTimeout(this._showPopoverTimeout);
delete this._showPopoverTimeout;
}
if (this._popover) this._popover.dismiss();
function delayedWork() {
if (this._popoverCallStackTreeOutline) this._popoverCallStackTreeOutline.removeChildren();
}
if (this._hidePopoverContentClearTimeout) clearTimeout(this._hidePopoverContentClearTimeout);
this._hidePopoverContentClearTimeout = setTimeout(delayedWork.bind(this), WebInspector.TimelineDataGrid.DelayedPopoverHideContentClearTimeout);
},
_updatePopoverForSelectedNode: function _updatePopoverForSelectedNode(updateContent) {
if (!this._popover || !this.selectedNode) return;
var targetPopoverElement = this.callFramePopoverAnchorElement();
console.assert(targetPopoverElement, "TimelineDataGrid subclass should always return a valid element from callFramePopoverAnchorElement.");
if (!targetPopoverElement) return;
var targetFrame = WebInspector.Rect.rectFromClientRect(targetPopoverElement.getBoundingClientRect());
// The element might be hidden if it does not have a width and height.
if (!targetFrame.size.width && !targetFrame.size.height) return;
if (this._hidePopoverContentClearTimeout) {
clearTimeout(this._hidePopoverContentClearTimeout);
delete this._hidePopoverContentClearTimeout;
}
if (updateContent) this._popover.content = this._createPopoverContent();
this._popover.present(targetFrame.pad(2), [WebInspector.RectEdge.MAX_Y, WebInspector.RectEdge.MIN_Y, WebInspector.RectEdge.MAX_X]);
},
_createPopoverContent: function _createPopoverContent() {
if (!this._popoverCallStackTreeOutline) {
var contentElement = document.createElement("ol");
contentElement.classList.add("timeline-data-grid-tree-outline");
this._popoverCallStackTreeOutline = new TreeOutline(contentElement);
this._popoverCallStackTreeOutline.onselect = this._popoverCallStackTreeElementSelected.bind(this);
} else this._popoverCallStackTreeOutline.removeChildren();
var callFrames = this.selectedNode.record.callFrames;
for (var i = 0; i < callFrames.length; ++i) {
var callFrameTreeElement = new WebInspector.CallFrameTreeElement(callFrames[i]);
this._popoverCallStackTreeOutline.appendChild(callFrameTreeElement);
}
var content = document.createElement("div");
content.className = "timeline-data-grid-popover";
content.appendChild(this._popoverCallStackTreeOutline.element);
return content;
},
_popoverCallStackTreeElementSelected: function _popoverCallStackTreeElementSelected(treeElement, selectedByUser) {
this._popover.dismiss();
console.assert(treeElement instanceof WebInspector.CallFrameTreeElement, "TreeElements in TimelineDataGrid popover should always be CallFrameTreeElements");
var callFrame = treeElement.callFrame;
if (!callFrame.sourceCodeLocation) return;
WebInspector.resourceSidebarPanel.showSourceCodeLocation(callFrame.sourceCodeLocation);
}
};
| artygus/webkit-webinspector | lib/WebInspectorUI/v8/Views/TimelineDataGrid.js | JavaScript | mit | 24,614 |
var mongodb = require("mongodb"),
config = require("./config"),
connectArr = [];
module.exports = function(server){
connectArr.push("mongodb://");
if(config.dbUser){
connectArr.push(config.dbUser);
connectArr.push("@");
}
if(config.dbPwd){
connectArr.push(config.dbPwd);
}
connectArr.push(config.db);
mongodb.MongoClient.connect(connectArr.join(""), function(err, db){
if(err) {
console.log("error connecting to mongo");
} else {
console.log("connected to %s successfully", db.databaseName);
require("./realtime")(server, db);
}
});
}; | codyrushing/btc-streaming-data | db-connect.js | JavaScript | mit | 569 |
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from '../actions/workspace';
import { setActiveComponent } from '../actions/FileSystemActions';
import Workspace from '../components/Workspace';
function mapStateToProps(state) {
return {
workspace: state.workspace
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ ...actionCreators, setActiveComponent }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Workspace);
| FermORG/FermionJS | app/containers/Workspace.js | JavaScript | mit | 539 |
export const ATTR_ID = 'data-referid'
export let info = {
component: {
amount: 0,
mounts: 0,
unmounts: 0
}
}
export let getId = () => Math.random().toString(36).substr(2)
export let pipe = (fn1, fn2) => function(...args) {
fn1.apply(this, args)
return fn2.apply(this, args)
}
export let createCallbackStore = name => {
let store = []
return {
name,
clear() {
while (store.length) {
store.shift()()
}
},
push(item) {
store.push(item)
},
store
}
}
export let wrapNative = (obj, method, fn) => {
let nativeMethod = obj[method]
let wrapper = function(...args) {
fn.apply(this, args)
return nativeMethod.apply(this, args)
}
obj[method] = wrapper
return () => obj[method] = nativeMethod
}
if (!Object.assign) {
Object.assign = (target, ...args) => {
args.forEach(source => {
for (let key in source) {
if (!source.hasOwnProperty(key)) {
continue
}
target[key] = source[key]
}
})
return target
}
} | Lucifier129/refer-dom | src/util.js | JavaScript | mit | 975 |
export default function _isEdge() {
const ua = navigator.userAgent.toLowerCase();
return Boolean(ua.match(/edge/i));
}
| gnk-sato-hotto/nkdash | source/_isEdge.js | JavaScript | mit | 123 |
import React from 'react';
import PropTypes from 'prop-types';
import dropdownDriverFactory from '../Dropdown.driver';
import Dropdown from '../Dropdown';
import { sleep } from 'wix-ui-test-utils/react-helpers';
import {
createRendererWithDriver,
createRendererWithUniDriver,
cleanup,
} from '../../../test/utils/unit';
import { dropdownUniDriverFactory } from '../Dropdown.uni.driver';
describe('Dropdown', () => {
describe('[sync]', () => {
runTests(createRendererWithDriver(dropdownDriverFactory));
});
describe('[async]', () => {
runTests(createRendererWithUniDriver(dropdownUniDriverFactory));
});
function runTests(render) {
afterEach(() => cleanup());
const createDriver = jsx => render(jsx).driver;
const getOptions = () => [
{ id: 0, value: 'Option 1' },
{ id: 1, value: 'Option 2' },
{ id: 2, value: 'Option 3', disabled: true },
{ id: 3, value: 'Option 4' },
{ id: 'divider1', value: '-' },
{
id: 'element1',
value: <span style={{ color: 'brown' }}>Option 4</span>,
},
];
describe('Uncontrolled SelectedId', () => {
it('should select item with selectedId on init state', async () => {
const { inputDriver, dropdownLayoutDriver } = createDriver(
<Dropdown options={getOptions()} initialSelectedId={0} />,
);
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(true);
expect(await inputDriver.getValue()).toBe('Option 1');
});
it('should select an item when clicked', async () => {
const { driver, dropdownLayoutDriver } = createDriver(
<Dropdown options={getOptions()} />,
);
await driver.focus();
await dropdownLayoutDriver.clickAtOption(0);
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(true);
});
it('should enter the selected option text when selected', async () => {
const { driver, inputDriver, dropdownLayoutDriver } = createDriver(
<Dropdown options={getOptions()} />,
);
await driver.focus();
await dropdownLayoutDriver.clickAtOption(0);
expect(await inputDriver.getValue()).toBe('Option 1');
});
it('should close when clicking on input (header)', async () => {
const { dropdownLayoutDriver, inputDriver } = createDriver(
<Dropdown options={getOptions()} />,
);
await inputDriver.click();
expect(await dropdownLayoutDriver.isShown()).toBe(true);
return sleep(200).then(async () => {
await inputDriver.click();
expect(await dropdownLayoutDriver.isShown()).toBe(false);
});
});
it('should not be editable ', async () => {
const { driver } = createDriver(<Dropdown options={getOptions()} />);
expect(await driver.isEditable()).toBe(false);
});
it('should have no selection when initialSelectedId is null', async () => {
const { driver: _driver } = render(
<Dropdown
options={[{ id: 0, value: 'Option 1' }]}
initialSelectedId={null}
/>,
);
const { dropdownLayoutDriver, inputDriver } = _driver;
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(false);
expect(await inputDriver.getValue()).toBe('');
});
describe('initiallySelected', () => {
it('should keep selectedId and value when initialSelectedId changed', async () => {
const { driver: _driver, rerender } = render(
<Dropdown options={getOptions()} initialSelectedId={0} />,
);
const { dropdownLayoutDriver } = _driver;
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(true);
rerender(<Dropdown options={getOptions()} initialSelectedId={1} />);
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(true);
});
});
it(`should update selectedId when options change and id does not exist anymore`, async () => {
const { driver: _driver, rerender } = render(
<Dropdown
options={[
{ id: 0, value: 'Option 1' },
{ id: 1, value: 'Option 2' },
]}
initialSelectedId={0}
/>,
);
const { inputDriver, dropdownLayoutDriver } = _driver;
const option = await dropdownLayoutDriver.optionById(0);
expect(await option.isSelected()).toBe(true);
expect(await inputDriver.getValue()).toBe('Option 1');
rerender(<Dropdown options={[{ id: 1, value: 'Option 2' }]} />);
const options = await dropdownLayoutDriver.options();
const isAnyOptionSelected = (
await Promise.all(options.map(option => option.isSelected()))
).some(val => val);
expect(isAnyOptionSelected).toBe(false);
expect(await inputDriver.getValue()).toBe('');
});
it('should select item with selectedId on async init', async () => {
const { driver: _driver, rerender } = render(
<Dropdown options={[]} selectedId={0} />,
);
const { inputDriver, dropdownLayoutDriver } = _driver;
const options = await dropdownLayoutDriver.options();
const isAnyOptionSelected = (
await Promise.all(options.map(option => option.isSelected()))
).some(val => val);
expect(isAnyOptionSelected).toBe(false);
expect(await inputDriver.getValue()).toBe('');
rerender(
<Dropdown
options={[
{ id: 0, value: 'Option 1' },
{ id: 1, value: 'Option 2' },
]}
selectedId={0}
/>,
);
const option = await dropdownLayoutDriver.optionById(0);
expect(await option.isSelected()).toBe(true);
expect(await inputDriver.getValue()).toBe('Option 1');
});
describe('PropTypes Validation', () => {
let consoleErrorSpy;
beforeEach(() => {
consoleErrorSpy = jest
.spyOn(global.console, 'error')
.mockImplementation(jest.fn());
});
afterEach(() => {
consoleErrorSpy.mockRestore();
PropTypes.checkPropTypes.resetWarningCache();
});
it('should log error when selectedId and initialSelectedId are used together', async () => {
render(
<Dropdown
options={getOptions()}
selectedId={0}
initialSelectedId={0}
/>,
);
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
expect(consoleErrorSpy).toBeCalledWith(
expect.stringContaining(
`'selectedId' and 'initialSelectedId' cannot both be used at the same time.`,
),
);
});
});
});
describe('Controlled SelectedId', () => {
it('should keep current selection and value when option clicked', async () => {
const { driver, dropdownLayoutDriver, inputDriver } = createDriver(
<Dropdown options={getOptions()} selectedId={0} />,
);
await driver.focus();
await dropdownLayoutDriver.clickAtOption(1);
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(true);
expect(await inputDriver.getValue()).toBe('Option 1');
});
it('should have no selection if selectedId does not exist', async () => {
const { dropdownLayoutDriver } = createDriver(
<Dropdown options={[{ id: 0, value: 'Option 1' }]} selectedId={99} />,
);
const option = await dropdownLayoutDriver.optionById(0);
expect(await option.isSelected()).toBe(false);
});
it('should update selection and value when selectedId changes', async () => {
const { driver: _driver, rerender } = render(
<Dropdown options={getOptions()} selectedId={0} />,
);
const { dropdownLayoutDriver, inputDriver } = _driver;
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(true);
expect(await inputDriver.getValue()).toBe('Option 1');
rerender(<Dropdown options={getOptions()} selectedId={1} />);
expect(await dropdownLayoutDriver.isOptionSelected(1)).toBe(true);
expect(await inputDriver.getValue()).toBe('Option 2');
});
it('should have no selection when selectedId is null', async () => {
const { driver: _driver } = render(
<Dropdown
options={[{ id: 0, value: 'Option 1' }]}
selectedId={null}
/>,
);
const { dropdownLayoutDriver, inputDriver } = _driver;
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(false);
expect(await inputDriver.getValue()).toBe('');
});
});
describe('Rerender', () => {
it('should clear selection when selectedId is updated to null', async () => {
const { driver: _driver, rerender } = render(
<Dropdown options={getOptions()} selectedId={0} />,
);
const { dropdownLayoutDriver, inputDriver } = _driver;
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(true);
expect(await inputDriver.getValue()).toBe('Option 1');
rerender(<Dropdown options={getOptions()} selectedId={null} />);
expect(await dropdownLayoutDriver.isOptionSelected(0)).toBe(false);
expect(await inputDriver.getValue()).toBe('');
});
});
}
});
| wix/wix-style-react | packages/wix-style-react/src/Dropdown/test/Dropdown.spec.js | JavaScript | mit | 9,504 |
/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ var parentJsonpFunction = window["webpackJsonp"];
/******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) {
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, callbacks = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(installedChunks[chunkId])
/******/ callbacks.push.apply(callbacks, installedChunks[chunkId]);
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);
/******/ while(callbacks.length)
/******/ callbacks.shift().call(null, __webpack_require__);
/******/ if(moreModules[0]) {
/******/ installedModules[0] = 0;
/******/ return __webpack_require__(0);
/******/ }
/******/ };
/******/ var parentHotUpdateCallback = this["webpackHotUpdate"];
/******/ this["webpackHotUpdate"] =
/******/ function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
/******/ hotAddUpdateChunk(chunkId, moreModules);
/******/ if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
/******/ }
/******/
/******/ function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
/******/ var head = document.getElementsByTagName("head")[0];
/******/ var script = document.createElement("script");
/******/ script.type = "text/javascript";
/******/ script.charset = "utf-8";
/******/ script.src = __webpack_require__.p + "" + chunkId + "." + hotCurrentHash + ".hot-update.js";
/******/ head.appendChild(script);
/******/ }
/******/
/******/ function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars
/******/ if(typeof XMLHttpRequest === "undefined")
/******/ return callback(new Error("No browser support"));
/******/ try {
/******/ var request = new XMLHttpRequest();
/******/ var requestPath = __webpack_require__.p + "" + hotCurrentHash + ".hot-update.json";
/******/ request.open("GET", requestPath, true);
/******/ request.timeout = 10000;
/******/ request.send(null);
/******/ } catch(err) {
/******/ return callback(err);
/******/ }
/******/ request.onreadystatechange = function() {
/******/ if(request.readyState !== 4) return;
/******/ if(request.status === 0) {
/******/ // timeout
/******/ callback(new Error("Manifest request to " + requestPath + " timed out."));
/******/ } else if(request.status === 404) {
/******/ // no update available
/******/ callback();
/******/ } else if(request.status !== 200 && request.status !== 304) {
/******/ // other failure
/******/ callback(new Error("Manifest request to " + requestPath + " failed."));
/******/ } else {
/******/ // success
/******/ try {
/******/ var update = JSON.parse(request.responseText);
/******/ } catch(e) {
/******/ callback(e);
/******/ return;
/******/ }
/******/ callback(null, update);
/******/ }
/******/ };
/******/ }
/******/
/******/
/******/ // Copied from https://github.com/facebook/react/blob/bef45b0/src/shared/utils/canDefineProperty.js
/******/ var canDefineProperty = false;
/******/ try {
/******/ Object.defineProperty({}, "x", {
/******/ get: function() {}
/******/ });
/******/ canDefineProperty = true;
/******/ } catch(x) {
/******/ // IE will fail on defineProperty
/******/ }
/******/
/******/ var hotApplyOnUpdate = true;
/******/ var hotCurrentHash = "76da46d3f9751b1fc809"; // eslint-disable-line no-unused-vars
/******/ var hotCurrentModuleData = {};
/******/ var hotCurrentParents = []; // eslint-disable-line no-unused-vars
/******/
/******/ function hotCreateRequire(moduleId) { // eslint-disable-line no-unused-vars
/******/ var me = installedModules[moduleId];
/******/ if(!me) return __webpack_require__;
/******/ var fn = function(request) {
/******/ if(me.hot.active) {
/******/ if(installedModules[request]) {
/******/ if(installedModules[request].parents.indexOf(moduleId) < 0)
/******/ installedModules[request].parents.push(moduleId);
/******/ if(me.children.indexOf(request) < 0)
/******/ me.children.push(request);
/******/ } else hotCurrentParents = [moduleId];
/******/ } else {
/******/ console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
/******/ hotCurrentParents = [];
/******/ }
/******/ return __webpack_require__(request);
/******/ };
/******/ for(var name in __webpack_require__) {
/******/ if(Object.prototype.hasOwnProperty.call(__webpack_require__, name)) {
/******/ if(canDefineProperty) {
/******/ Object.defineProperty(fn, name, (function(name) {
/******/ return {
/******/ configurable: true,
/******/ enumerable: true,
/******/ get: function() {
/******/ return __webpack_require__[name];
/******/ },
/******/ set: function(value) {
/******/ __webpack_require__[name] = value;
/******/ }
/******/ };
/******/ }(name)));
/******/ } else {
/******/ fn[name] = __webpack_require__[name];
/******/ }
/******/ }
/******/ }
/******/
/******/ function ensure(chunkId, callback) {
/******/ if(hotStatus === "ready")
/******/ hotSetStatus("prepare");
/******/ hotChunksLoading++;
/******/ __webpack_require__.e(chunkId, function() {
/******/ try {
/******/ callback.call(null, fn);
/******/ } finally {
/******/ finishChunkLoading();
/******/ }
/******/
/******/ function finishChunkLoading() {
/******/ hotChunksLoading--;
/******/ if(hotStatus === "prepare") {
/******/ if(!hotWaitingFilesMap[chunkId]) {
/******/ hotEnsureUpdateChunk(chunkId);
/******/ }
/******/ if(hotChunksLoading === 0 && hotWaitingFiles === 0) {
/******/ hotUpdateDownloaded();
/******/ }
/******/ }
/******/ }
/******/ });
/******/ }
/******/ if(canDefineProperty) {
/******/ Object.defineProperty(fn, "e", {
/******/ enumerable: true,
/******/ value: ensure
/******/ });
/******/ } else {
/******/ fn.e = ensure;
/******/ }
/******/ return fn;
/******/ }
/******/
/******/ function hotCreateModule(moduleId) { // eslint-disable-line no-unused-vars
/******/ var hot = {
/******/ // private stuff
/******/ _acceptedDependencies: {},
/******/ _declinedDependencies: {},
/******/ _selfAccepted: false,
/******/ _selfDeclined: false,
/******/ _disposeHandlers: [],
/******/
/******/ // Module API
/******/ active: true,
/******/ accept: function(dep, callback) {
/******/ if(typeof dep === "undefined")
/******/ hot._selfAccepted = true;
/******/ else if(typeof dep === "function")
/******/ hot._selfAccepted = dep;
/******/ else if(typeof dep === "object")
/******/ for(var i = 0; i < dep.length; i++)
/******/ hot._acceptedDependencies[dep[i]] = callback;
/******/ else
/******/ hot._acceptedDependencies[dep] = callback;
/******/ },
/******/ decline: function(dep) {
/******/ if(typeof dep === "undefined")
/******/ hot._selfDeclined = true;
/******/ else if(typeof dep === "number")
/******/ hot._declinedDependencies[dep] = true;
/******/ else
/******/ for(var i = 0; i < dep.length; i++)
/******/ hot._declinedDependencies[dep[i]] = true;
/******/ },
/******/ dispose: function(callback) {
/******/ hot._disposeHandlers.push(callback);
/******/ },
/******/ addDisposeHandler: function(callback) {
/******/ hot._disposeHandlers.push(callback);
/******/ },
/******/ removeDisposeHandler: function(callback) {
/******/ var idx = hot._disposeHandlers.indexOf(callback);
/******/ if(idx >= 0) hot._disposeHandlers.splice(idx, 1);
/******/ },
/******/
/******/ // Management API
/******/ check: hotCheck,
/******/ apply: hotApply,
/******/ status: function(l) {
/******/ if(!l) return hotStatus;
/******/ hotStatusHandlers.push(l);
/******/ },
/******/ addStatusHandler: function(l) {
/******/ hotStatusHandlers.push(l);
/******/ },
/******/ removeStatusHandler: function(l) {
/******/ var idx = hotStatusHandlers.indexOf(l);
/******/ if(idx >= 0) hotStatusHandlers.splice(idx, 1);
/******/ },
/******/
/******/ //inherit from previous dispose call
/******/ data: hotCurrentModuleData[moduleId]
/******/ };
/******/ return hot;
/******/ }
/******/
/******/ var hotStatusHandlers = [];
/******/ var hotStatus = "idle";
/******/
/******/ function hotSetStatus(newStatus) {
/******/ hotStatus = newStatus;
/******/ for(var i = 0; i < hotStatusHandlers.length; i++)
/******/ hotStatusHandlers[i].call(null, newStatus);
/******/ }
/******/
/******/ // while downloading
/******/ var hotWaitingFiles = 0;
/******/ var hotChunksLoading = 0;
/******/ var hotWaitingFilesMap = {};
/******/ var hotRequestedFilesMap = {};
/******/ var hotAvailibleFilesMap = {};
/******/ var hotCallback;
/******/
/******/ // The update info
/******/ var hotUpdate, hotUpdateNewHash;
/******/
/******/ function toModuleId(id) {
/******/ var isNumber = (+id) + "" === id;
/******/ return isNumber ? +id : id;
/******/ }
/******/
/******/ function hotCheck(apply, callback) {
/******/ if(hotStatus !== "idle") throw new Error("check() is only allowed in idle status");
/******/ if(typeof apply === "function") {
/******/ hotApplyOnUpdate = false;
/******/ callback = apply;
/******/ } else {
/******/ hotApplyOnUpdate = apply;
/******/ callback = callback || function(err) {
/******/ if(err) throw err;
/******/ };
/******/ }
/******/ hotSetStatus("check");
/******/ hotDownloadManifest(function(err, update) {
/******/ if(err) return callback(err);
/******/ if(!update) {
/******/ hotSetStatus("idle");
/******/ callback(null, null);
/******/ return;
/******/ }
/******/
/******/ hotRequestedFilesMap = {};
/******/ hotAvailibleFilesMap = {};
/******/ hotWaitingFilesMap = {};
/******/ for(var i = 0; i < update.c.length; i++)
/******/ hotAvailibleFilesMap[update.c[i]] = true;
/******/ hotUpdateNewHash = update.h;
/******/
/******/ hotSetStatus("prepare");
/******/ hotCallback = callback;
/******/ hotUpdate = {};
/******/ for(var chunkId in installedChunks)
/******/ { // eslint-disable-line no-lone-blocks
/******/ /*globals chunkId */
/******/ hotEnsureUpdateChunk(chunkId);
/******/ }
/******/ if(hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) {
/******/ hotUpdateDownloaded();
/******/ }
/******/ });
/******/ }
/******/
/******/ function hotAddUpdateChunk(chunkId, moreModules) { // eslint-disable-line no-unused-vars
/******/ if(!hotAvailibleFilesMap[chunkId] || !hotRequestedFilesMap[chunkId])
/******/ return;
/******/ hotRequestedFilesMap[chunkId] = false;
/******/ for(var moduleId in moreModules) {
/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ hotUpdate[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(--hotWaitingFiles === 0 && hotChunksLoading === 0) {
/******/ hotUpdateDownloaded();
/******/ }
/******/ }
/******/
/******/ function hotEnsureUpdateChunk(chunkId) {
/******/ if(!hotAvailibleFilesMap[chunkId]) {
/******/ hotWaitingFilesMap[chunkId] = true;
/******/ } else {
/******/ hotRequestedFilesMap[chunkId] = true;
/******/ hotWaitingFiles++;
/******/ hotDownloadUpdateChunk(chunkId);
/******/ }
/******/ }
/******/
/******/ function hotUpdateDownloaded() {
/******/ hotSetStatus("ready");
/******/ var callback = hotCallback;
/******/ hotCallback = null;
/******/ if(!callback) return;
/******/ if(hotApplyOnUpdate) {
/******/ hotApply(hotApplyOnUpdate, callback);
/******/ } else {
/******/ var outdatedModules = [];
/******/ for(var id in hotUpdate) {
/******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
/******/ outdatedModules.push(toModuleId(id));
/******/ }
/******/ }
/******/ callback(null, outdatedModules);
/******/ }
/******/ }
/******/
/******/ function hotApply(options, callback) {
/******/ if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status");
/******/ if(typeof options === "function") {
/******/ callback = options;
/******/ options = {};
/******/ } else if(options && typeof options === "object") {
/******/ callback = callback || function(err) {
/******/ if(err) throw err;
/******/ };
/******/ } else {
/******/ options = {};
/******/ callback = callback || function(err) {
/******/ if(err) throw err;
/******/ };
/******/ }
/******/
/******/ function getAffectedStuff(module) {
/******/ var outdatedModules = [module];
/******/ var outdatedDependencies = {};
/******/
/******/ var queue = outdatedModules.slice();
/******/ while(queue.length > 0) {
/******/ var moduleId = queue.pop();
/******/ var module = installedModules[moduleId];
/******/ if(!module || module.hot._selfAccepted)
/******/ continue;
/******/ if(module.hot._selfDeclined) {
/******/ return new Error("Aborted because of self decline: " + moduleId);
/******/ }
/******/ if(moduleId === 0) {
/******/ return;
/******/ }
/******/ for(var i = 0; i < module.parents.length; i++) {
/******/ var parentId = module.parents[i];
/******/ var parent = installedModules[parentId];
/******/ if(parent.hot._declinedDependencies[moduleId]) {
/******/ return new Error("Aborted because of declined dependency: " + moduleId + " in " + parentId);
/******/ }
/******/ if(outdatedModules.indexOf(parentId) >= 0) continue;
/******/ if(parent.hot._acceptedDependencies[moduleId]) {
/******/ if(!outdatedDependencies[parentId])
/******/ outdatedDependencies[parentId] = [];
/******/ addAllToSet(outdatedDependencies[parentId], [moduleId]);
/******/ continue;
/******/ }
/******/ delete outdatedDependencies[parentId];
/******/ outdatedModules.push(parentId);
/******/ queue.push(parentId);
/******/ }
/******/ }
/******/
/******/ return [outdatedModules, outdatedDependencies];
/******/ }
/******/
/******/ function addAllToSet(a, b) {
/******/ for(var i = 0; i < b.length; i++) {
/******/ var item = b[i];
/******/ if(a.indexOf(item) < 0)
/******/ a.push(item);
/******/ }
/******/ }
/******/
/******/ // at begin all updates modules are outdated
/******/ // the "outdated" status can propagate to parents if they don't accept the children
/******/ var outdatedDependencies = {};
/******/ var outdatedModules = [];
/******/ var appliedUpdate = {};
/******/ for(var id in hotUpdate) {
/******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
/******/ var moduleId = toModuleId(id);
/******/ var result = getAffectedStuff(moduleId);
/******/ if(!result) {
/******/ if(options.ignoreUnaccepted)
/******/ continue;
/******/ hotSetStatus("abort");
/******/ return callback(new Error("Aborted because " + moduleId + " is not accepted"));
/******/ }
/******/ if(result instanceof Error) {
/******/ hotSetStatus("abort");
/******/ return callback(result);
/******/ }
/******/ appliedUpdate[moduleId] = hotUpdate[moduleId];
/******/ addAllToSet(outdatedModules, result[0]);
/******/ for(var moduleId in result[1]) {
/******/ if(Object.prototype.hasOwnProperty.call(result[1], moduleId)) {
/******/ if(!outdatedDependencies[moduleId])
/******/ outdatedDependencies[moduleId] = [];
/******/ addAllToSet(outdatedDependencies[moduleId], result[1][moduleId]);
/******/ }
/******/ }
/******/ }
/******/ }
/******/
/******/ // Store self accepted outdated modules to require them later by the module system
/******/ var outdatedSelfAcceptedModules = [];
/******/ for(var i = 0; i < outdatedModules.length; i++) {
/******/ var moduleId = outdatedModules[i];
/******/ if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted)
/******/ outdatedSelfAcceptedModules.push({
/******/ module: moduleId,
/******/ errorHandler: installedModules[moduleId].hot._selfAccepted
/******/ });
/******/ }
/******/
/******/ // Now in "dispose" phase
/******/ hotSetStatus("dispose");
/******/ var queue = outdatedModules.slice();
/******/ while(queue.length > 0) {
/******/ var moduleId = queue.pop();
/******/ var module = installedModules[moduleId];
/******/ if(!module) continue;
/******/
/******/ var data = {};
/******/
/******/ // Call dispose handlers
/******/ var disposeHandlers = module.hot._disposeHandlers;
/******/ for(var j = 0; j < disposeHandlers.length; j++) {
/******/ var cb = disposeHandlers[j];
/******/ cb(data);
/******/ }
/******/ hotCurrentModuleData[moduleId] = data;
/******/
/******/ // disable module (this disables requires from this module)
/******/ module.hot.active = false;
/******/
/******/ // remove module from cache
/******/ delete installedModules[moduleId];
/******/
/******/ // remove "parents" references from all children
/******/ for(var j = 0; j < module.children.length; j++) {
/******/ var child = installedModules[module.children[j]];
/******/ if(!child) continue;
/******/ var idx = child.parents.indexOf(moduleId);
/******/ if(idx >= 0) {
/******/ child.parents.splice(idx, 1);
/******/ }
/******/ }
/******/ }
/******/
/******/ // remove outdated dependency from module children
/******/ for(var moduleId in outdatedDependencies) {
/******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
/******/ var module = installedModules[moduleId];
/******/ var moduleOutdatedDependencies = outdatedDependencies[moduleId];
/******/ for(var j = 0; j < moduleOutdatedDependencies.length; j++) {
/******/ var dependency = moduleOutdatedDependencies[j];
/******/ var idx = module.children.indexOf(dependency);
/******/ if(idx >= 0) module.children.splice(idx, 1);
/******/ }
/******/ }
/******/ }
/******/
/******/ // Not in "apply" phase
/******/ hotSetStatus("apply");
/******/
/******/ hotCurrentHash = hotUpdateNewHash;
/******/
/******/ // insert new code
/******/ for(var moduleId in appliedUpdate) {
/******/ if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) {
/******/ modules[moduleId] = appliedUpdate[moduleId];
/******/ }
/******/ }
/******/
/******/ // call accept handlers
/******/ var error = null;
/******/ for(var moduleId in outdatedDependencies) {
/******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
/******/ var module = installedModules[moduleId];
/******/ var moduleOutdatedDependencies = outdatedDependencies[moduleId];
/******/ var callbacks = [];
/******/ for(var i = 0; i < moduleOutdatedDependencies.length; i++) {
/******/ var dependency = moduleOutdatedDependencies[i];
/******/ var cb = module.hot._acceptedDependencies[dependency];
/******/ if(callbacks.indexOf(cb) >= 0) continue;
/******/ callbacks.push(cb);
/******/ }
/******/ for(var i = 0; i < callbacks.length; i++) {
/******/ var cb = callbacks[i];
/******/ try {
/******/ cb(outdatedDependencies);
/******/ } catch(err) {
/******/ if(!error)
/******/ error = err;
/******/ }
/******/ }
/******/ }
/******/ }
/******/
/******/ // Load self accepted modules
/******/ for(var i = 0; i < outdatedSelfAcceptedModules.length; i++) {
/******/ var item = outdatedSelfAcceptedModules[i];
/******/ var moduleId = item.module;
/******/ hotCurrentParents = [moduleId];
/******/ try {
/******/ __webpack_require__(moduleId);
/******/ } catch(err) {
/******/ if(typeof item.errorHandler === "function") {
/******/ try {
/******/ item.errorHandler(err);
/******/ } catch(err) {
/******/ if(!error)
/******/ error = err;
/******/ }
/******/ } else if(!error)
/******/ error = err;
/******/ }
/******/ }
/******/
/******/ // handle errors in accept handlers and self accepted module load
/******/ if(error) {
/******/ hotSetStatus("fail");
/******/ return callback(error);
/******/ }
/******/
/******/ hotSetStatus("idle");
/******/ callback(null, outdatedModules);
/******/ }
/******/ // The module cache
/******/ var installedModules = {};
/******/ // object to store loaded and loading chunks
/******/ // "0" means "already loaded"
/******/ // Array means "loading", array contains callbacks
/******/ var installedChunks = {
/******/ 0:0
/******/ };
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false,
/******/ hot: hotCreateModule(moduleId),
/******/ parents: hotCurrentParents,
/******/ children: []
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId, callback) {
/******/ // "0" is the signal for "already loaded"
/******/ if(installedChunks[chunkId] === 0)
/******/ return callback.call(null, __webpack_require__);
/******/ // an array means "currently loading".
/******/ if(installedChunks[chunkId] !== undefined) {
/******/ installedChunks[chunkId].push(callback);
/******/ } else {
/******/ // start chunk loading
/******/ installedChunks[chunkId] = [callback];
/******/ var head = document.getElementsByTagName('head')[0];
/******/ var script = document.createElement('script');
/******/ script.type = 'text/javascript';
/******/ script.charset = 'utf-8';
/******/ script.async = true;
/******/ script.src = __webpack_require__.p + "" + chunkId + ".chunk.js";
/******/ head.appendChild(script);
/******/ }
/******/ };
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // __webpack_hash__
/******/ __webpack_require__.h = function() { return hotCurrentHash; };
/******/ // Load entry module and return exports
/******/ return hotCreateRequire(0)(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
// Polyfills
// (these modules are what are in '@angularbundles/angular2-polyfills' so don't use that here)
"use strict";
// import 'ie-shim'; // Internet Explorer
// import 'es6-shim';
// import 'es6-promise';
// import 'es7-reflect-metadata';
// Prefer CoreJS over the polyfills above
__webpack_require__(681);
__webpack_require__(682);
__webpack_require__(846);
// Typescript "emit helpers" polyfill
__webpack_require__(844);
if (false) {
}
else {
// Development
Error.stackTraceLimit = Infinity;
__webpack_require__(845);
}
/***/ },
/* 1 */,
/* 2 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(15)
, core = __webpack_require__(53)
, hide = __webpack_require__(37)
, redefine = __webpack_require__(38)
, ctx = __webpack_require__(54)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ },
/* 3 */,
/* 4 */,
/* 5 */,
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 7 */,
/* 8 */,
/* 9 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 10 */,
/* 11 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 12 */,
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var store = __webpack_require__(156)('wks')
, uid = __webpack_require__(85)
, Symbol = __webpack_require__(15).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ },
/* 14 */,
/* 15 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 16 */,
/* 17 */,
/* 18 */,
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(6)
, IE8_DOM_DEFINE = __webpack_require__(390)
, toPrimitive = __webpack_require__(71)
, dP = Object.defineProperty;
exports.f = __webpack_require__(24) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ },
/* 20 */,
/* 21 */,
/* 22 */,
/* 23 */,
/* 24 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(9)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 25 */,
/* 26 */,
/* 27 */,
/* 28 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(70)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 30 */,
/* 31 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, fails = __webpack_require__(9)
, defined = __webpack_require__(55)
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ },
/* 32 */,
/* 33 */,
/* 34 */,
/* 35 */,
/* 36 */,
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(19)
, createDesc = __webpack_require__(69);
module.exports = __webpack_require__(24) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(15)
, hide = __webpack_require__(37)
, has = __webpack_require__(28)
, SRC = __webpack_require__(85)('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
__webpack_require__(53).inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(55);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
var fails = __webpack_require__(9);
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(112)
, defined = __webpack_require__(55);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 42 */,
/* 43 */
/***/ function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(54)
, IObject = __webpack_require__(112)
, toObject = __webpack_require__(39)
, toLength = __webpack_require__(29)
, asc = __webpack_require__(685);
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(28)
, toObject = __webpack_require__(39)
, IE_PROTO = __webpack_require__(249)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(2)
, core = __webpack_require__(53)
, fails = __webpack_require__(9);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
/***/ },
/* 46 */,
/* 47 */,
/* 48 */,
/* 49 */,
/* 50 */,
/* 51 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 52 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 53 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(51);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 55 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
var Map = __webpack_require__(408)
, $export = __webpack_require__(2)
, shared = __webpack_require__(156)('metadata')
, store = shared.store || (shared.store = new (__webpack_require__(411)));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(154)
, createDesc = __webpack_require__(69)
, toIObject = __webpack_require__(41)
, toPrimitive = __webpack_require__(71)
, has = __webpack_require__(28)
, IE8_DOM_DEFINE = __webpack_require__(390)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(24) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
if(__webpack_require__(24)){
var LIBRARY = __webpack_require__(97)
, global = __webpack_require__(15)
, fails = __webpack_require__(9)
, $export = __webpack_require__(2)
, $typed = __webpack_require__(158)
, $buffer = __webpack_require__(253)
, ctx = __webpack_require__(54)
, anInstance = __webpack_require__(81)
, propertyDesc = __webpack_require__(69)
, hide = __webpack_require__(37)
, redefineAll = __webpack_require__(99)
, isInteger = __webpack_require__(244)
, toInteger = __webpack_require__(70)
, toLength = __webpack_require__(29)
, toIndex = __webpack_require__(84)
, toPrimitive = __webpack_require__(71)
, has = __webpack_require__(28)
, same = __webpack_require__(402)
, classof = __webpack_require__(110)
, isObject = __webpack_require__(11)
, toObject = __webpack_require__(39)
, isArrayIter = __webpack_require__(242)
, create = __webpack_require__(82)
, getPrototypeOf = __webpack_require__(44)
, gOPN = __webpack_require__(83).f
, isIterable = __webpack_require__(692)
, getIterFn = __webpack_require__(254)
, uid = __webpack_require__(85)
, wks = __webpack_require__(13)
, createArrayMethod = __webpack_require__(43)
, createArrayIncludes = __webpack_require__(235)
, speciesConstructor = __webpack_require__(250)
, ArrayIterators = __webpack_require__(407)
, Iterators = __webpack_require__(96)
, $iterDetect = __webpack_require__(152)
, setSpecies = __webpack_require__(100)
, arrayFill = __webpack_require__(234)
, arrayCopyWithin = __webpack_require__(384)
, $DP = __webpack_require__(19)
, $GOPD = __webpack_require__(57)
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
/***/ },
/* 59 */,
/* 60 */,
/* 61 */,
/* 62 */,
/* 63 */,
/* 64 */,
/* 65 */,
/* 66 */,
/* 67 */,
/* 68 */
/***/ function(module, exports, __webpack_require__) {
var META = __webpack_require__(85)('meta')
, isObject = __webpack_require__(11)
, has = __webpack_require__(28)
, setDesc = __webpack_require__(19).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !__webpack_require__(9)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ },
/* 69 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 70 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(11);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ },
/* 72 */,
/* 73 */,
/* 74 */,
/* 75 */,
/* 76 */,
/* 77 */,
/* 78 */,
/* 79 */,
/* 80 */,
/* 81 */
/***/ function(module, exports) {
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(6)
, dPs = __webpack_require__(397)
, enumBugKeys = __webpack_require__(237)
, IE_PROTO = __webpack_require__(249)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(236)('iframe')
, i = enumBugKeys.length
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
__webpack_require__(240).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(399)
, hiddenKeys = __webpack_require__(237).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(70)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 85 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 86 */,
/* 87 */,
/* 88 */,
/* 89 */,
/* 90 */,
/* 91 */,
/* 92 */,
/* 93 */,
/* 94 */,
/* 95 */,
/* 96 */
/***/ function(module, exports) {
module.exports = {};
/***/ },
/* 97 */
/***/ function(module, exports) {
module.exports = false;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(399)
, enumBugKeys = __webpack_require__(237);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ },
/* 99 */
/***/ function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(38);
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(15)
, dP = __webpack_require__(19)
, DESCRIPTORS = __webpack_require__(24)
, SPECIES = __webpack_require__(13)('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var def = __webpack_require__(19).f
, has = __webpack_require__(28)
, TAG = __webpack_require__(13)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
/***/ },
/* 102 */,
/* 103 */,
/* 104 */,
/* 105 */,
/* 106 */,
/* 107 */,
/* 108 */,
/* 109 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(13)('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(37)(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(52)
, TAG = __webpack_require__(13)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(54)
, call = __webpack_require__(392)
, isArrayIter = __webpack_require__(242)
, anObject = __webpack_require__(6)
, toLength = __webpack_require__(29)
, getIterFn = __webpack_require__(254)
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(52);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 113 */,
/* 114 */,
/* 115 */,
/* 116 */,
/* 117 */,
/* 118 */,
/* 119 */,
/* 120 */,
/* 121 */,
/* 122 */,
/* 123 */,
/* 124 */,
/* 125 */,
/* 126 */,
/* 127 */,
/* 128 */,
/* 129 */,
/* 130 */,
/* 131 */,
/* 132 */,
/* 133 */,
/* 134 */,
/* 135 */,
/* 136 */,
/* 137 */,
/* 138 */,
/* 139 */,
/* 140 */,
/* 141 */,
/* 142 */,
/* 143 */,
/* 144 */,
/* 145 */,
/* 146 */,
/* 147 */,
/* 148 */,
/* 149 */,
/* 150 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(15)
, $export = __webpack_require__(2)
, redefine = __webpack_require__(38)
, redefineAll = __webpack_require__(99)
, meta = __webpack_require__(68)
, forOf = __webpack_require__(111)
, anInstance = __webpack_require__(81)
, isObject = __webpack_require__(11)
, fails = __webpack_require__(9)
, $iterDetect = __webpack_require__(152)
, setToStringTag = __webpack_require__(101)
, inheritIfRequired = __webpack_require__(241);
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var hide = __webpack_require__(37)
, redefine = __webpack_require__(38)
, fails = __webpack_require__(9)
, defined = __webpack_require__(55)
, wks = __webpack_require__(13);
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(13)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
/***/ },
/* 153 */
/***/ function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ },
/* 154 */
/***/ function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(11)
, anObject = __webpack_require__(6);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = __webpack_require__(54)(Function.call, __webpack_require__(57).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(15)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, defined = __webpack_require__(55)
, fails = __webpack_require__(9)
, spaces = __webpack_require__(252)
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(15)
, hide = __webpack_require__(37)
, uid = __webpack_require__(85)
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
/***/ },
/* 159 */,
/* 160 */,
/* 161 */,
/* 162 */,
/* 163 */,
/* 164 */,
/* 165 */,
/* 166 */,
/* 167 */,
/* 168 */,
/* 169 */,
/* 170 */,
/* 171 */,
/* 172 */,
/* 173 */,
/* 174 */,
/* 175 */,
/* 176 */,
/* 177 */,
/* 178 */,
/* 179 */,
/* 180 */,
/* 181 */,
/* 182 */,
/* 183 */,
/* 184 */,
/* 185 */,
/* 186 */,
/* 187 */,
/* 188 */,
/* 189 */,
/* 190 */,
/* 191 */,
/* 192 */,
/* 193 */,
/* 194 */,
/* 195 */,
/* 196 */,
/* 197 */,
/* 198 */,
/* 199 */,
/* 200 */,
/* 201 */,
/* 202 */,
/* 203 */,
/* 204 */,
/* 205 */,
/* 206 */,
/* 207 */,
/* 208 */,
/* 209 */,
/* 210 */,
/* 211 */,
/* 212 */,
/* 213 */,
/* 214 */,
/* 215 */,
/* 216 */,
/* 217 */,
/* 218 */,
/* 219 */,
/* 220 */,
/* 221 */,
/* 222 */,
/* 223 */,
/* 224 */,
/* 225 */,
/* 226 */,
/* 227 */,
/* 228 */,
/* 229 */,
/* 230 */,
/* 231 */,
/* 232 */,
/* 233 */,
/* 234 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = __webpack_require__(39)
, toIndex = __webpack_require__(84)
, toLength = __webpack_require__(29);
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
/***/ },
/* 235 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(41)
, toLength = __webpack_require__(29)
, toIndex = __webpack_require__(84);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 236 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, document = __webpack_require__(15).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 237 */
/***/ function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ },
/* 238 */
/***/ function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(13)('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
/***/ },
/* 239 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(6);
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
/***/ },
/* 240 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(15).document && document.documentElement;
/***/ },
/* 241 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, setPrototypeOf = __webpack_require__(155).set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
/***/ },
/* 242 */
/***/ function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(96)
, ITERATOR = __webpack_require__(13)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ },
/* 243 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(52);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
/***/ },
/* 244 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(11)
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ },
/* 245 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(11)
, cof = __webpack_require__(52)
, MATCH = __webpack_require__(13)('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ },
/* 246 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(97)
, $export = __webpack_require__(2)
, redefine = __webpack_require__(38)
, hide = __webpack_require__(37)
, has = __webpack_require__(28)
, Iterators = __webpack_require__(96)
, $iterCreate = __webpack_require__(393)
, setToStringTag = __webpack_require__(101)
, getPrototypeOf = __webpack_require__(44)
, ITERATOR = __webpack_require__(13)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ },
/* 247 */
/***/ function(module, exports) {
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
/***/ },
/* 248 */
/***/ function(module, exports) {
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
/***/ },
/* 249 */
/***/ function(module, exports, __webpack_require__) {
var shared = __webpack_require__(156)('keys')
, uid = __webpack_require__(85);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ },
/* 250 */
/***/ function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(6)
, aFunction = __webpack_require__(51)
, SPECIES = __webpack_require__(13)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ },
/* 251 */
/***/ function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(245)
, defined = __webpack_require__(55);
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ },
/* 252 */
/***/ function(module, exports) {
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
/***/ },
/* 253 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(15)
, DESCRIPTORS = __webpack_require__(24)
, LIBRARY = __webpack_require__(97)
, $typed = __webpack_require__(158)
, hide = __webpack_require__(37)
, redefineAll = __webpack_require__(99)
, fails = __webpack_require__(9)
, anInstance = __webpack_require__(81)
, toInteger = __webpack_require__(70)
, toLength = __webpack_require__(29)
, gOPN = __webpack_require__(83).f
, dP = __webpack_require__(19).f
, arrayFill = __webpack_require__(234)
, setToStringTag = __webpack_require__(101)
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, parseInt = global.parseInt
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, min = Math.min
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * 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) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
/***/ },
/* 254 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(110)
, ITERATOR = __webpack_require__(13)('iterator')
, Iterators = __webpack_require__(96);
module.exports = __webpack_require__(53).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ },
/* 255 */,
/* 256 */,
/* 257 */,
/* 258 */,
/* 259 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
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 = setTimeout(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;
clearTimeout(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) {
setTimeout(drainQueue, 0);
}
};
// 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.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; };
/***/ },
/* 260 */,
/* 261 */,
/* 262 */,
/* 263 */,
/* 264 */,
/* 265 */,
/* 266 */,
/* 267 */,
/* 268 */,
/* 269 */,
/* 270 */,
/* 271 */,
/* 272 */,
/* 273 */,
/* 274 */,
/* 275 */,
/* 276 */,
/* 277 */,
/* 278 */,
/* 279 */,
/* 280 */,
/* 281 */,
/* 282 */,
/* 283 */,
/* 284 */,
/* 285 */,
/* 286 */,
/* 287 */,
/* 288 */,
/* 289 */,
/* 290 */,
/* 291 */,
/* 292 */,
/* 293 */,
/* 294 */,
/* 295 */,
/* 296 */,
/* 297 */,
/* 298 */,
/* 299 */,
/* 300 */,
/* 301 */,
/* 302 */,
/* 303 */,
/* 304 */,
/* 305 */,
/* 306 */,
/* 307 */,
/* 308 */,
/* 309 */,
/* 310 */,
/* 311 */,
/* 312 */,
/* 313 */,
/* 314 */,
/* 315 */,
/* 316 */,
/* 317 */,
/* 318 */,
/* 319 */,
/* 320 */,
/* 321 */,
/* 322 */,
/* 323 */,
/* 324 */,
/* 325 */,
/* 326 */,
/* 327 */,
/* 328 */,
/* 329 */,
/* 330 */,
/* 331 */,
/* 332 */,
/* 333 */,
/* 334 */,
/* 335 */,
/* 336 */,
/* 337 */,
/* 338 */,
/* 339 */,
/* 340 */,
/* 341 */,
/* 342 */,
/* 343 */,
/* 344 */,
/* 345 */,
/* 346 */,
/* 347 */,
/* 348 */,
/* 349 */,
/* 350 */,
/* 351 */,
/* 352 */,
/* 353 */,
/* 354 */,
/* 355 */,
/* 356 */,
/* 357 */,
/* 358 */,
/* 359 */,
/* 360 */,
/* 361 */,
/* 362 */,
/* 363 */,
/* 364 */,
/* 365 */,
/* 366 */,
/* 367 */,
/* 368 */,
/* 369 */,
/* 370 */,
/* 371 */,
/* 372 */,
/* 373 */,
/* 374 */,
/* 375 */,
/* 376 */,
/* 377 */,
/* 378 */,
/* 379 */,
/* 380 */,
/* 381 */,
/* 382 */,
/* 383 */
/***/ function(module, exports, __webpack_require__) {
var cof = __webpack_require__(52);
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
/***/ },
/* 384 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = __webpack_require__(39)
, toIndex = __webpack_require__(84)
, toLength = __webpack_require__(29);
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ },
/* 385 */
/***/ function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(51)
, toObject = __webpack_require__(39)
, IObject = __webpack_require__(112)
, toLength = __webpack_require__(29);
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
/***/ },
/* 386 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var aFunction = __webpack_require__(51)
, isObject = __webpack_require__(11)
, invoke = __webpack_require__(391)
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
/***/ },
/* 387 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var dP = __webpack_require__(19).f
, create = __webpack_require__(82)
, hide = __webpack_require__(37)
, redefineAll = __webpack_require__(99)
, ctx = __webpack_require__(54)
, anInstance = __webpack_require__(81)
, defined = __webpack_require__(55)
, forOf = __webpack_require__(111)
, $iterDefine = __webpack_require__(246)
, step = __webpack_require__(394)
, setSpecies = __webpack_require__(100)
, DESCRIPTORS = __webpack_require__(24)
, fastKey = __webpack_require__(68).fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ },
/* 388 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var redefineAll = __webpack_require__(99)
, getWeak = __webpack_require__(68).getWeak
, anObject = __webpack_require__(6)
, isObject = __webpack_require__(11)
, anInstance = __webpack_require__(81)
, forOf = __webpack_require__(111)
, createArrayMethod = __webpack_require__(43)
, $has = __webpack_require__(28)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ },
/* 389 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $defineProperty = __webpack_require__(19)
, createDesc = __webpack_require__(69);
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ },
/* 390 */
/***/ function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(24) && !__webpack_require__(9)(function(){
return Object.defineProperty(__webpack_require__(236)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 391 */
/***/ function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ },
/* 392 */
/***/ function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(6);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
/***/ },
/* 393 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var create = __webpack_require__(82)
, descriptor = __webpack_require__(69)
, setToStringTag = __webpack_require__(101)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(37)(IteratorPrototype, __webpack_require__(13)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ },
/* 394 */
/***/ function(module, exports) {
module.exports = function(done, value){
return {value: value, done: !!done};
};
/***/ },
/* 395 */
/***/ function(module, exports) {
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
/***/ },
/* 396 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(98)
, gOPS = __webpack_require__(153)
, pIE = __webpack_require__(154)
, toObject = __webpack_require__(39)
, IObject = __webpack_require__(112)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(9)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
/***/ },
/* 397 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(19)
, anObject = __webpack_require__(6)
, getKeys = __webpack_require__(98);
module.exports = __webpack_require__(24) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ },
/* 398 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(41)
, gOPN = __webpack_require__(83).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ },
/* 399 */
/***/ function(module, exports, __webpack_require__) {
var has = __webpack_require__(28)
, toIObject = __webpack_require__(41)
, arrayIndexOf = __webpack_require__(235)(false)
, IE_PROTO = __webpack_require__(249)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ },
/* 400 */
/***/ function(module, exports, __webpack_require__) {
var $parseFloat = __webpack_require__(15).parseFloat
, $trim = __webpack_require__(157).trim;
module.exports = 1 / $parseFloat(__webpack_require__(252) + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
/***/ },
/* 401 */
/***/ function(module, exports, __webpack_require__) {
var $parseInt = __webpack_require__(15).parseInt
, $trim = __webpack_require__(157).trim
, ws = __webpack_require__(252)
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
/***/ },
/* 402 */
/***/ function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ },
/* 403 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(70)
, defined = __webpack_require__(55);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ },
/* 404 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var toInteger = __webpack_require__(70)
, defined = __webpack_require__(55);
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
/***/ },
/* 405 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(54)
, invoke = __webpack_require__(391)
, html = __webpack_require__(240)
, cel = __webpack_require__(236)
, global = __webpack_require__(15)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(__webpack_require__(52)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ },
/* 406 */
/***/ function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(13);
/***/ },
/* 407 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var addToUnscopables = __webpack_require__(109)
, step = __webpack_require__(394)
, Iterators = __webpack_require__(96)
, toIObject = __webpack_require__(41);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(246)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ },
/* 408 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(387);
// 23.1 Map Objects
module.exports = __webpack_require__(150)('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ },
/* 409 */
/***/ function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
if(__webpack_require__(24) && /./g.flags != 'g')__webpack_require__(19).f(RegExp.prototype, 'flags', {
configurable: true,
get: __webpack_require__(239)
});
/***/ },
/* 410 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(387);
// 23.2 Set Objects
module.exports = __webpack_require__(150)('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ },
/* 411 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var each = __webpack_require__(43)(0)
, redefine = __webpack_require__(38)
, meta = __webpack_require__(68)
, assign = __webpack_require__(396)
, weak = __webpack_require__(388)
, isObject = __webpack_require__(11)
, has = __webpack_require__(28)
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(150)('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ },
/* 412 */,
/* 413 */,
/* 414 */,
/* 415 */,
/* 416 */,
/* 417 */,
/* 418 */,
/* 419 */,
/* 420 */,
/* 421 */,
/* 422 */,
/* 423 */,
/* 424 */,
/* 425 */,
/* 426 */,
/* 427 */,
/* 428 */,
/* 429 */,
/* 430 */,
/* 431 */,
/* 432 */,
/* 433 */,
/* 434 */,
/* 435 */,
/* 436 */,
/* 437 */,
/* 438 */,
/* 439 */,
/* 440 */,
/* 441 */,
/* 442 */,
/* 443 */,
/* 444 */,
/* 445 */,
/* 446 */,
/* 447 */,
/* 448 */,
/* 449 */,
/* 450 */,
/* 451 */,
/* 452 */,
/* 453 */,
/* 454 */,
/* 455 */,
/* 456 */,
/* 457 */,
/* 458 */,
/* 459 */,
/* 460 */,
/* 461 */,
/* 462 */,
/* 463 */,
/* 464 */,
/* 465 */,
/* 466 */,
/* 467 */,
/* 468 */,
/* 469 */,
/* 470 */,
/* 471 */,
/* 472 */,
/* 473 */,
/* 474 */,
/* 475 */,
/* 476 */,
/* 477 */,
/* 478 */,
/* 479 */,
/* 480 */,
/* 481 */,
/* 482 */,
/* 483 */,
/* 484 */,
/* 485 */,
/* 486 */,
/* 487 */,
/* 488 */,
/* 489 */,
/* 490 */,
/* 491 */,
/* 492 */,
/* 493 */,
/* 494 */,
/* 495 */,
/* 496 */,
/* 497 */,
/* 498 */,
/* 499 */,
/* 500 */,
/* 501 */,
/* 502 */,
/* 503 */,
/* 504 */,
/* 505 */,
/* 506 */,
/* 507 */,
/* 508 */,
/* 509 */,
/* 510 */,
/* 511 */,
/* 512 */,
/* 513 */,
/* 514 */,
/* 515 */,
/* 516 */,
/* 517 */,
/* 518 */,
/* 519 */,
/* 520 */,
/* 521 */,
/* 522 */,
/* 523 */,
/* 524 */,
/* 525 */,
/* 526 */,
/* 527 */,
/* 528 */,
/* 529 */,
/* 530 */,
/* 531 */,
/* 532 */,
/* 533 */,
/* 534 */,
/* 535 */,
/* 536 */,
/* 537 */,
/* 538 */,
/* 539 */,
/* 540 */,
/* 541 */,
/* 542 */,
/* 543 */,
/* 544 */,
/* 545 */,
/* 546 */,
/* 547 */,
/* 548 */,
/* 549 */,
/* 550 */,
/* 551 */,
/* 552 */,
/* 553 */,
/* 554 */,
/* 555 */,
/* 556 */,
/* 557 */,
/* 558 */,
/* 559 */,
/* 560 */,
/* 561 */,
/* 562 */,
/* 563 */,
/* 564 */,
/* 565 */,
/* 566 */,
/* 567 */,
/* 568 */,
/* 569 */,
/* 570 */,
/* 571 */,
/* 572 */,
/* 573 */,
/* 574 */,
/* 575 */,
/* 576 */,
/* 577 */,
/* 578 */,
/* 579 */,
/* 580 */,
/* 581 */,
/* 582 */,
/* 583 */,
/* 584 */,
/* 585 */,
/* 586 */,
/* 587 */,
/* 588 */,
/* 589 */,
/* 590 */,
/* 591 */,
/* 592 */,
/* 593 */,
/* 594 */,
/* 595 */,
/* 596 */,
/* 597 */,
/* 598 */,
/* 599 */,
/* 600 */,
/* 601 */,
/* 602 */,
/* 603 */,
/* 604 */,
/* 605 */,
/* 606 */,
/* 607 */,
/* 608 */,
/* 609 */,
/* 610 */,
/* 611 */,
/* 612 */,
/* 613 */,
/* 614 */,
/* 615 */,
/* 616 */,
/* 617 */,
/* 618 */,
/* 619 */,
/* 620 */,
/* 621 */,
/* 622 */,
/* 623 */,
/* 624 */,
/* 625 */,
/* 626 */,
/* 627 */,
/* 628 */,
/* 629 */,
/* 630 */,
/* 631 */,
/* 632 */,
/* 633 */,
/* 634 */,
/* 635 */,
/* 636 */,
/* 637 */,
/* 638 */,
/* 639 */,
/* 640 */,
/* 641 */,
/* 642 */,
/* 643 */,
/* 644 */,
/* 645 */,
/* 646 */,
/* 647 */,
/* 648 */,
/* 649 */,
/* 650 */,
/* 651 */,
/* 652 */,
/* 653 */,
/* 654 */,
/* 655 */,
/* 656 */,
/* 657 */,
/* 658 */,
/* 659 */,
/* 660 */,
/* 661 */,
/* 662 */,
/* 663 */,
/* 664 */,
/* 665 */,
/* 666 */,
/* 667 */,
/* 668 */,
/* 669 */,
/* 670 */,
/* 671 */,
/* 672 */,
/* 673 */,
/* 674 */,
/* 675 */,
/* 676 */,
/* 677 */,
/* 678 */,
/* 679 */,
/* 680 */,
/* 681 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(812);
__webpack_require__(751);
__webpack_require__(753);
__webpack_require__(752);
__webpack_require__(755);
__webpack_require__(757);
__webpack_require__(762);
__webpack_require__(756);
__webpack_require__(754);
__webpack_require__(764);
__webpack_require__(763);
__webpack_require__(759);
__webpack_require__(760);
__webpack_require__(758);
__webpack_require__(750);
__webpack_require__(761);
__webpack_require__(765);
__webpack_require__(766);
__webpack_require__(718);
__webpack_require__(720);
__webpack_require__(719);
__webpack_require__(768);
__webpack_require__(767);
__webpack_require__(738);
__webpack_require__(748);
__webpack_require__(749);
__webpack_require__(739);
__webpack_require__(740);
__webpack_require__(741);
__webpack_require__(742);
__webpack_require__(743);
__webpack_require__(744);
__webpack_require__(745);
__webpack_require__(746);
__webpack_require__(747);
__webpack_require__(721);
__webpack_require__(722);
__webpack_require__(723);
__webpack_require__(724);
__webpack_require__(725);
__webpack_require__(726);
__webpack_require__(727);
__webpack_require__(728);
__webpack_require__(729);
__webpack_require__(730);
__webpack_require__(731);
__webpack_require__(732);
__webpack_require__(733);
__webpack_require__(734);
__webpack_require__(735);
__webpack_require__(736);
__webpack_require__(737);
__webpack_require__(799);
__webpack_require__(804);
__webpack_require__(811);
__webpack_require__(802);
__webpack_require__(794);
__webpack_require__(795);
__webpack_require__(800);
__webpack_require__(805);
__webpack_require__(807);
__webpack_require__(790);
__webpack_require__(791);
__webpack_require__(792);
__webpack_require__(793);
__webpack_require__(796);
__webpack_require__(797);
__webpack_require__(798);
__webpack_require__(801);
__webpack_require__(803);
__webpack_require__(806);
__webpack_require__(808);
__webpack_require__(809);
__webpack_require__(810);
__webpack_require__(713);
__webpack_require__(715);
__webpack_require__(714);
__webpack_require__(717);
__webpack_require__(716);
__webpack_require__(702);
__webpack_require__(700);
__webpack_require__(706);
__webpack_require__(703);
__webpack_require__(709);
__webpack_require__(711);
__webpack_require__(699);
__webpack_require__(705);
__webpack_require__(696);
__webpack_require__(710);
__webpack_require__(694);
__webpack_require__(708);
__webpack_require__(707);
__webpack_require__(701);
__webpack_require__(704);
__webpack_require__(693);
__webpack_require__(695);
__webpack_require__(698);
__webpack_require__(697);
__webpack_require__(712);
__webpack_require__(407);
__webpack_require__(784);
__webpack_require__(789);
__webpack_require__(409);
__webpack_require__(785);
__webpack_require__(786);
__webpack_require__(787);
__webpack_require__(788);
__webpack_require__(769);
__webpack_require__(408);
__webpack_require__(410);
__webpack_require__(411);
__webpack_require__(824);
__webpack_require__(813);
__webpack_require__(814);
__webpack_require__(819);
__webpack_require__(822);
__webpack_require__(823);
__webpack_require__(817);
__webpack_require__(820);
__webpack_require__(818);
__webpack_require__(821);
__webpack_require__(815);
__webpack_require__(816);
__webpack_require__(770);
__webpack_require__(771);
__webpack_require__(772);
__webpack_require__(773);
__webpack_require__(774);
__webpack_require__(777);
__webpack_require__(775);
__webpack_require__(776);
__webpack_require__(778);
__webpack_require__(779);
__webpack_require__(780);
__webpack_require__(781);
__webpack_require__(783);
__webpack_require__(782);
module.exports = __webpack_require__(53);
/***/ },
/* 682 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(825);
__webpack_require__(826);
__webpack_require__(828);
__webpack_require__(827);
__webpack_require__(830);
__webpack_require__(829);
__webpack_require__(831);
__webpack_require__(832);
__webpack_require__(833);
module.exports = __webpack_require__(53).Reflect;
/***/ },
/* 683 */
/***/ function(module, exports, __webpack_require__) {
var forOf = __webpack_require__(111);
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
/***/ },
/* 684 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, isArray = __webpack_require__(243)
, SPECIES = __webpack_require__(13)('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ },
/* 685 */
/***/ function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(684);
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
/***/ },
/* 686 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var anObject = __webpack_require__(6)
, toPrimitive = __webpack_require__(71)
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
/***/ },
/* 687 */
/***/ function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(98)
, gOPS = __webpack_require__(153)
, pIE = __webpack_require__(154);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
/***/ },
/* 688 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(98)
, toIObject = __webpack_require__(41);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ },
/* 689 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(15)
, macrotask = __webpack_require__(405).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = __webpack_require__(52)(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
/***/ },
/* 690 */
/***/ function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__(83)
, gOPS = __webpack_require__(153)
, anObject = __webpack_require__(6)
, Reflect = __webpack_require__(15).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ },
/* 691 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(15)
, core = __webpack_require__(53)
, LIBRARY = __webpack_require__(97)
, wksExt = __webpack_require__(406)
, defineProperty = __webpack_require__(19).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
/***/ },
/* 692 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(110)
, ITERATOR = __webpack_require__(13)('iterator')
, Iterators = __webpack_require__(96);
module.exports = __webpack_require__(53).isIterable = function(it){
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
|| Iterators.hasOwnProperty(classof(O));
};
/***/ },
/* 693 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(2);
$export($export.P, 'Array', {copyWithin: __webpack_require__(384)});
__webpack_require__(109)('copyWithin');
/***/ },
/* 694 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $every = __webpack_require__(43)(4);
$export($export.P + $export.F * !__webpack_require__(40)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 695 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(2);
$export($export.P, 'Array', {fill: __webpack_require__(234)});
__webpack_require__(109)('fill');
/***/ },
/* 696 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $filter = __webpack_require__(43)(2);
$export($export.P + $export.F * !__webpack_require__(40)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 697 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(2)
, $find = __webpack_require__(43)(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(109)(KEY);
/***/ },
/* 698 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(2)
, $find = __webpack_require__(43)(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(109)(KEY);
/***/ },
/* 699 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $forEach = __webpack_require__(43)(0)
, STRICT = __webpack_require__(40)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 700 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ctx = __webpack_require__(54)
, $export = __webpack_require__(2)
, toObject = __webpack_require__(39)
, call = __webpack_require__(392)
, isArrayIter = __webpack_require__(242)
, toLength = __webpack_require__(29)
, createProperty = __webpack_require__(389)
, getIterFn = __webpack_require__(254);
$export($export.S + $export.F * !__webpack_require__(152)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ },
/* 701 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $indexOf = __webpack_require__(235)(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(40)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
/***/ },
/* 702 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__(2);
$export($export.S, 'Array', {isArray: __webpack_require__(243)});
/***/ },
/* 703 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = __webpack_require__(2)
, toIObject = __webpack_require__(41)
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (__webpack_require__(112) != Object || !__webpack_require__(40)(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
/***/ },
/* 704 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, toIObject = __webpack_require__(41)
, toInteger = __webpack_require__(70)
, toLength = __webpack_require__(29)
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(40)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
/***/ },
/* 705 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $map = __webpack_require__(43)(1);
$export($export.P + $export.F * !__webpack_require__(40)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 706 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, createProperty = __webpack_require__(389);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(9)(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
/***/ },
/* 707 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $reduce = __webpack_require__(385);
$export($export.P + $export.F * !__webpack_require__(40)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
/***/ },
/* 708 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $reduce = __webpack_require__(385);
$export($export.P + $export.F * !__webpack_require__(40)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
/***/ },
/* 709 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, html = __webpack_require__(240)
, cof = __webpack_require__(52)
, toIndex = __webpack_require__(84)
, toLength = __webpack_require__(29)
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * __webpack_require__(9)(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
/***/ },
/* 710 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $some = __webpack_require__(43)(3);
$export($export.P + $export.F * !__webpack_require__(40)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 711 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, aFunction = __webpack_require__(51)
, toObject = __webpack_require__(39)
, fails = __webpack_require__(9)
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !__webpack_require__(40)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
/***/ },
/* 712 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(100)('Array');
/***/ },
/* 713 */
/***/ function(module, exports, __webpack_require__) {
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__(2);
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
/***/ },
/* 714 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = __webpack_require__(2)
, fails = __webpack_require__(9)
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
/***/ },
/* 715 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, toObject = __webpack_require__(39)
, toPrimitive = __webpack_require__(71);
$export($export.P + $export.F * __webpack_require__(9)(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
/***/ },
/* 716 */
/***/ function(module, exports, __webpack_require__) {
var TO_PRIMITIVE = __webpack_require__(13)('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))__webpack_require__(37)(proto, TO_PRIMITIVE, __webpack_require__(686));
/***/ },
/* 717 */
/***/ function(module, exports, __webpack_require__) {
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
__webpack_require__(38)(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
/***/ },
/* 718 */
/***/ function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__(2);
$export($export.P, 'Function', {bind: __webpack_require__(386)});
/***/ },
/* 719 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isObject = __webpack_require__(11)
, getPrototypeOf = __webpack_require__(44)
, HAS_INSTANCE = __webpack_require__(13)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(19).f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
/***/ },
/* 720 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(19).f
, createDesc = __webpack_require__(69)
, has = __webpack_require__(28)
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || __webpack_require__(24) && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
/***/ },
/* 721 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
var $export = __webpack_require__(2)
, log1p = __webpack_require__(395)
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
/***/ },
/* 722 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
var $export = __webpack_require__(2)
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
/***/ },
/* 723 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
var $export = __webpack_require__(2)
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
/***/ },
/* 724 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
var $export = __webpack_require__(2)
, sign = __webpack_require__(248);
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
/***/ },
/* 725 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(2);
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
/***/ },
/* 726 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
var $export = __webpack_require__(2)
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
/***/ },
/* 727 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
var $export = __webpack_require__(2)
, $expm1 = __webpack_require__(247);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
/***/ },
/* 728 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var $export = __webpack_require__(2)
, sign = __webpack_require__(248)
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
/***/ },
/* 729 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = __webpack_require__(2)
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
/***/ },
/* 730 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
var $export = __webpack_require__(2)
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * __webpack_require__(9)(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
/***/ },
/* 731 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.21 Math.log10(x)
var $export = __webpack_require__(2);
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
/***/ },
/* 732 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(2);
$export($export.S, 'Math', {log1p: __webpack_require__(395)});
/***/ },
/* 733 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.22 Math.log2(x)
var $export = __webpack_require__(2);
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
/***/ },
/* 734 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(2);
$export($export.S, 'Math', {sign: __webpack_require__(248)});
/***/ },
/* 735 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
var $export = __webpack_require__(2)
, expm1 = __webpack_require__(247)
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * __webpack_require__(9)(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
/***/ },
/* 736 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
var $export = __webpack_require__(2)
, expm1 = __webpack_require__(247)
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
/***/ },
/* 737 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.34 Math.trunc(x)
var $export = __webpack_require__(2);
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
/***/ },
/* 738 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(15)
, has = __webpack_require__(28)
, cof = __webpack_require__(52)
, inheritIfRequired = __webpack_require__(241)
, toPrimitive = __webpack_require__(71)
, fails = __webpack_require__(9)
, gOPN = __webpack_require__(83).f
, gOPD = __webpack_require__(57).f
, dP = __webpack_require__(19).f
, $trim = __webpack_require__(157).trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(__webpack_require__(82)(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = __webpack_require__(24) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
__webpack_require__(38)(global, NUMBER, $Number);
}
/***/ },
/* 739 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(2);
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
/***/ },
/* 740 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(2)
, _isFinite = __webpack_require__(15).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
/***/ },
/* 741 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(2);
$export($export.S, 'Number', {isInteger: __webpack_require__(244)});
/***/ },
/* 742 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(2);
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
/***/ },
/* 743 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(2)
, isInteger = __webpack_require__(244)
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ },
/* 744 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(2);
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
/***/ },
/* 745 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(2);
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
/***/ },
/* 746 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, $parseFloat = __webpack_require__(400);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
/***/ },
/* 747 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, $parseInt = __webpack_require__(401);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
/***/ },
/* 748 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, anInstance = __webpack_require__(81)
, toInteger = __webpack_require__(70)
, aNumberValue = __webpack_require__(383)
, repeat = __webpack_require__(404)
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !__webpack_require__(9)(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
/***/ },
/* 749 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $fails = __webpack_require__(9)
, aNumberValue = __webpack_require__(383)
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
/***/ },
/* 750 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(2);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(396)});
/***/ },
/* 751 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: __webpack_require__(82)});
/***/ },
/* 752 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__webpack_require__(24), 'Object', {defineProperties: __webpack_require__(397)});
/***/ },
/* 753 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(24), 'Object', {defineProperty: __webpack_require__(19).f});
/***/ },
/* 754 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(68).onFreeze;
__webpack_require__(45)('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ },
/* 755 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(41)
, $getOwnPropertyDescriptor = __webpack_require__(57).f;
__webpack_require__(45)('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ },
/* 756 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(45)('getOwnPropertyNames', function(){
return __webpack_require__(398).f;
});
/***/ },
/* 757 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(39)
, $getPrototypeOf = __webpack_require__(44);
__webpack_require__(45)('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
/***/ },
/* 758 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(11);
__webpack_require__(45)('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ },
/* 759 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(11);
__webpack_require__(45)('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ },
/* 760 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(11);
__webpack_require__(45)('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ },
/* 761 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(2);
$export($export.S, 'Object', {is: __webpack_require__(402)});
/***/ },
/* 762 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(39)
, $keys = __webpack_require__(98);
__webpack_require__(45)('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
/***/ },
/* 763 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(68).onFreeze;
__webpack_require__(45)('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ },
/* 764 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(68).onFreeze;
__webpack_require__(45)('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ },
/* 765 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(2);
$export($export.S, 'Object', {setPrototypeOf: __webpack_require__(155).set});
/***/ },
/* 766 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = __webpack_require__(110)
, test = {};
test[__webpack_require__(13)('toStringTag')] = 'z';
if(test + '' != '[object z]'){
__webpack_require__(38)(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
/***/ },
/* 767 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, $parseFloat = __webpack_require__(400);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
/***/ },
/* 768 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, $parseInt = __webpack_require__(401);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
/***/ },
/* 769 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(97)
, global = __webpack_require__(15)
, ctx = __webpack_require__(54)
, classof = __webpack_require__(110)
, $export = __webpack_require__(2)
, isObject = __webpack_require__(11)
, anObject = __webpack_require__(6)
, aFunction = __webpack_require__(51)
, anInstance = __webpack_require__(81)
, forOf = __webpack_require__(111)
, setProto = __webpack_require__(155).set
, speciesConstructor = __webpack_require__(250)
, task = __webpack_require__(405).set
, microtask = __webpack_require__(689)()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[__webpack_require__(13)('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(99)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
__webpack_require__(101)($Promise, PROMISE);
__webpack_require__(100)(PROMISE);
Wrapper = __webpack_require__(53)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(152)(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
/***/ },
/* 770 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = __webpack_require__(2)
, aFunction = __webpack_require__(51)
, anObject = __webpack_require__(6)
, _apply = Function.apply;
$export($export.S, 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(aFunction(target), thisArgument, anObject(argumentsList));
}
});
/***/ },
/* 771 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = __webpack_require__(2)
, create = __webpack_require__(82)
, aFunction = __webpack_require__(51)
, anObject = __webpack_require__(6)
, isObject = __webpack_require__(11)
, bind = __webpack_require__(386);
// MS Edge supports only 2 arguments
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
$export($export.S + $export.F * __webpack_require__(9)(function(){
function F(){}
return !(Reflect.construct(function(){}, [], F) instanceof F);
}), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
switch(args.length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
/***/ },
/* 772 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = __webpack_require__(19)
, $export = __webpack_require__(2)
, anObject = __webpack_require__(6)
, toPrimitive = __webpack_require__(71);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * __webpack_require__(9)(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 773 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = __webpack_require__(2)
, gOPD = __webpack_require__(57).f
, anObject = __webpack_require__(6);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
/***/ },
/* 774 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = __webpack_require__(2)
, anObject = __webpack_require__(6);
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
__webpack_require__(393)(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
/***/ },
/* 775 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = __webpack_require__(57)
, $export = __webpack_require__(2)
, anObject = __webpack_require__(6);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
/***/ },
/* 776 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = __webpack_require__(2)
, getProto = __webpack_require__(44)
, anObject = __webpack_require__(6);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
/***/ },
/* 777 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = __webpack_require__(57)
, getPrototypeOf = __webpack_require__(44)
, has = __webpack_require__(28)
, $export = __webpack_require__(2)
, isObject = __webpack_require__(11)
, anObject = __webpack_require__(6);
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
/***/ },
/* 778 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(2);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
/***/ },
/* 779 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
var $export = __webpack_require__(2)
, anObject = __webpack_require__(6)
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
/***/ },
/* 780 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(2);
$export($export.S, 'Reflect', {ownKeys: __webpack_require__(690)});
/***/ },
/* 781 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
var $export = __webpack_require__(2)
, anObject = __webpack_require__(6)
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 782 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = __webpack_require__(2)
, setProto = __webpack_require__(155);
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 783 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = __webpack_require__(19)
, gOPD = __webpack_require__(57)
, getPrototypeOf = __webpack_require__(44)
, has = __webpack_require__(28)
, $export = __webpack_require__(2)
, createDesc = __webpack_require__(69)
, anObject = __webpack_require__(6)
, isObject = __webpack_require__(11);
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
/***/ },
/* 784 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(15)
, inheritIfRequired = __webpack_require__(241)
, dP = __webpack_require__(19).f
, gOPN = __webpack_require__(83).f
, isRegExp = __webpack_require__(245)
, $flags = __webpack_require__(239)
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(__webpack_require__(24) && (!CORRECT_NEW || __webpack_require__(9)(function(){
re2[__webpack_require__(13)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__(38)(global, 'RegExp', $RegExp);
}
__webpack_require__(100)('RegExp');
/***/ },
/* 785 */
/***/ function(module, exports, __webpack_require__) {
// @@match logic
__webpack_require__(151)('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
/***/ },
/* 786 */
/***/ function(module, exports, __webpack_require__) {
// @@replace logic
__webpack_require__(151)('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
/***/ },
/* 787 */
/***/ function(module, exports, __webpack_require__) {
// @@search logic
__webpack_require__(151)('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
/***/ },
/* 788 */
/***/ function(module, exports, __webpack_require__) {
// @@split logic
__webpack_require__(151)('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = __webpack_require__(245)
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
/***/ },
/* 789 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(409);
var anObject = __webpack_require__(6)
, $flags = __webpack_require__(239)
, DESCRIPTORS = __webpack_require__(24)
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
__webpack_require__(38)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(__webpack_require__(9)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
/***/ },
/* 790 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.2 String.prototype.anchor(name)
__webpack_require__(31)('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
/***/ },
/* 791 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.3 String.prototype.big()
__webpack_require__(31)('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
/***/ },
/* 792 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.4 String.prototype.blink()
__webpack_require__(31)('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
/***/ },
/* 793 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.5 String.prototype.bold()
__webpack_require__(31)('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
/***/ },
/* 794 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $at = __webpack_require__(403)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
/***/ },
/* 795 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = __webpack_require__(2)
, toLength = __webpack_require__(29)
, context = __webpack_require__(251)
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(238)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ },
/* 796 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.6 String.prototype.fixed()
__webpack_require__(31)('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
/***/ },
/* 797 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
__webpack_require__(31)('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
/***/ },
/* 798 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
__webpack_require__(31)('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
/***/ },
/* 799 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, toIndex = __webpack_require__(84)
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ },
/* 800 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = __webpack_require__(2)
, context = __webpack_require__(251)
, INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(238)(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ },
/* 801 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.9 String.prototype.italics()
__webpack_require__(31)('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
/***/ },
/* 802 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $at = __webpack_require__(403)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(246)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
/***/ },
/* 803 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.10 String.prototype.link(url)
__webpack_require__(31)('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
/***/ },
/* 804 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2)
, toIObject = __webpack_require__(41)
, toLength = __webpack_require__(29);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ },
/* 805 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(404)
});
/***/ },
/* 806 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.11 String.prototype.small()
__webpack_require__(31)('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
/***/ },
/* 807 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = __webpack_require__(2)
, toLength = __webpack_require__(29)
, context = __webpack_require__(251)
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(238)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ },
/* 808 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.12 String.prototype.strike()
__webpack_require__(31)('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
/***/ },
/* 809 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.13 String.prototype.sub()
__webpack_require__(31)('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
/***/ },
/* 810 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.14 String.prototype.sup()
__webpack_require__(31)('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
/***/ },
/* 811 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.1.3.25 String.prototype.trim()
__webpack_require__(157)('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
/***/ },
/* 812 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var global = __webpack_require__(15)
, has = __webpack_require__(28)
, DESCRIPTORS = __webpack_require__(24)
, $export = __webpack_require__(2)
, redefine = __webpack_require__(38)
, META = __webpack_require__(68).KEY
, $fails = __webpack_require__(9)
, shared = __webpack_require__(156)
, setToStringTag = __webpack_require__(101)
, uid = __webpack_require__(85)
, wks = __webpack_require__(13)
, wksExt = __webpack_require__(406)
, wksDefine = __webpack_require__(691)
, keyOf = __webpack_require__(688)
, enumKeys = __webpack_require__(687)
, isArray = __webpack_require__(243)
, anObject = __webpack_require__(6)
, toIObject = __webpack_require__(41)
, toPrimitive = __webpack_require__(71)
, createDesc = __webpack_require__(69)
, _create = __webpack_require__(82)
, gOPNExt = __webpack_require__(398)
, $GOPD = __webpack_require__(57)
, $DP = __webpack_require__(19)
, $keys = __webpack_require__(98)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(83).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(154).f = $propertyIsEnumerable;
__webpack_require__(153).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !__webpack_require__(97)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(37)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ },
/* 813 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(2)
, $typed = __webpack_require__(158)
, buffer = __webpack_require__(253)
, anObject = __webpack_require__(6)
, toIndex = __webpack_require__(84)
, toLength = __webpack_require__(29)
, isObject = __webpack_require__(11)
, TYPED_ARRAY = __webpack_require__(13)('typed_array')
, ArrayBuffer = __webpack_require__(15).ArrayBuffer
, speciesConstructor = __webpack_require__(250)
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * __webpack_require__(9)(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
__webpack_require__(100)(ARRAY_BUFFER);
/***/ },
/* 814 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(2);
$export($export.G + $export.W + $export.F * !__webpack_require__(158).ABV, {
DataView: __webpack_require__(253).DataView
});
/***/ },
/* 815 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 816 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 817 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 818 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 819 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 820 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 821 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 822 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 823 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
/***/ },
/* 824 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var weak = __webpack_require__(388);
// 23.4 WeakSet Objects
__webpack_require__(150)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
/***/ },
/* 825 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
/***/ },
/* 826 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
/***/ },
/* 827 */
/***/ function(module, exports, __webpack_require__) {
var Set = __webpack_require__(410)
, from = __webpack_require__(683)
, metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, getPrototypeOf = __webpack_require__(44)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 828 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, getPrototypeOf = __webpack_require__(44)
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 829 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 830 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 831 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, getPrototypeOf = __webpack_require__(44)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 832 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 833 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(56)
, anObject = __webpack_require__(6)
, aFunction = __webpack_require__(51)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
/***/ },
/* 834 */,
/* 835 */,
/* 836 */,
/* 837 */,
/* 838 */,
/* 839 */,
/* 840 */,
/* 841 */,
/* 842 */,
/* 843 */,
/* 844 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {function __assignFn(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
}
function __extendsFn(d, b) {
for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __decorateFn(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __metadataFn(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(k, v);
}
function __paramFn(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __awaiterFn(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator.throw(value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
}
// hook global helpers
(function (__global) {
__global.__assign = (__global && __global.__assign) || Object.assign || __assignFn;
__global.__extends = (__global && __global.__extends) || __extendsFn;
__global.__decorate = (__global && __global.__decorate) || __decorateFn;
__global.__metadata = (__global && __global.__metadata) || __metadataFn;
__global.__param = (__global && __global.__param) || __paramFn;
__global.__awaiter = (__global && __global.__awaiter) || __awaiterFn;
})(typeof window !== "undefined" ? window :
typeof WorkerGlobalScope !== "undefined" ? self :
typeof global !== "undefined" ? global :
Function("return this;")());
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 845 */
/***/ function(module, exports) {
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {
'use strict';
(function () {
var NEWLINE = '\n';
var SEP = ' ------------- ';
var IGNORE_FRAMES = [];
var creationTrace = '__creationTrace__';
var LongStackTrace = (function () {
function LongStackTrace() {
this.error = getStacktrace();
this.timestamp = new Date();
}
return LongStackTrace;
}());
function getStacktraceWithUncaughtError() {
return new Error('STACKTRACE TRACKING');
}
function getStacktraceWithCaughtError() {
try {
throw getStacktraceWithUncaughtError();
}
catch (e) {
return e;
}
}
// Some implementations of exception handling don't create a stack trace if the exception
// isn't thrown, however it's faster not to actually throw the exception.
var error = getStacktraceWithUncaughtError();
var coughtError = getStacktraceWithCaughtError();
var getStacktrace = error.stack
? getStacktraceWithUncaughtError
: (coughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
function getFrames(error) {
return error.stack ? error.stack.split(NEWLINE) : [];
}
function addErrorStack(lines, error) {
var trace = getFrames(error);
for (var i = 0; i < trace.length; i++) {
var frame = trace[i];
// Filter out the Frames which are part of stack capturing.
if (!(i < IGNORE_FRAMES.length && IGNORE_FRAMES[i] === frame)) {
lines.push(trace[i]);
}
}
}
function renderLongStackTrace(frames, stack) {
var longTrace = [stack];
if (frames) {
var timestamp = new Date().getTime();
for (var i = 0; i < frames.length; i++) {
var traceFrames = frames[i];
var lastTime = traceFrames.timestamp;
longTrace.push(SEP + " Elapsed: " + (timestamp - lastTime.getTime()) + " ms; At: " + lastTime + " " + SEP);
addErrorStack(longTrace, traceFrames.error);
timestamp = lastTime.getTime();
}
}
return longTrace.join(NEWLINE);
}
Zone['longStackTraceZoneSpec'] = {
name: 'long-stack-trace',
longStackTraceLimit: 10,
onScheduleTask: function (parentZoneDelegate, currentZone, targetZone, task) {
var currentTask = Zone.currentTask;
var trace = currentTask && currentTask.data && currentTask.data[creationTrace] || [];
trace = [new LongStackTrace()].concat(trace);
if (trace.length > this.longStackTraceLimit) {
trace.length = this.longStackTraceLimit;
}
if (!task.data)
task.data = {};
task.data[creationTrace] = trace;
return parentZoneDelegate.scheduleTask(targetZone, task);
},
onHandleError: function (parentZoneDelegate, currentZone, targetZone, error) {
var parentTask = Zone.currentTask;
if (error instanceof Error && parentTask) {
var descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
if (descriptor) {
var delegateGet_1 = descriptor.get;
var value_1 = descriptor.value;
descriptor = {
get: function () {
return renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], delegateGet_1 ? delegateGet_1.apply(this) : value_1);
}
};
Object.defineProperty(error, 'stack', descriptor);
}
else {
error.stack = renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
}
}
return parentZoneDelegate.handleError(targetZone, error);
}
};
function captureStackTraces(stackTraces, count) {
if (count > 0) {
stackTraces.push(getFrames((new LongStackTrace()).error));
captureStackTraces(stackTraces, count - 1);
}
}
function computeIgnoreFrames() {
var frames = [];
captureStackTraces(frames, 2);
var frames1 = frames[0];
var frames2 = frames[1];
for (var i = 0; i < frames1.length; i++) {
var frame1 = frames1[i];
var frame2 = frames2[i];
if (frame1 === frame2) {
IGNORE_FRAMES.push(frame1);
}
else {
break;
}
}
}
computeIgnoreFrames();
})();
/***/ }
/******/ ]);
/***/ },
/* 846 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {"use strict";
__webpack_require__(1);
var event_target_1 = __webpack_require__(2);
var define_property_1 = __webpack_require__(4);
var register_element_1 = __webpack_require__(5);
var property_descriptor_1 = __webpack_require__(6);
var timers_1 = __webpack_require__(8);
var utils_1 = __webpack_require__(3);
var set = 'set';
var clear = 'clear';
var blockingMethods = ['alert', 'prompt', 'confirm'];
var _global = typeof window == 'undefined' ? global : window;
timers_1.patchTimer(_global, set, clear, 'Timeout');
timers_1.patchTimer(_global, set, clear, 'Interval');
timers_1.patchTimer(_global, set, clear, 'Immediate');
timers_1.patchTimer(_global, 'request', 'cancelMacroTask', 'AnimationFrame');
timers_1.patchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame');
timers_1.patchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
for (var i = 0; i < blockingMethods.length; i++) {
var name = blockingMethods[i];
utils_1.patchMethod(_global, name, function (delegate, symbol, name) {
return function (s, args) {
return Zone.current.run(delegate, _global, args, name);
};
});
}
event_target_1.eventTargetPatch(_global);
property_descriptor_1.propertyDescriptorPatch(_global);
utils_1.patchClass('MutationObserver');
utils_1.patchClass('WebKitMutationObserver');
utils_1.patchClass('FileReader');
define_property_1.propertyPatch();
register_element_1.registerElementPatch(_global);
// Treat XMLHTTPRequest as a macrotask.
patchXHR(_global);
var XHR_TASK = utils_1.zoneSymbol('xhrTask');
function patchXHR(window) {
function findPendingTask(target) {
var pendingTask = target[XHR_TASK];
return pendingTask;
}
function scheduleTask(task) {
var data = task.data;
data.target.addEventListener('readystatechange', function () {
if (data.target.readyState === XMLHttpRequest.DONE) {
if (!data.aborted) {
task.invoke();
}
}
});
var storedTask = data.target[XHR_TASK];
if (!storedTask) {
data.target[XHR_TASK] = task;
}
setNative.apply(data.target, data.args);
return task;
}
function placeholderCallback() {
}
function clearTask(task) {
var data = task.data;
// Note - ideally, we would call data.target.removeEventListener here, but it's too late
// to prevent it from firing. So instead, we store info for the event listener.
data.aborted = true;
return clearNative.apply(data.target, data.args);
}
var setNative = utils_1.patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) {
var zone = Zone.current;
var options = {
target: self,
isPeriodic: false,
delay: null,
args: args,
aborted: false
};
return zone.scheduleMacroTask('XMLHttpRequest.send', placeholderCallback, options, scheduleTask, clearTask);
}; });
var clearNative = utils_1.patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) {
var task = findPendingTask(self);
if (task && typeof task.type == 'string') {
// If the XHR has already completed, do nothing.
if (task.cancelFn == null) {
return;
}
task.zone.cancelTask(task);
}
// Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no task to cancel. Do nothing.
}; });
}
/// GEO_LOCATION
if (_global['navigator'] && _global['navigator'].geolocation) {
utils_1.patchPrototype(_global['navigator'].geolocation, [
'getCurrentPosition',
'watchPosition'
]);
}
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 1 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {;
;
var Zone = (function (global) {
var Zone = (function () {
function Zone(parent, zoneSpec) {
this._properties = null;
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
this._properties = zoneSpec && zoneSpec.properties || {};
this._zoneDelegate = new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
}
Object.defineProperty(Zone, "current", {
get: function () { return _currentZone; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(Zone, "currentTask", {
get: function () { return _currentTask; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(Zone.prototype, "parent", {
get: function () { return this._parent; },
enumerable: true,
configurable: true
});
;
Object.defineProperty(Zone.prototype, "name", {
get: function () { return this._name; },
enumerable: true,
configurable: true
});
;
Zone.prototype.get = function (key) {
var current = this;
while (current) {
if (current._properties.hasOwnProperty(key)) {
return current._properties[key];
}
current = current._parent;
}
};
Zone.prototype.fork = function (zoneSpec) {
if (!zoneSpec)
throw new Error('ZoneSpec required!');
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
var zone = this;
return function () {
return zone.runGuarded(_callback, this, arguments, source);
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
if (applyArgs === void 0) { applyArgs = null; }
if (source === void 0) { source = null; }
var oldZone = _currentZone;
_currentZone = this;
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
}
finally {
_currentZone = oldZone;
}
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
if (applyArgs === void 0) { applyArgs = null; }
if (source === void 0) { source = null; }
var oldZone = _currentZone;
_currentZone = this;
try {
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
}
catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
}
finally {
_currentZone = oldZone;
}
};
Zone.prototype.runTask = function (task, applyThis, applyArgs) {
task.runCount++;
if (task.zone != this)
throw new Error('A task can only be run in the zone which created it! (Creation: ' +
task.zone.name + '; Execution: ' + this.name + ')');
var previousTask = _currentTask;
_currentTask = task;
var oldZone = _currentZone;
_currentZone = this;
try {
if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) {
task.cancelFn = null;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
}
catch (error) {
if (this._zoneDelegate.handleError(this, error)) {
throw error;
}
}
}
finally {
_currentZone = oldZone;
_currentTask = previousTask;
}
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {
return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel));
};
Zone.prototype.cancelTask = function (task) {
var value = this._zoneDelegate.cancelTask(this, task);
task.runCount = -1;
task.cancelFn = null;
return value;
};
Zone.__symbol__ = __symbol__;
return Zone;
}());
;
var ZoneDelegate = (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 };
this.zone = zone;
this._parentDelegate = parentDelegate;
this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS);
this._hasTaskDlgt = zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt);
}
ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {
return this._forkZS
? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec)
: new Zone(targetZone, zoneSpec);
};
ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {
return this._interceptZS
? this._interceptZS.onIntercept(this._interceptDlgt, this.zone, targetZone, callback, source)
: callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
return this._invokeZS
? this._invokeZS.onInvoke(this._invokeDlgt, this.zone, targetZone, callback, applyThis, applyArgs, source)
: callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
return this._handleErrorZS
? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this.zone, targetZone, error)
: true;
};
ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {
try {
if (this._scheduleTaskZS) {
return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this.zone, targetZone, task);
}
else if (task.scheduleFn) {
task.scheduleFn(task);
}
else if (task.type == 'microTask') {
scheduleMicroTask(task);
}
else {
throw new Error('Task is missing scheduleFn.');
}
return task;
}
finally {
if (targetZone == this.zone) {
this._updateTaskCount(task.type, 1);
}
}
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
try {
return this._invokeTaskZS
? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this.zone, targetZone, task, applyThis, applyArgs)
: task.callback.apply(applyThis, applyArgs);
}
finally {
if (targetZone == this.zone && (task.type != 'eventTask') && !(task.data && task.data.isPeriodic)) {
this._updateTaskCount(task.type, -1);
}
}
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
var value;
if (this._cancelTaskZS) {
value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this.zone, targetZone, task);
}
else if (!task.cancelFn) {
throw new Error('Task does not support cancellation, or is already canceled.');
}
else {
value = task.cancelFn(task);
}
if (targetZone == this.zone) {
// this should not be in the finally block, because exceptions assume not canceled.
this._updateTaskCount(task.type, -1);
}
return value;
};
ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {
return this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this.zone, targetZone, isEmpty);
};
ZoneDelegate.prototype._updateTaskCount = function (type, count) {
var counts = this._taskCounts;
var prev = counts[type];
var next = counts[type] = prev + count;
if (next < 0) {
throw new Error('More tasks executed then were scheduled.');
}
if (prev == 0 || next == 0) {
var isEmpty = {
microTask: counts.microTask > 0,
macroTask: counts.macroTask > 0,
eventTask: counts.eventTask > 0,
change: type
};
try {
this.hasTask(this.zone, isEmpty);
}
finally {
if (this._parentDelegate) {
this._parentDelegate._updateTaskCount(type, count);
}
}
}
};
return ZoneDelegate;
}());
var ZoneTask = (function () {
function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) {
this.runCount = 0;
this.type = type;
this.zone = zone;
this.source = source;
this.data = options;
this.scheduleFn = scheduleFn;
this.cancelFn = cancelFn;
this.callback = callback;
var self = this;
this.invoke = function () {
try {
return zone.runTask(self, this, arguments);
}
finally {
drainMicroTaskQueue();
}
};
}
return ZoneTask;
}());
function __symbol__(name) { return '__zone_symbol__' + name; }
;
var symbolSetTimeout = __symbol__('setTimeout');
var symbolPromise = __symbol__('Promise');
var symbolThen = __symbol__('then');
var _currentZone = new Zone(null, null);
var _currentTask = null;
var _microTaskQueue = [];
var _isDrainingMicrotaskQueue = false;
var _uncaughtPromiseErrors = [];
var _drainScheduled = false;
function scheduleQueueDrain() {
if (!_drainScheduled && !_currentTask && _microTaskQueue.length == 0) {
// We are not running in Task, so we need to kickstart the microtask queue.
if (global[symbolPromise]) {
global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
}
}
}
function scheduleMicroTask(task) {
scheduleQueueDrain();
_microTaskQueue.push(task);
}
function consoleError(e) {
var rejection = e && e.rejection;
if (rejection) {
console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection);
}
console.error(e);
}
function drainMicroTaskQueue() {
if (!_isDrainingMicrotaskQueue) {
_isDrainingMicrotaskQueue = true;
while (_microTaskQueue.length) {
var queue = _microTaskQueue;
_microTaskQueue = [];
for (var i = 0; i < queue.length; i++) {
var task = queue[i];
try {
task.zone.runTask(task, null, null);
}
catch (e) {
consoleError(e);
}
}
}
while (_uncaughtPromiseErrors.length) {
var uncaughtPromiseErrors = _uncaughtPromiseErrors;
_uncaughtPromiseErrors = [];
var _loop_1 = function(i) {
var uncaughtPromiseError = uncaughtPromiseErrors[i];
try {
uncaughtPromiseError.zone.runGuarded(function () { throw uncaughtPromiseError; });
}
catch (e) {
consoleError(e);
}
};
for (var i = 0; i < uncaughtPromiseErrors.length; i++) {
_loop_1(i);
}
}
_isDrainingMicrotaskQueue = false;
_drainScheduled = false;
}
}
function isThenable(value) {
return value && value.then;
}
function forwardResolution(value) { return value; }
function forwardRejection(rejection) { return ZoneAwarePromise.reject(rejection); }
var symbolState = __symbol__('state');
var symbolValue = __symbol__('value');
var source = 'Promise.then';
var UNRESOLVED = null;
var RESOLVED = true;
var REJECTED = false;
var REJECTED_NO_CATCH = 0;
function makeResolver(promise, state) {
return function (v) {
resolvePromise(promise, state, v);
// Do not return value or you will break the Promise spec.
};
}
function resolvePromise(promise, state, value) {
if (promise[symbolState] === UNRESOLVED) {
if (value instanceof ZoneAwarePromise && value[symbolState] !== UNRESOLVED) {
clearRejectedNoCatch(value);
resolvePromise(promise, value[symbolState], value[symbolValue]);
}
else if (isThenable(value)) {
value.then(makeResolver(promise, state), makeResolver(promise, false));
}
else {
promise[symbolState] = state;
var queue = promise[symbolValue];
promise[symbolValue] = value;
for (var i = 0; i < queue.length;) {
scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
}
if (queue.length == 0 && state == REJECTED) {
promise[symbolState] = REJECTED_NO_CATCH;
try {
throw new Error("Uncaught (in promise): " + value);
}
catch (e) {
var error = e;
error.rejection = value;
error.promise = promise;
error.zone = Zone.current;
error.task = Zone.currentTask;
_uncaughtPromiseErrors.push(error);
scheduleQueueDrain();
}
}
}
}
// Resolving an already resolved promise is a noop.
return promise;
}
function clearRejectedNoCatch(promise) {
if (promise[symbolState] === REJECTED_NO_CATCH) {
promise[symbolState] = REJECTED;
for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {
if (promise === _uncaughtPromiseErrors[i].promise) {
_uncaughtPromiseErrors.splice(i, 1);
break;
}
}
}
}
function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
clearRejectedNoCatch(promise);
var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection;
zone.scheduleMicroTask(source, function () {
try {
resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]]));
}
catch (error) {
resolvePromise(chainPromise, false, error);
}
});
}
var ZoneAwarePromise = (function () {
function ZoneAwarePromise(executor) {
var promise = this;
promise[symbolState] = UNRESOLVED;
promise[symbolValue] = []; // queue;
try {
executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
}
catch (e) {
resolvePromise(promise, false, e);
}
}
ZoneAwarePromise.resolve = function (value) {
return resolvePromise(new this(null), RESOLVED, value);
};
ZoneAwarePromise.reject = function (error) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
var resolve;
var reject;
var promise = new this(function (res, rej) { resolve = res; reject = rej; });
function onResolve(value) { promise && (promise = null || resolve(value)); }
function onReject(error) { promise && (promise = null || reject(error)); }
for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
var value = values_1[_i];
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then(onResolve, onReject);
}
return promise;
};
ZoneAwarePromise.all = function (values) {
var resolve;
var reject;
var promise = new this(function (res, rej) { resolve = res; reject = rej; });
var count = 0;
var resolvedValues = [];
function onReject(error) { promise && reject(error); promise = null; }
for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
var value = values_2[_i];
if (!isThenable(value)) {
value = this.resolve(value);
}
value.then((function (index) { return function (value) {
resolvedValues[index] = value;
count--;
if (promise && !count) {
resolve(resolvedValues);
}
promise == null;
}; })(count), onReject);
count++;
}
if (!count)
resolve(resolvedValues);
return promise;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
var chainPromise = new ZoneAwarePromise(null);
var zone = Zone.current;
if (this[symbolState] == UNRESOLVED) {
this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
}
else {
scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
}
return chainPromise;
};
ZoneAwarePromise.prototype.catch = function (onRejected) {
return this.then(null, onRejected);
};
return ZoneAwarePromise;
}());
var NativePromise = global[__symbol__('Promise')] = global.Promise;
global.Promise = ZoneAwarePromise;
if (NativePromise) {
var NativePromiseProtototype = NativePromise.prototype;
var NativePromiseThen_1 = NativePromiseProtototype[__symbol__('then')]
= NativePromiseProtototype.then;
NativePromiseProtototype.then = function (onResolve, onReject) {
var nativePromise = this;
return new ZoneAwarePromise(function (resolve, reject) {
NativePromiseThen_1.call(nativePromise, resolve, reject);
}).then(onResolve, onReject);
};
}
return global.Zone = Zone;
})(typeof window === 'undefined' ? global : window);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex'.split(',');
var EVENT_TARGET = 'EventTarget';
function eventTargetPatch(_global) {
var apis = [];
var isWtf = _global['wtf'];
if (isWtf) {
// Workaround for: https://github.com/google/tracing-framework/issues/555
apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);
}
else if (_global[EVENT_TARGET]) {
apis.push(EVENT_TARGET);
}
else {
// Note: EventTarget is not available in all browsers,
// if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
apis = NO_EVENT_TARGET;
}
for (var i = 0; i < apis.length; i++) {
var type = _global[apis[i]];
utils_1.patchEventTargetMethods(type && type.prototype);
}
}
exports.eventTargetPatch = eventTargetPatch;
/***/ },
/* 3 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* Suppress closure compiler errors about unknown 'process' variable
* @fileoverview
* @suppress {undefinedVars}
*/
"use strict";
exports.zoneSymbol = Zone['__symbol__'];
var _global = typeof window == 'undefined' ? global : window;
function bindArguments(args, source) {
for (var i = args.length - 1; i >= 0; i--) {
if (typeof args[i] === 'function') {
args[i] = Zone.current.wrap(args[i], source + '_' + i);
}
}
return args;
}
exports.bindArguments = bindArguments;
;
function patchPrototype(prototype, fnNames) {
var source = prototype.constructor['name'];
var _loop_1 = function(i) {
var name_1 = fnNames[i];
var delegate = prototype[name_1];
if (delegate) {
prototype[name_1] = (function (delegate) {
return function () {
return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));
};
})(delegate);
}
};
for (var i = 0; i < fnNames.length; i++) {
_loop_1(i);
}
}
exports.patchPrototype = patchPrototype;
;
exports.isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
exports.isNode = (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]');
exports.isBrowser = !exports.isNode && !exports.isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']);
function patchProperty(obj, prop) {
var desc = Object.getOwnPropertyDescriptor(obj, prop) || {
enumerable: true,
configurable: true
};
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
// TypeError: property descriptors must not specify a value or be writable when a
// getter or setter has been specified
delete desc.writable;
delete desc.value;
// substr(2) cuz 'onclick' -> 'click', etc
var eventName = prop.substr(2);
var _prop = '_' + prop;
desc.set = function (fn) {
if (this[_prop]) {
this.removeEventListener(eventName, this[_prop]);
}
if (typeof fn === 'function') {
var wrapFn = function (event) {
var result;
result = fn.apply(this, arguments);
if (result != undefined && !result)
event.preventDefault();
};
this[_prop] = wrapFn;
this.addEventListener(eventName, wrapFn, false);
}
else {
this[_prop] = null;
}
};
desc.get = function () {
return this[_prop];
};
Object.defineProperty(obj, prop, desc);
}
exports.patchProperty = patchProperty;
;
function patchOnProperties(obj, properties) {
var onProperties = [];
for (var prop in obj) {
if (prop.substr(0, 2) == 'on') {
onProperties.push(prop);
}
}
for (var j = 0; j < onProperties.length; j++) {
patchProperty(obj, onProperties[j]);
}
if (properties) {
for (var i = 0; i < properties.length; i++) {
patchProperty(obj, 'on' + properties[i]);
}
}
}
exports.patchOnProperties = patchOnProperties;
;
var EVENT_TASKS = exports.zoneSymbol('eventTasks');
var ADD_EVENT_LISTENER = 'addEventListener';
var REMOVE_EVENT_LISTENER = 'removeEventListener';
var SYMBOL_ADD_EVENT_LISTENER = exports.zoneSymbol(ADD_EVENT_LISTENER);
var SYMBOL_REMOVE_EVENT_LISTENER = exports.zoneSymbol(REMOVE_EVENT_LISTENER);
function findExistingRegisteredTask(target, handler, name, capture, remove) {
var eventTasks = target[EVENT_TASKS];
if (eventTasks) {
for (var i = 0; i < eventTasks.length; i++) {
var eventTask = eventTasks[i];
var data = eventTask.data;
if (data.handler === handler
&& data.useCapturing === capture
&& data.eventName === name) {
if (remove) {
eventTasks.splice(i, 1);
}
return eventTask;
}
}
}
return null;
}
function attachRegisteredEvent(target, eventTask) {
var eventTasks = target[EVENT_TASKS];
if (!eventTasks) {
eventTasks = target[EVENT_TASKS] = [];
}
eventTasks.push(eventTask);
}
function scheduleEventListener(eventTask) {
var meta = eventTask.data;
attachRegisteredEvent(meta.target, eventTask);
return meta.target[SYMBOL_ADD_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing);
}
function cancelEventListener(eventTask) {
var meta = eventTask.data;
findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true);
meta.target[SYMBOL_REMOVE_EVENT_LISTENER](meta.eventName, eventTask.invoke, meta.useCapturing);
}
function zoneAwareAddEventListener(self, args) {
var eventName = args[0];
var handler = args[1];
var useCapturing = args[2] || false;
// - Inside a Web Worker, `this` is undefined, the context is `global`
// - When `addEventListener` is called on the global context in strict mode, `this` is undefined
// see https://github.com/angular/zone.js/issues/190
var target = self || _global;
var delegate = null;
if (typeof handler == 'function') {
delegate = handler;
}
else if (handler && handler.handleEvent) {
delegate = function (event) { return handler.handleEvent(event); };
}
var validZoneHandler = false;
try {
// In cross site contexts (such as WebDriver frameworks like Selenium),
// accessing the handler object here will cause an exception to be thrown which
// will fail tests prematurely.
validZoneHandler = handler && handler.toString() === "[object FunctionWrapper]";
}
catch (e) {
// Returning nothing here is fine, because objects in a cross-site context are unusable
return;
}
// Ignore special listeners of IE11 & Edge dev tools, see https://github.com/angular/zone.js/issues/150
if (!delegate || validZoneHandler) {
return target[SYMBOL_ADD_EVENT_LISTENER](eventName, handler, useCapturing);
}
var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, false);
if (eventTask) {
// we already registered, so this will have noop.
return target[SYMBOL_ADD_EVENT_LISTENER](eventName, eventTask.invoke, useCapturing);
}
var zone = Zone.current;
var source = target.constructor['name'] + '.addEventListener:' + eventName;
var data = {
target: target,
eventName: eventName,
name: eventName,
useCapturing: useCapturing,
handler: handler
};
zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener);
}
function zoneAwareRemoveEventListener(self, args) {
var eventName = args[0];
var handler = args[1];
var useCapturing = args[2] || false;
// - Inside a Web Worker, `this` is undefined, the context is `global`
// - When `addEventListener` is called on the global context in strict mode, `this` is undefined
// see https://github.com/angular/zone.js/issues/190
var target = self || _global;
var eventTask = findExistingRegisteredTask(target, handler, eventName, useCapturing, true);
if (eventTask) {
eventTask.zone.cancelTask(eventTask);
}
else {
target[SYMBOL_REMOVE_EVENT_LISTENER](eventName, handler, useCapturing);
}
}
function patchEventTargetMethods(obj) {
if (obj && obj.addEventListener) {
patchMethod(obj, ADD_EVENT_LISTENER, function () { return zoneAwareAddEventListener; });
patchMethod(obj, REMOVE_EVENT_LISTENER, function () { return zoneAwareRemoveEventListener; });
return true;
}
else {
return false;
}
}
exports.patchEventTargetMethods = patchEventTargetMethods;
;
var originalInstanceKey = exports.zoneSymbol('originalInstance');
// wrap some native API on `window`
function patchClass(className) {
var OriginalClass = _global[className];
if (!OriginalClass)
return;
_global[className] = function () {
var a = bindArguments(arguments, className);
switch (a.length) {
case 0:
this[originalInstanceKey] = new OriginalClass();
break;
case 1:
this[originalInstanceKey] = new OriginalClass(a[0]);
break;
case 2:
this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
break;
case 3:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
break;
case 4:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
break;
default: throw new Error('Arg list too long.');
}
};
var instance = new OriginalClass(function () { });
var prop;
for (prop in instance) {
(function (prop) {
if (typeof instance[prop] === 'function') {
_global[className].prototype[prop] = function () {
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
};
}
else {
Object.defineProperty(_global[className].prototype, prop, {
set: function (fn) {
if (typeof fn === 'function') {
this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop);
}
else {
this[originalInstanceKey][prop] = fn;
}
},
get: function () {
return this[originalInstanceKey][prop];
}
});
}
}(prop));
}
for (prop in OriginalClass) {
if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
_global[className][prop] = OriginalClass[prop];
}
}
}
exports.patchClass = patchClass;
;
function createNamedFn(name, delegate) {
try {
return (Function('f', "return function " + name + "(){return f(this, arguments)}"))(delegate);
}
catch (e) {
// if we fail, we must be CSP, just return delegate.
return function () {
return delegate(this, arguments);
};
}
}
exports.createNamedFn = createNamedFn;
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
proto = Object.getPrototypeOf(proto);
}
if (!proto && target[name]) {
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
proto = target;
}
var delegateName = exports.zoneSymbol(name);
var delegate;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name));
}
return delegate;
}
exports.patchMethod = patchMethod;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
/*
* This is necessary for Chrome and Chrome mobile, to enable
* things like redefining `createdCallback` on an element.
*/
var _defineProperty = Object.defineProperty;
var _getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var _create = Object.create;
var unconfigurablesKey = utils_1.zoneSymbol('unconfigurables');
function propertyPatch() {
Object.defineProperty = function (obj, prop, desc) {
if (isUnconfigurable(obj, prop)) {
throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj);
}
if (prop !== 'prototype') {
desc = rewriteDescriptor(obj, prop, desc);
}
return _defineProperty(obj, prop, desc);
};
Object.defineProperties = function (obj, props) {
Object.keys(props).forEach(function (prop) {
Object.defineProperty(obj, prop, props[prop]);
});
return obj;
};
Object.create = function (obj, proto) {
if (typeof proto === 'object') {
Object.keys(proto).forEach(function (prop) {
proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);
});
}
return _create(obj, proto);
};
Object.getOwnPropertyDescriptor = function (obj, prop) {
var desc = _getOwnPropertyDescriptor(obj, prop);
if (isUnconfigurable(obj, prop)) {
desc.configurable = false;
}
return desc;
};
}
exports.propertyPatch = propertyPatch;
;
function _redefineProperty(obj, prop, desc) {
desc = rewriteDescriptor(obj, prop, desc);
return _defineProperty(obj, prop, desc);
}
exports._redefineProperty = _redefineProperty;
;
function isUnconfigurable(obj, prop) {
return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];
}
function rewriteDescriptor(obj, prop, desc) {
desc.configurable = true;
if (!desc.configurable) {
if (!obj[unconfigurablesKey]) {
_defineProperty(obj, unconfigurablesKey, { writable: true, value: {} });
}
obj[unconfigurablesKey][prop] = true;
}
return desc;
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var define_property_1 = __webpack_require__(4);
var utils_1 = __webpack_require__(3);
function registerElementPatch(_global) {
if (!utils_1.isBrowser || !('registerElement' in _global.document)) {
return;
}
var _registerElement = document.registerElement;
var callbacks = [
'createdCallback',
'attachedCallback',
'detachedCallback',
'attributeChangedCallback'
];
document.registerElement = function (name, opts) {
if (opts && opts.prototype) {
callbacks.forEach(function (callback) {
var source = 'Document.registerElement::' + callback;
if (opts.prototype.hasOwnProperty(callback)) {
var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback);
if (descriptor && descriptor.value) {
descriptor.value = Zone.current.wrap(descriptor.value, source);
define_property_1._redefineProperty(opts.prototype, callback, descriptor);
}
else {
opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);
}
}
else if (opts.prototype[callback]) {
opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);
}
});
}
return _registerElement.apply(document, [name, opts]);
};
}
exports.registerElementPatch = registerElementPatch;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var webSocketPatch = __webpack_require__(7);
var utils_1 = __webpack_require__(3);
var eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'.split(' ');
function propertyDescriptorPatch(_global) {
if (utils_1.isNode) {
return;
}
var supportsWebSocket = typeof WebSocket !== 'undefined';
if (canPatchViaPropertyDescriptor()) {
// for browsers that we can patch the descriptor: Chrome & Firefox
if (utils_1.isBrowser) {
utils_1.patchOnProperties(HTMLElement.prototype, eventNames);
}
utils_1.patchOnProperties(XMLHttpRequest.prototype, null);
if (typeof IDBIndex !== 'undefined') {
utils_1.patchOnProperties(IDBIndex.prototype, null);
utils_1.patchOnProperties(IDBRequest.prototype, null);
utils_1.patchOnProperties(IDBOpenDBRequest.prototype, null);
utils_1.patchOnProperties(IDBDatabase.prototype, null);
utils_1.patchOnProperties(IDBTransaction.prototype, null);
utils_1.patchOnProperties(IDBCursor.prototype, null);
}
if (supportsWebSocket) {
utils_1.patchOnProperties(WebSocket.prototype, null);
}
}
else {
// Safari, Android browsers (Jelly Bean)
patchViaCapturingAllTheEvents();
utils_1.patchClass('XMLHttpRequest');
if (supportsWebSocket) {
webSocketPatch.apply(_global);
}
}
}
exports.propertyDescriptorPatch = propertyDescriptorPatch;
function canPatchViaPropertyDescriptor() {
if (utils_1.isBrowser && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick')
&& typeof Element !== 'undefined') {
// WebKit https://bugs.webkit.org/show_bug.cgi?id=134364
// IDL interface attributes are not configurable
var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick');
if (desc && !desc.configurable)
return false;
}
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
get: function () {
return true;
}
});
var req = new XMLHttpRequest();
var result = !!req.onreadystatechange;
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {});
return result;
}
;
var unboundKey = utils_1.zoneSymbol('unbound');
// Whenever any eventListener fires, we check the eventListener target and all parents
// for `onwhatever` properties and replace them with zone-bound functions
// - Chrome (for now)
function patchViaCapturingAllTheEvents() {
var _loop_1 = function(i) {
var property = eventNames[i];
var onproperty = 'on' + property;
document.addEventListener(property, function (event) {
var elt = event.target, bound, source;
if (elt) {
source = elt.constructor['name'] + '.' + onproperty;
}
else {
source = 'unknown.' + onproperty;
}
while (elt) {
if (elt[onproperty] && !elt[onproperty][unboundKey]) {
bound = Zone.current.wrap(elt[onproperty], source);
bound[unboundKey] = elt[onproperty];
elt[onproperty] = bound;
}
elt = elt.parentElement;
}
}, true);
};
for (var i = 0; i < eventNames.length; i++) {
_loop_1(i);
}
;
}
;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
// we have to patch the instance since the proto is non-configurable
function apply(_global) {
var WS = _global.WebSocket;
// On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
// On older Chrome, no need since EventTarget was already patched
if (!_global.EventTarget) {
utils_1.patchEventTargetMethods(WS.prototype);
}
_global.WebSocket = function (a, b) {
var socket = arguments.length > 1 ? new WS(a, b) : new WS(a);
var proxySocket;
// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage');
if (onmessageDesc && onmessageDesc.configurable === false) {
proxySocket = Object.create(socket);
['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) {
proxySocket[propName] = function () {
return socket[propName].apply(socket, arguments);
};
});
}
else {
// we can patch the real socket
proxySocket = socket;
}
utils_1.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']);
return proxySocket;
};
for (var prop in WS) {
_global.WebSocket[prop] = WS[prop];
}
}
exports.apply = apply;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var utils_1 = __webpack_require__(3);
function patchTimer(window, setName, cancelName, nameSuffix) {
var setNative = null;
var clearNative = null;
setName += nameSuffix;
cancelName += nameSuffix;
function scheduleTask(task) {
var data = task.data;
data.args[0] = task.invoke;
data.handleId = setNative.apply(window, data.args);
return task;
}
function clearTask(task) {
return clearNative(task.data.handleId);
}
setNative = utils_1.patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === 'function') {
var zone = Zone.current;
var options = {
handleId: null,
isPeriodic: nameSuffix === 'Interval',
delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,
args: args
};
return zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask);
}
else {
// cause an error by calling it directly.
return delegate.apply(window, args);
}
}; });
clearNative = utils_1.patchMethod(window, cancelName, function (delegate) { return function (self, args) {
var task = args[0];
if (task && typeof task.type === 'string') {
if (task.cancelFn && task.data.isPeriodic || task.runCount === 0) {
// Do not cancel already canceled functions
task.zone.cancelTask(task);
}
}
else {
// cause an error by calling it directly.
delegate.apply(window, args);
}
}; });
}
exports.patchTimer = patchTimer;
/***/ }
/******/ ]);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(259)))
/***/ }
/******/ ]);
//# sourceMappingURL=polyfills.map | nawalgupta/angular2-shop | dist/polyfills.bundle.js | JavaScript | mit | 303,126 |
const {
QUERY_PROFILE_PROJECT,
QUERY_PROFILE_ENVIRONMENT,
QUERY_PROFILE_SETTINGS,
MUTATION_LOG,
MUTATION_SESSION,
} = require('constants/permissions/values');
const {
PRIVATE,
} = require('constants/permissions/entries');
const app = require('./app');
const user = require('./user');
const { APP, USER } = require('constants/profiles/types');
const values = [
{
value: QUERY_PROFILE_PROJECT,
entries: [PRIVATE]
},
{
value: QUERY_PROFILE_ENVIRONMENT,
entries: [PRIVATE]
},
{
value: QUERY_PROFILE_SETTINGS,
entries: [PRIVATE]
},
{
value: MUTATION_LOG,
entries: [PRIVATE]
},
{
value: MUTATION_SESSION,
entries: [PRIVATE]
},
];
exports.values = values;
exports[APP] = [...values, ...app];
exports[USER] = [...values, ...user]; | Apozhidaev/get-sso | web/permissions/index.js | JavaScript | mit | 870 |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
goog.provide('jspb.Map');
goog.require('goog.asserts');
goog.forwardDeclare('jspb.BinaryReader');
goog.forwardDeclare('jspb.BinaryWriter');
/**
* Constructs a new Map. A Map is a container that is used to implement map
* fields on message objects. It closely follows the ES6 Map API; however,
* it is distinct because we do not want to depend on external polyfills or
* on ES6 itself.
*
* This constructor should only be called from generated message code. It is not
* intended for general use by library consumers.
*
* @template K, V
*
* @param {!Array<!Array<!Object>>} arr
*
* @param {?function(new:V)|function(new:V,?)=} opt_valueCtor
* The constructor for type V, if type V is a message type.
*
* @constructor
* @struct
*/
jspb.Map = function(arr, opt_valueCtor) {
/** @const @private */
this.arr_ = arr;
/** @const @private */
this.valueCtor_ = opt_valueCtor;
/** @type {!Object<string, !jspb.Map.Entry_<K,V>>} @private */
this.map_ = {};
/**
* Is `this.arr_ updated with respect to `this.map_`?
* @type {boolean}
*/
this.arrClean = true;
if (this.arr_.length > 0) {
this.loadFromArray_();
}
};
/**
* Load initial content from underlying array.
* @private
*/
jspb.Map.prototype.loadFromArray_ = function() {
for (var i = 0; i < this.arr_.length; i++) {
var record = this.arr_[i];
var key = record[0];
var value = record[1];
this.map_[key.toString()] = new jspb.Map.Entry_(key, value);
}
this.arrClean = true;
};
/**
* Synchronize content to underlying array, if needed, and return it.
* @return {!Array<!Array<!Object>>}
*/
jspb.Map.prototype.toArray = function() {
if (this.arrClean) {
if (this.valueCtor_) {
// We need to recursively sync maps in submessages to their arrays.
var m = this.map_;
for (var p in m) {
if (Object.prototype.hasOwnProperty.call(m, p)) {
m[p].valueWrapper.toArray();
}
}
}
} else {
// Delete all elements.
this.arr_.length = 0;
var strKeys = this.stringKeys_();
// Output keys in deterministic (sorted) order.
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
var valueWrapper = /** @type {!Object} */ (entry.valueWrapper);
if (valueWrapper) {
valueWrapper.toArray();
}
this.arr_.push([entry.key, entry.value]);
}
this.arrClean = true;
}
return this.arr_;
};
/**
* Helper: return an iterator over an array.
* @template T
* @param {!Array<T>} arr the array
* @return {!Iterator<T>} an iterator
* @private
*/
jspb.Map.arrayIterator_ = function(arr) {
var idx = 0;
return /** @type {!Iterator} */ ({
next: function() {
if (idx < arr.length) {
return { done: false, value: arr[idx++] };
} else {
return { done: true };
}
}
});
};
/**
* Returns the map's length (number of key/value pairs).
* @return {number}
*/
jspb.Map.prototype.getLength = function() {
return this.stringKeys_().length;
};
/**
* Clears the map.
*/
jspb.Map.prototype.clear = function() {
this.map_ = {};
this.arrClean = false;
};
/**
* Deletes a particular key from the map.
* N.B.: differs in name from ES6 Map's `delete` because IE8 does not support
* reserved words as property names.
* @this {jspb.Map}
* @param {K} key
* @return {boolean} Whether any entry with this key was deleted.
*/
jspb.Map.prototype.del = function(key) {
var keyValue = key.toString();
var hadKey = this.map_.hasOwnProperty(keyValue);
delete this.map_[keyValue];
this.arrClean = false;
return hadKey;
};
/**
* Returns an array of [key, value] pairs in the map.
*
* This is redundant compared to the plain entries() method, but we provide this
* to help out Angular 1.x users. Still evaluating whether this is the best
* option.
*
* @return {!Array<K|V>}
*/
jspb.Map.prototype.getEntryList = function() {
var entries = [];
var strKeys = this.stringKeys_();
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
entries.push([entry.key, entry.value]);
}
return entries;
};
/**
* Returns an iterator over [key, value] pairs in the map.
* Closure compiler sadly doesn't support tuples, ie. Iterator<[K,V]>.
* @return {!Iterator<!Array<K|V>>}
* The iterator
*/
jspb.Map.prototype.entries = function() {
var entries = [];
var strKeys = this.stringKeys_();
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
entries.push([entry.key, this.wrapEntry_(entry)]);
}
return jspb.Map.arrayIterator_(entries);
};
/**
* Returns an iterator over keys in the map.
* @return {!Iterator<K>} The iterator
*/
jspb.Map.prototype.keys = function() {
var keys = [];
var strKeys = this.stringKeys_();
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
keys.push(entry.key);
}
return jspb.Map.arrayIterator_(keys);
};
/**
* Returns an iterator over values in the map.
* @return {!Iterator<V>} The iterator
*/
jspb.Map.prototype.values = function() {
var values = [];
var strKeys = this.stringKeys_();
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
values.push(this.wrapEntry_(entry));
}
return jspb.Map.arrayIterator_(values);
};
/**
* Iterates over entries in the map, calling a function on each.
* @template T
* @param {function(this:T, V, K, ?jspb.Map<K, V>)} cb
* @param {T=} opt_thisArg
*/
jspb.Map.prototype.forEach = function(cb, opt_thisArg) {
var strKeys = this.stringKeys_();
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
cb.call(opt_thisArg, this.wrapEntry_(entry), entry.key, this);
}
};
/**
* Sets a key in the map to the given value.
* @param {K} key The key
* @param {V} value The value
* @return {!jspb.Map<K,V>}
*/
jspb.Map.prototype.set = function(key, value) {
var entry = new jspb.Map.Entry_(key);
if (this.valueCtor_) {
entry.valueWrapper = value;
// .toArray() on a message returns a reference to the underlying array
// rather than a copy.
entry.value = value.toArray();
} else {
entry.value = value;
}
this.map_[key.toString()] = entry;
this.arrClean = false;
return this;
};
/**
* Helper: lazily construct a wrapper around an entry, if needed, and return the
* user-visible type.
* @param {!jspb.Map.Entry_<K,V>} entry
* @return {V}
* @private
*/
jspb.Map.prototype.wrapEntry_ = function(entry) {
if (this.valueCtor_) {
if (!entry.valueWrapper) {
entry.valueWrapper = new this.valueCtor_(entry.value);
}
return /** @type {V} */ (entry.valueWrapper);
} else {
return entry.value;
}
};
/**
* Gets the value corresponding to a key in the map.
* @param {K} key
* @return {V|undefined} The value, or `undefined` if key not present
*/
jspb.Map.prototype.get = function(key) {
var keyValue = key.toString();
var entry = this.map_[keyValue];
if (entry) {
return this.wrapEntry_(entry);
} else {
return undefined;
}
};
/**
* Determines whether the given key is present in the map.
* @param {K} key
* @return {boolean} `true` if the key is present
*/
jspb.Map.prototype.has = function(key) {
var keyValue = key.toString();
return (keyValue in this.map_);
};
/**
* Write this Map field in wire format to a BinaryWriter, using the given field
* number.
* @param {number} fieldNumber
* @param {!jspb.BinaryWriter} writer
* @param {function(this:jspb.BinaryWriter,number,K)=} keyWriterFn
* The method on BinaryWriter that writes type K to the stream.
* @param {function(this:jspb.BinaryWriter,number,V)|
* function(this:jspb.BinaryReader,V,?)=} valueWriterFn
* The method on BinaryWriter that writes type V to the stream. May be
* writeMessage, in which case the second callback arg form is used.
* @param {?function(V,!jspb.BinaryWriter)=} opt_valueWriterCallback
* The BinaryWriter serialization callback for type V, if V is a message
* type.
*/
jspb.Map.prototype.serializeBinary = function(
fieldNumber, writer, keyWriterFn, valueWriterFn, opt_valueWriterCallback) {
var strKeys = this.stringKeys_();
strKeys.sort();
for (var i = 0; i < strKeys.length; i++) {
var entry = this.map_[strKeys[i]];
writer.beginSubMessage(fieldNumber);
keyWriterFn.call(writer, 1, entry.key);
if (this.valueCtor_) {
valueWriterFn.call(writer, 2, this.wrapEntry_(entry),
opt_valueWriterCallback);
} else {
valueWriterFn.call(writer, 2, entry.value);
}
writer.endSubMessage();
}
};
/**
* Read one key/value message from the given BinaryReader. Compatible as the
* `reader` callback parameter to jspb.BinaryReader.readMessage, to be called
* when a key/value pair submessage is encountered.
* @param {!jspb.Map} map
* @param {!jspb.BinaryReader} reader
* @param {function(this:jspb.BinaryReader):K=} keyReaderFn
* The method on BinaryReader that reads type K from the stream.
*
* @param {function(this:jspb.BinaryReader):V|
* function(this:jspb.BinaryReader,V,
* function(V,!jspb.BinaryReader))=} valueReaderFn
* The method on BinaryReader that reads type V from the stream. May be
* readMessage, in which case the second callback arg form is used.
*
* @param {?function(V,!jspb.BinaryReader)=} opt_valueReaderCallback
* The BinaryReader parsing callback for type V, if V is a message type.
*
*/
jspb.Map.deserializeBinary = function(map, reader, keyReaderFn, valueReaderFn,
opt_valueReaderCallback) {
var key = undefined;
var value = undefined;
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
if (field == 1) {
// Key.
key = keyReaderFn.call(reader);
} else if (field == 2) {
// Value.
if (map.valueCtor_) {
value = new map.valueCtor_();
valueReaderFn.call(reader, value, opt_valueReaderCallback);
} else {
value = valueReaderFn.call(reader);
}
}
}
goog.asserts.assert(key != undefined);
goog.asserts.assert(value != undefined);
map.set(key, value);
};
/**
* Helper: compute the list of all stringified keys in the underlying Object
* map.
* @return {!Array<string>}
* @private
*/
jspb.Map.prototype.stringKeys_ = function() {
var m = this.map_;
var ret = [];
for (var p in m) {
if (Object.prototype.hasOwnProperty.call(m, p)) {
ret.push(p);
}
}
return ret;
};
/**
* @param {!K} key The entry's key.
* @param {V=} opt_value The entry's value wrapper.
* @constructor
* @struct
* @template K, V
* @private
*/
jspb.Map.Entry_ = function(key, opt_value) {
/** @const {K} */
this.key = key;
// The JSPB-serializable value. For primitive types this will be of type V.
// For message types it will be an array.
/** @type {V} */
this.value = opt_value;
// Only used for submessage values.
/** @type {V} */
this.valueWrapper = undefined;
};
| nicecapj/crossplatfromMmorpgServer | ThirdParty/protobuf/js/map.js | JavaScript | mit | 12,904 |
(function() {
'use strict';
angular.module('facetApp')
.directive('kblink', function() {
return {
restrict: 'EC',
scope: { href: '@' },
transclude: true,
controller: ['$scope', 'popoverService', function($scope, popoverService){
if (!$scope.href) return;
$scope.image = false;
$scope.lifespan = '';
popoverService.getHrefPopover($scope.href).then(function(data) {
if (data.length) data = data[0];
$scope.label = data.label;
$scope.link = '#!/henkilo/'+ (data.id).replace(/^.+?(p[0-9_]+)$/, '$1');
// check if lifespan contains any numbers
if ((new RegExp(/\d/)).test(data.lifespan)) {
// remove leading zeros (0800-0900) -> (800-900)
data.lifespan = data.lifespan.replace(/(\D)0/g, "$1");
$scope.lifespan = data.lifespan;
}
if (data.hasOwnProperty('image')) $scope.image = data.image;
});
}],
template: '<a uib-popover-template="\'views/tooltips/personTooltipTemplate.html\'" popover-trigger="\'mouseenter\'" ng-href="{{ link }}" ng-transclude></a>'
}});
})(); | SemanticComputing/nbf | src/scripts/common/directives/kblink.directive.js | JavaScript | mit | 1,247 |
/* jshint node: true */
(function () {
"use strict";
var APP;
var utils = require("./utils");
var fs = require("fs");
var path = require("path");
var wrench = require("wrench");
var colors = require("colors");
var supervisor = require("supervisor");
function server(settingsFile, dir, port, interval) {
utils.loadSettings(settingsFile, function (settings) {
var i;
dir = dir || path.join(path.dirname(settings.file), settings.source_dir);
dir = dir.split(",");
port = port || 8000;
var reload = function (e, f) {
restartServer(settings, port);
};
for (i = 0; i < dir.length; i++) {
fs.watch(dir[i], reload);
}
restartServer(settings, port);
});
}
function newProject(folder) {
utils.fsCopy(path.join(path.dirname(__dirname), "example"), folder || "example");
}
function restartServer(settings, port) {
var rootDir = path.join(settings.source_dir),
indexFound = false,
express = require("express"),
consolidate = require("consolidate"),
app = express.createServer();
if (APP) {
APP.close();
APP = null;
}
app.configure(function () {
app.disable("view cache");
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(rootDir));
});
if (settings.expressConfig) {
app.configure(settings.expressConfig(express, app));
}
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
function renderTemplate(page) {
return function (req, res, next) {
var prop,
data = {layout : false};
for (prop in settings.global_data) {
data[prop] = settings.global_data[prop];
}
for (prop in page.data) {
data[prop] = page.data[prop];
}
consolidate[settings.template_engine](path.join(rootDir, page.source), data, function (err, html) {
if (err) {
throw err;
}
res.send(html);
});
};
}
var page, i, subdir;
for (i = 0; i < settings.pages.length; i++) {
page = settings.pages[i];
if (!indexFound && page.source.indexOf("index") > -1 || page.output.indexOf("index") > -1) {
subdir = path.join(path.sep, page.output.substr(0, page.output.indexOf("index") - 1));
app.get(subdir, renderTemplate(page));
indexFound = true;
}
app.get(path.join(path.sep, page.output), renderTemplate(page));
}
if (!indexFound) {
app.get(path.sep, renderTemplate(settings.pages[0]));
}
var running = true;
app.listen(port);
console.log("");
app.on("error", function (e) {
if (running) {
running = false;
if (e.code === "EADDRINUSE") {
console.error(("Port " + port + " is already in use. Please try with a different port, or exit the process which is tying up the port.").yellow);
} else {
console.error(e);
}
}
});
setTimeout(function () {
if (running) {
console.log("STATIX server is now running on port ".green + port.toString().yellow);
}
}, 500);
APP = app;
}
function build(settingsFile) {
utils.loadSettings(settingsFile, function (settings) {
var consolidate = require("consolidate"),
sourceDir = path.join(settings.source_dir),
outputDir = path.join(settings.output_dir);
console.log("");
settings.preBuild = settings.preBuild || function (cb) {
return cb();
};
settings.preBuild(function () {
if (fs.existsSync(outputDir)) {
wrench.rmdirSyncRecursive(outputDir);
}
utils.copyMatchingFiles(sourceDir, outputDir, settings.include_patterns, settings.exclude_patterns);
function renderTemplate(page, cb) {
consolidate[settings.template_engine](path.join(sourceDir, page.source), data, function (err, html) {
var outputFile = path.join(outputDir, page.output);
if (fs.existsSync(outputFile)) {
fs.unlinkSync(outputFile);
}
wrench.mkdirSyncRecursive(path.dirname(path.join(outputDir, page.output)));
fs.writeFileSync(path.join(outputDir, page.output), html);
if (cb) {
cb();
}
});
}
function callback() {
settings.postBuild = settings.postBuild || function (cb) {
return cb();
};
settings.postBuild(function () {
console.log("Statix build complete!".green);
console.log("");
process.exit();
});
}
for (var i = 0; i < settings.pages.length; i ++) {
var page = settings.pages[i],
data = {},
cb = null,
prop;
for (prop in settings.global_data) {
data[prop] = settings.global_data[prop];
}
for (prop in settings.build_data) {
data[prop] = settings.build_data[prop];
}
for (prop in page.data) {
data[prop] = page.data[prop];
}
if (i + 1 === settings.pages.length) {
cb = callback;
}
renderTemplate(page, cb);
}
});
});
}
module.exports = {
utils : utils,
server : server,
newProject : newProject,
restartServer : restartServer,
build : build
};
}());
| ff0000/statix | lib/statix.js | JavaScript | mit | 4,991 |
Session.setDefault('isLoggingIn', false);
Template.account.helpers({
signedUp: function() {
return Package["brettle:accounts-login-state"].LoginState.signedUp()
}
});
Template.account.events({
'click .logout': function(evt) {
Meteor.logout();
evt.preventDefault();
},
'click .login': function(evt) {
Session.set('isLoggingIn', true);
evt.preventDefault();
}
});
| jcantara/resume-tube | client/account.js | JavaScript | mit | 398 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({widgetLabel:"\u30d5\u30a3\u30fc\u30c1\u30e3",attach:"\u6dfb\u4ed8\u30d5\u30a1\u30a4\u30eb",fields:"\u30d5\u30a3\u30fc\u30eb\u30c9",fieldsSummary:"\u5c5e\u6027\u304a\u3088\u3073\u5024\u306e\u30ea\u30b9\u30c8",media:"\u30e1\u30c7\u30a3\u30a2",next:"\u6b21\u3078",noTitle:"\u7121\u984c",previous:"\u524d\u3078",lastEdited:"{date} \u306b\u6700\u5f8c\u306b\u7de8\u96c6\u3055\u308c\u307e\u3057\u305f\u3002",lastCreated:"{date} \u306b\u4f5c\u6210\u3055\u308c\u307e\u3057\u305f\u3002",lastEditedByUser:"{user} \u306b\u3088\u3063\u3066 {date} \u306b\u6700\u5f8c\u306b\u7de8\u96c6\u3055\u308c\u307e\u3057\u305f\u3002",
lastCreatedByUser:"{user} \u306b\u3088\u3063\u3066 {date} \u306b\u4f5c\u6210\u3055\u308c\u307e\u3057\u305f\u3002"}); | ycabon/presentations | 2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/widgets/Feature/nls/ja/Feature.js | JavaScript | mit | 890 |
var resource = require('../'),
creature = resource.define('creature');
creature.persist('memory');
creature.property('name');
creature.before('create', function (data, next) {
console.log('before creature.create')
data.name += '-a';
next(null, data)
});
creature.after('create', function (data, next) {
console.log('after creature.create')
data.name += "-b";
next(null, data);
});
creature.create({ name: 'bobby' }, function (err, result) {
console.log(err, result);
});
creature.on('create', function(data){
console.log('create has been created!', data)
});
creature.method('eat', function (options, callback){
callback(null, options);
});
creature.on('eat', function(data){
console.log('create ate!', data)
});
creature.eat({}, function(){});
creature.emit('eat', "food")
| bigcompany/resource | examples/hooks.js | JavaScript | mit | 810 |
/*!
CSSLint v0.10.0
Copyright (c) 2016 Nicole Sullivan and Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var clone = require('clone');
var parserlib = require('parserlib');
/**
* Main CSSLint object.
* @class CSSLint
* @static
* @extends parserlib.util.EventTarget
*/
/* global parserlib, clone, Reporter */
/* exported CSSLint */
var CSSLint = (function(){
"use strict";
var rules = [],
formatters = [],
embeddedRuleset = /\/\*\s*csslint([^\*]*)\*\//,
api = new parserlib.util.EventTarget();
api.version = "0.10.0";
//-------------------------------------------------------------------------
// Rule Management
//-------------------------------------------------------------------------
/**
* Adds a new rule to the engine.
* @param {Object} rule The rule to add.
* @method addRule
*/
api.addRule = function(rule){
rules.push(rule);
rules[rule.id] = rule;
};
/**
* Clears all rule from the engine.
* @method clearRules
*/
api.clearRules = function(){
rules = [];
};
/**
* Returns the rule objects.
* @return An array of rule objects.
* @method getRules
*/
api.getRules = function(){
return [].concat(rules).sort(function(a,b){
return a.id > b.id ? 1 : 0;
});
};
/**
* Returns a ruleset configuration object with all current rules.
* @return A ruleset object.
* @method getRuleset
*/
api.getRuleset = function() {
var ruleset = {},
i = 0,
len = rules.length;
while (i < len){
ruleset[rules[i++].id] = 1; //by default, everything is a warning
}
return ruleset;
};
/**
* Returns a ruleset object based on embedded rules.
* @param {String} text A string of css containing embedded rules.
* @param {Object} ruleset A ruleset object to modify.
* @return {Object} A ruleset object.
* @method getEmbeddedRuleset
*/
function applyEmbeddedRuleset(text, ruleset){
var valueMap,
embedded = text && text.match(embeddedRuleset),
rules = embedded && embedded[1];
if (rules) {
valueMap = {
"true": 2, // true is error
"": 1, // blank is warning
"false": 0, // false is ignore
"2": 2, // explicit error
"1": 1, // explicit warning
"0": 0 // explicit ignore
};
rules.toLowerCase().split(",").forEach(function(rule){
var pair = rule.split(":"),
property = pair[0] || "",
value = pair[1] || "";
ruleset[property.trim()] = valueMap[value.trim()];
});
}
return ruleset;
}
//-------------------------------------------------------------------------
// Formatters
//-------------------------------------------------------------------------
/**
* Adds a new formatter to the engine.
* @param {Object} formatter The formatter to add.
* @method addFormatter
*/
api.addFormatter = function(formatter) {
// formatters.push(formatter);
formatters[formatter.id] = formatter;
};
/**
* Retrieves a formatter for use.
* @param {String} formatId The name of the format to retrieve.
* @return {Object} The formatter or undefined.
* @method getFormatter
*/
api.getFormatter = function(formatId){
return formatters[formatId];
};
/**
* Formats the results in a particular format for a single file.
* @param {Object} result The results returned from CSSLint.verify().
* @param {String} filename The filename for which the results apply.
* @param {String} formatId The name of the formatter to use.
* @param {Object} options (Optional) for special output handling.
* @return {String} A formatted string for the results.
* @method format
*/
api.format = function(results, filename, formatId, options) {
var formatter = this.getFormatter(formatId),
result = null;
if (formatter){
result = formatter.startFormat();
result += formatter.formatResults(results, filename, options || {});
result += formatter.endFormat();
}
return result;
};
/**
* Indicates if the given format is supported.
* @param {String} formatId The ID of the format to check.
* @return {Boolean} True if the format exists, false if not.
* @method hasFormat
*/
api.hasFormat = function(formatId){
return formatters.hasOwnProperty(formatId);
};
//-------------------------------------------------------------------------
// Verification
//-------------------------------------------------------------------------
/**
* Starts the verification process for the given CSS text.
* @param {String} text The CSS text to verify.
* @param {Object} ruleset (Optional) List of rules to apply. If null, then
* all rules are used. If a rule has a value of 1 then it's a warning,
* a value of 2 means it's an error.
* @return {Object} Results of the verification.
* @method verify
*/
api.verify = function(text, ruleset){
var i = 0,
reporter,
lines,
report,
parser = new parserlib.css.Parser({ starHack: true, ieFilters: true,
underscoreHack: true, strict: false });
// normalize line endings
lines = text.replace(/\n\r?/g, "$split$").split("$split$");
if (!ruleset){
ruleset = this.getRuleset();
}
if (embeddedRuleset.test(text)){
//defensively copy so that caller's version does not get modified
ruleset = clone(ruleset);
ruleset = applyEmbeddedRuleset(text, ruleset);
}
reporter = new Reporter(lines, ruleset);
ruleset.errors = 2; //always report parsing errors as errors
for (i in ruleset){
if(ruleset.hasOwnProperty(i) && ruleset[i]){
if (rules[i]){
rules[i].init(parser, reporter);
}
}
}
//capture most horrible error type
try {
parser.parse(text);
} catch (ex) {
reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {});
}
report = {
messages : reporter.messages,
stats : reporter.stats,
ruleset : reporter.ruleset
};
//sort by line numbers, rollups at the bottom
report.messages.sort(function (a, b){
if (a.rollup && !b.rollup){
return 1;
} else if (!a.rollup && b.rollup){
return -1;
} else {
return a.line - b.line;
}
});
return report;
};
//-------------------------------------------------------------------------
// Publish the API
//-------------------------------------------------------------------------
return api;
})();
/**
* An instance of Report is used to report results of the
* verification back to the main API.
* @class Reporter
* @constructor
* @param {String[]} lines The text lines of the source.
* @param {Object} ruleset The set of rules to work with, including if
* they are errors or warnings.
*/
function Reporter(lines, ruleset){
"use strict";
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
/**
* List of statistics being reported.
* @property stats
* @type String[]
*/
this.stats = [];
/**
* Lines of code being reported on. Used to provide contextual information
* for messages.
* @property lines
* @type String[]
*/
this.lines = lines;
/**
* Information about the rules. Used to determine whether an issue is an
* error or warning.
* @property ruleset
* @type Object
*/
this.ruleset = ruleset;
}
Reporter.prototype = {
//restore constructor
constructor: Reporter,
/**
* Report an error.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method error
*/
error: function(message, line, col, rule){
"use strict";
this.messages.push({
type : "error",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule || {}
});
},
/**
* Report an warning.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method warn
* @deprecated Use report instead.
*/
warn: function(message, line, col, rule){
"use strict";
this.report(message, line, col, rule);
},
/**
* Report an issue.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method report
*/
report: function(message, line, col, rule){
"use strict";
this.messages.push({
type : this.ruleset[rule.id] === 2 ? "error" : "warning",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some informational text.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method info
*/
info: function(message, line, col, rule){
"use strict";
this.messages.push({
type : "info",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some rollup error information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupError
*/
rollupError: function(message, rule){
"use strict";
this.messages.push({
type : "error",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report some rollup warning information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupWarn
*/
rollupWarn: function(message, rule){
"use strict";
this.messages.push({
type : "warning",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report a statistic.
* @param {String} name The name of the stat to store.
* @param {Variant} value The value of the stat.
* @method stat
*/
stat: function(name, value){
"use strict";
this.stats[name] = value;
}
};
//expose for testing purposes
CSSLint._Reporter = Reporter;
/*
* Utility functions that make life easier.
*/
CSSLint.Util = {
/*
* Adds all properties from supplier onto receiver,
* overwriting if the same name already exists on
* reciever.
* @param {Object} The object to receive the properties.
* @param {Object} The object to provide the properties.
* @return {Object} The receiver
*/
mix: function(receiver, supplier){
"use strict";
var prop;
for (prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return prop;
},
/*
* Polyfill for array indexOf() method.
* @param {Array} values The array to search.
* @param {Variant} value The value to search for.
* @return {int} The index of the value if found, -1 if not.
*/
indexOf: function(values, value){
"use strict";
if (values.indexOf){
return values.indexOf(value);
} else {
for (var i=0, len=values.length; i < len; i++){
if (values[i] === value){
return i;
}
}
return -1;
}
},
/*
* Polyfill for array forEach() method.
* @param {Array} values The array to operate on.
* @param {Function} func The function to call on each item.
* @return {void}
*/
forEach: function(values, func) {
"use strict";
if (values.forEach){
return values.forEach(func);
} else {
for (var i=0, len=values.length; i < len; i++){
func(values[i], i, values);
}
}
}
};
/*
* Rule: Don't use adjoining classes (.foo.bar).
*/
CSSLint.addRule({
//rule information
id: "adjoining-classes",
name: "Disallow adjoining classes",
desc: "Don't use adjoining classes.",
browsers: "IE6",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
classCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type === parser.SELECTOR_PART_TYPE){
classCount = 0;
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type === "class"){
classCount++;
}
if (classCount > 1){
reporter.report("Don't use adjoining classes.", part.line, part.col, rule);
}
}
}
}
}
});
}
});
/*
* Rule: Don't use width or height when using padding or border.
*/
CSSLint.addRule({
//rule information
id: "box-model",
name: "Beware of broken box size",
desc: "Don't use width or height when using padding or border.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
widthProperties = {
border: 1,
"border-left": 1,
"border-right": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1
},
heightProperties = {
border: 1,
"border-bottom": 1,
"border-top": 1,
padding: 1,
"padding-bottom": 1,
"padding-top": 1
},
properties,
boxSizing = false;
function startRule(){
properties = {};
boxSizing = false;
}
function endRule(){
var prop, value;
if (!boxSizing) {
if (properties.height){
for (prop in heightProperties){
if (heightProperties.hasOwnProperty(prop) && properties[prop]){
value = properties[prop].value;
//special case for padding
if (!(prop === "padding" && value.parts.length === 2 && value.parts[0].value === 0)){
reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
if (properties.width){
for (prop in widthProperties){
if (widthProperties.hasOwnProperty(prop) && properties[prop]){
value = properties[prop].value;
if (!(prop === "padding" && value.parts.length === 2 && value.parts[1].value === 0)){
reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startviewport", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (heightProperties[name] || widthProperties[name]){
if (!/^0\S*$/.test(event.value) && !(name === "border" && event.value.toString() === "none")){
properties[name] = { line: event.property.line, col: event.property.col, value: event.value };
}
} else {
if (/^(width|height)/i.test(name) && /^(length|percentage)/.test(event.value.parts[0].type)){
properties[name] = 1;
} else if (name === "box-sizing") {
boxSizing = true;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endviewport", endRule);
}
});
/*
* Rule: box-sizing doesn't work in IE6 and IE7.
*/
CSSLint.addRule({
//rule information
id: "box-sizing",
name: "Disallow use of box-sizing",
desc: "The box-sizing properties isn't supported in IE6 and IE7.",
browsers: "IE6, IE7",
tags: ["Compatibility"],
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (name === "box-sizing"){
reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule);
}
});
}
});
/*
* Rule: Use the bulletproof @font-face syntax to avoid 404's in old IE
* (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax)
*/
CSSLint.addRule({
//rule information
id: "bulletproof-font-face",
name: "Use the bulletproof @font-face syntax",
desc: "Use the bulletproof @font-face syntax to avoid 404's in old IE (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax).",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
fontFaceRule = false,
firstSrc = true,
ruleFailed = false,
line, col;
// Mark the start of a @font-face declaration so we only test properties inside it
parser.addListener("startfontface", function(){
fontFaceRule = true;
});
parser.addListener("property", function(event){
// If we aren't inside an @font-face declaration then just return
if (!fontFaceRule) {
return;
}
var propertyName = event.property.toString().toLowerCase(),
value = event.value.toString();
// Set the line and col numbers for use in the endfontface listener
line = event.line;
col = event.col;
// This is the property that we care about, we can ignore the rest
if (propertyName === "src") {
var regex = /^\s?url\(['"].+\.eot\?.*['"]\)\s*format\(['"]embedded-opentype['"]\).*$/i;
// We need to handle the advanced syntax with two src properties
if (!value.match(regex) && firstSrc) {
ruleFailed = true;
firstSrc = false;
} else if (value.match(regex) && !firstSrc) {
ruleFailed = false;
}
}
});
// Back to normal rules that we don't need to test
parser.addListener("endfontface", function(){
fontFaceRule = false;
if (ruleFailed) {
reporter.report("@font-face declaration doesn't follow the fontspring bulletproof syntax.", line, col, rule);
}
});
}
});
/*
* Rule: Include all compatible vendor prefixes to reach a wider
* range of users.
*/
CSSLint.addRule({
//rule information
id: "compatible-vendor-prefixes",
name: "Require compatible vendor prefixes",
desc: "Include all compatible vendor prefixes to reach a wider range of users.",
browsers: "All",
//initialization
init: function (parser, reporter) {
"use strict";
var rule = this,
compatiblePrefixes,
properties,
prop,
variations,
prefixed,
i,
len,
inKeyFrame = false,
arrayPush = Array.prototype.push,
applyTo = [];
// See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details
compatiblePrefixes = {
"animation" : "webkit moz",
"animation-delay" : "webkit moz",
"animation-direction" : "webkit moz",
"animation-duration" : "webkit moz",
"animation-fill-mode" : "webkit moz",
"animation-iteration-count" : "webkit moz",
"animation-name" : "webkit moz",
"animation-play-state" : "webkit moz",
"animation-timing-function" : "webkit moz",
"appearance" : "webkit moz",
"border-end" : "webkit moz",
"border-end-color" : "webkit moz",
"border-end-style" : "webkit moz",
"border-end-width" : "webkit moz",
"border-image" : "webkit moz o",
"border-radius" : "webkit",
"border-start" : "webkit moz",
"border-start-color" : "webkit moz",
"border-start-style" : "webkit moz",
"border-start-width" : "webkit moz",
"box-align" : "webkit moz ms",
"box-direction" : "webkit moz ms",
"box-flex" : "webkit moz ms",
"box-lines" : "webkit ms",
"box-ordinal-group" : "webkit moz ms",
"box-orient" : "webkit moz ms",
"box-pack" : "webkit moz ms",
"box-sizing" : "webkit moz",
"box-shadow" : "webkit moz",
"column-count" : "webkit moz ms",
"column-gap" : "webkit moz ms",
"column-rule" : "webkit moz ms",
"column-rule-color" : "webkit moz ms",
"column-rule-style" : "webkit moz ms",
"column-rule-width" : "webkit moz ms",
"column-width" : "webkit moz ms",
"hyphens" : "epub moz",
"line-break" : "webkit ms",
"margin-end" : "webkit moz",
"margin-start" : "webkit moz",
"marquee-speed" : "webkit wap",
"marquee-style" : "webkit wap",
"padding-end" : "webkit moz",
"padding-start" : "webkit moz",
"tab-size" : "moz o",
"text-size-adjust" : "webkit ms",
"transform" : "webkit moz ms o",
"transform-origin" : "webkit moz ms o",
"transition" : "webkit moz o",
"transition-delay" : "webkit moz o",
"transition-duration" : "webkit moz o",
"transition-property" : "webkit moz o",
"transition-timing-function" : "webkit moz o",
"user-modify" : "webkit moz",
"user-select" : "webkit moz ms",
"word-break" : "epub ms",
"writing-mode" : "epub ms"
};
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = [];
prefixed = compatiblePrefixes[prop].split(" ");
for (i = 0, len = prefixed.length; i < len; i++) {
variations.push("-" + prefixed[i] + "-" + prop);
}
compatiblePrefixes[prop] = variations;
arrayPush.apply(applyTo, variations);
}
}
parser.addListener("startrule", function () {
properties = [];
});
parser.addListener("startkeyframes", function (event) {
inKeyFrame = event.prefix || true;
});
parser.addListener("endkeyframes", function () {
inKeyFrame = false;
});
parser.addListener("property", function (event) {
var name = event.property;
if (CSSLint.Util.indexOf(applyTo, name.text) > -1) {
// e.g., -moz-transform is okay to be alone in @-moz-keyframes
if (!inKeyFrame || typeof inKeyFrame !== "string" ||
name.text.indexOf("-" + inKeyFrame + "-") !== 0) {
properties.push(name);
}
}
});
parser.addListener("endrule", function () {
if (!properties.length) {
return;
}
var propertyGroups = {},
i,
len,
name,
prop,
variations,
value,
full,
actual,
item,
propertiesSpecified;
for (i = 0, len = properties.length; i < len; i++) {
name = properties[i];
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = compatiblePrefixes[prop];
if (CSSLint.Util.indexOf(variations, name.text) > -1) {
if (!propertyGroups[prop]) {
propertyGroups[prop] = {
full : variations.slice(0),
actual : [],
actualNodes: []
};
}
if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) {
propertyGroups[prop].actual.push(name.text);
propertyGroups[prop].actualNodes.push(name);
}
}
}
}
}
for (prop in propertyGroups) {
if (propertyGroups.hasOwnProperty(prop)) {
value = propertyGroups[prop];
full = value.full;
actual = value.actual;
if (full.length > actual.length) {
for (i = 0, len = full.length; i < len; i++) {
item = full[i];
if (CSSLint.Util.indexOf(actual, item) === -1) {
propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length === 2) ? actual.join(" and ") : actual.join(", ");
reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule);
}
}
}
}
}
});
}
});
/*
* Rule: Certain properties don't play well with certain display values.
* - float should not be used with inline-block
* - height, width, margin-top, margin-bottom, float should not be used with inline
* - vertical-align should not be used with block
* - margin, float should not be used with table-*
*/
CSSLint.addRule({
//rule information
id: "display-property-grouping",
name: "Require properties appropriate for display",
desc: "Certain properties shouldn't be used with certain display property values.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
var propertiesToCheck = {
display: 1,
"float": "none",
height: 1,
width: 1,
margin: 1,
"margin-left": 1,
"margin-right": 1,
"margin-bottom": 1,
"margin-top": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1,
"padding-bottom": 1,
"padding-top": 1,
"vertical-align": 1
},
properties;
function reportProperty(name, display, msg){
if (properties[name]){
if (typeof propertiesToCheck[name] !== "string" || properties[name].value.toLowerCase() !== propertiesToCheck[name]){
reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule);
}
}
}
function startRule(){
properties = {};
}
function endRule(){
var display = properties.display ? properties.display.value : null;
if (display){
switch(display){
case "inline":
//height, width, margin-top, margin-bottom, float should not be used with inline
reportProperty("height", display);
reportProperty("width", display);
reportProperty("margin", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");
break;
case "block":
//vertical-align should not be used with block
reportProperty("vertical-align", display);
break;
case "inline-block":
//float should not be used with inline-block
reportProperty("float", display);
break;
default:
//margin, float should not be used with table
if (display.indexOf("table-") === 0){
reportProperty("margin", display);
reportProperty("margin-left", display);
reportProperty("margin-right", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display);
}
//otherwise do nothing
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startviewport", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (propertiesToCheck[name]){
properties[name] = { value: event.value.text, line: event.property.line, col: event.property.col };
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endviewport", endRule);
}
});
/*
* Rule: Disallow duplicate background-images (using url).
*/
CSSLint.addRule({
//rule information
id: "duplicate-background-images",
name: "Disallow duplicate background images",
desc: "Every background-image should be unique. Use a common class for e.g. sprites.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
stack = {};
parser.addListener("property", function(event){
var name = event.property.text,
value = event.value,
i, len;
if (name.match(/background/i)) {
for (i=0, len=value.parts.length; i < len; i++) {
if (value.parts[i].type === "uri") {
if (typeof stack[value.parts[i].uri] === "undefined") {
stack[value.parts[i].uri] = event;
}
else {
reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule);
}
}
}
}
});
}
});
/*
* Rule: Duplicate properties must appear one after the other. If an already-defined
* property appears somewhere else in the rule, then it's likely an error.
*/
CSSLint.addRule({
//rule information
id: "duplicate-properties",
name: "Disallow duplicate properties",
desc: "Duplicate properties must appear one after the other.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
properties,
lastProperty;
function startRule(){
properties = {};
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startviewport", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase();
if (properties[name] && (lastProperty !== name || properties[name] === event.value.text)){
reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule);
}
properties[name] = event.value.text;
lastProperty = name;
});
}
});
/*
* Rule: Style rules without any properties defined should be removed.
*/
CSSLint.addRule({
//rule information
id: "empty-rules",
name: "Disallow empty rules",
desc: "Rules without any properties specified should be removed.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
count = 0;
parser.addListener("startrule", function(){
count=0;
});
parser.addListener("property", function(){
count++;
});
parser.addListener("endrule", function(event){
var selectors = event.selectors;
if (count === 0){
reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule);
}
});
}
});
/*
* Rule: There should be no syntax errors. (Duh.)
*/
CSSLint.addRule({
//rule information
id: "errors",
name: "Parsing Errors",
desc: "This rule looks for recoverable syntax errors.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("error", function(event){
reporter.error(event.message, event.line, event.col, rule);
});
}
});
CSSLint.addRule({
//rule information
id: "fallback-colors",
name: "Require fallback colors",
desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",
browsers: "IE6,IE7,IE8",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
lastProperty,
propertiesToCheck = {
color: 1,
background: 1,
"border-color": 1,
"border-top-color": 1,
"border-right-color": 1,
"border-bottom-color": 1,
"border-left-color": 1,
border: 1,
"border-top": 1,
"border-right": 1,
"border-bottom": 1,
"border-left": 1,
"background-color": 1
},
properties;
function startRule(){
properties = {};
lastProperty = null;
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startviewport", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase(),
parts = event.value.parts,
i = 0,
colorType = "",
len = parts.length;
if(propertiesToCheck[name]){
while(i < len){
if (parts[i].type === "color"){
if ("alpha" in parts[i] || "hue" in parts[i]){
if (/([^\)]+)\(/.test(parts[i])){
colorType = RegExp.$1.toUpperCase();
}
if (!lastProperty || (lastProperty.property.text.toLowerCase() !== name || lastProperty.colorType !== "compat")){
reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule);
}
} else {
event.colorType = "compat";
}
}
i++;
}
}
lastProperty = event;
});
}
});
/*
* Rule: You shouldn't use more than 10 floats. If you do, there's probably
* room for some abstraction.
*/
CSSLint.addRule({
//rule information
id: "floats",
name: "Disallow too many floats",
desc: "This rule tests if the float property is used too many times",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
var count = 0;
//count how many times "float" is used
parser.addListener("property", function(event){
if (event.property.text.toLowerCase() === "float" &&
event.value.text.toLowerCase() !== "none"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("floats", count);
if (count >= 10){
reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule);
}
});
}
});
/*
* Rule: Avoid too many @font-face declarations in the same stylesheet.
*/
CSSLint.addRule({
//rule information
id: "font-faces",
name: "Don't use too many web fonts",
desc: "Too many different web fonts in the same stylesheet.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
count = 0;
parser.addListener("startfontface", function(){
count++;
});
parser.addListener("endstylesheet", function(){
if (count > 5){
reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule);
}
});
}
});
/*
* Rule: You shouldn't need more than 9 font-size declarations.
*/
CSSLint.addRule({
//rule information
id: "font-sizes",
name: "Disallow too many font sizes",
desc: "Checks the number of font-size declarations.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
count = 0;
//check for use of "font-size"
parser.addListener("property", function(event){
if (event.property.toString() === "font-size"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("font-sizes", count);
if (count >= 10){
reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule);
}
});
}
});
/*
* Rule: When using a vendor-prefixed gradient, make sure to use them all.
*/
CSSLint.addRule({
//rule information
id: "gradients",
name: "Require all gradient definitions",
desc: "When using a vendor-prefixed gradient, make sure to use them all.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
gradients;
parser.addListener("startrule", function(){
gradients = {
moz: 0,
webkit: 0,
oldWebkit: 0,
o: 0
};
});
parser.addListener("property", function(event){
if (/\-(moz|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)){
gradients[RegExp.$1] = 1;
} else if (/\-webkit\-gradient/i.test(event.value)){
gradients.oldWebkit = 1;
}
});
parser.addListener("endrule", function(event){
var missing = [];
if (!gradients.moz){
missing.push("Firefox 3.6+");
}
if (!gradients.webkit){
missing.push("Webkit (Safari 5+, Chrome)");
}
if (!gradients.oldWebkit){
missing.push("Old Webkit (Safari 4+, Chrome)");
}
if (!gradients.o){
missing.push("Opera 11.1+");
}
if (missing.length && missing.length < 4){
reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule);
}
});
}
});
/*
* Rule: Don't use IDs for selectors.
*/
CSSLint.addRule({
//rule information
id: "ids",
name: "Disallow IDs in selectors",
desc: "Selectors should not contain IDs.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
idCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
idCount = 0;
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type === parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type === "id"){
idCount++;
}
}
}
}
if (idCount === 1){
reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule);
} else if (idCount > 1){
reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule);
}
}
});
}
});
/*
* Rule: Don't use @import, use <link> instead.
*/
CSSLint.addRule({
//rule information
id: "import",
name: "Disallow @import",
desc: "Don't use @import, use <link> instead.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("import", function(event){
reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule);
});
}
});
/*
* Rule: Make sure !important is not overused, this could lead to specificity
* war. Display a warning on !important declarations, an error if it's
* used more at least 10 times.
*/
CSSLint.addRule({
//rule information
id: "important",
name: "Disallow !important",
desc: "Be careful when using !important declaration",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
count = 0;
//warn that important is used and increment the declaration counter
parser.addListener("property", function(event){
if (event.important === true){
count++;
reporter.report("Use of !important", event.line, event.col, rule);
}
});
//if there are more than 10, show an error
parser.addListener("endstylesheet", function(){
reporter.stat("important", count);
if (count >= 10){
reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specificity issues.", rule);
}
});
}
});
/*
* Rule: Properties should be known (listed in CSS3 specification) or
* be a vendor-prefixed property.
*/
CSSLint.addRule({
//rule information
id: "known-properties",
name: "Require use of known properties",
desc: "Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("property", function(event){
// the check is handled entirely by the parser-lib (https://github.com/nzakas/parser-lib)
if (event.invalid) {
reporter.report(event.invalid.message, event.line, event.col, rule);
}
});
}
});
/*
* Rule: All properties should be in alphabetical order..
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "order-alphabetical",
name: "Alphabetical order",
desc: "Assure properties are in alphabetical order",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
properties;
var startRule = function () {
properties = [];
};
var endRule = function(event){
var currentProperties = properties.join(","),
expectedProperties = properties.sort().join(",");
if (currentProperties !== expectedProperties){
reporter.report("Rule doesn't have all its properties in alphabetical ordered.", event.line, event.col, rule);
}
};
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startviewport", startRule);
parser.addListener("property", function(event){
var name = event.property.text,
lowerCasePrefixLessName = name.toLowerCase().replace(/^-.*?-/, "");
properties.push(lowerCasePrefixLessName);
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endviewport", endRule);
}
});
/*
* Rule: outline: none or outline: 0 should only be used in a :focus rule
* and only if there are other properties in the same rule.
*/
CSSLint.addRule({
//rule information
id: "outline-none",
name: "Disallow outline: none",
desc: "Use of outline: none or outline: 0 should be limited to :focus rules.",
browsers: "All",
tags: ["Accessibility"],
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
lastRule;
function startRule(event){
if (event.selectors){
lastRule = {
line: event.line,
col: event.col,
selectors: event.selectors,
propCount: 0,
outline: false
};
} else {
lastRule = null;
}
}
function endRule(){
if (lastRule){
if (lastRule.outline){
if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") === -1){
reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule);
} else if (lastRule.propCount === 1) {
reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startviewport", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase(),
value = event.value;
if (lastRule){
lastRule.propCount++;
if (name === "outline" && (value.toString() === "none" || value.toString() === "0")){
lastRule.outline = true;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endviewport", endRule);
}
});
/*
* Rule: Don't use classes or IDs with elements (a.foo or a#foo).
*/
CSSLint.addRule({
//rule information
id: "overqualified-elements",
name: "Disallow overqualified elements",
desc: "Don't use classes or IDs with elements (a.foo or a#foo).",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
classes = {};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type === parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (part.elementName && modifier.type === "id"){
reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule);
} else if (modifier.type === "class"){
if (!classes[modifier]){
classes[modifier] = [];
}
classes[modifier].push({ modifier: modifier, part: part });
}
}
}
}
}
});
parser.addListener("endstylesheet", function(){
var prop;
for (prop in classes){
if (classes.hasOwnProperty(prop)){
//one use means that this is overqualified
if (classes[prop].length === 1 && classes[prop][0].part.elementName){
reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule);
}
}
}
});
}
});
/*
* Rule: Headings (h1-h6) should not be qualified (namespaced).
*/
CSSLint.addRule({
//rule information
id: "qualified-headings",
name: "Disallow qualified headings",
desc: "Headings should not be qualified (namespaced).",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type === parser.SELECTOR_PART_TYPE){
if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0){
reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule);
}
}
}
}
});
}
});
/*
* Rule: Selectors that look like regular expressions are slow and should be avoided.
*/
CSSLint.addRule({
//rule information
id: "regex-selectors",
name: "Disallow selectors that look like regexs",
desc: "Selectors that look like regular expressions are slow and should be avoided.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type === parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type === "attribute"){
if (/([\~\|\^\$\*]=)/.test(modifier)){
reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule);
}
}
}
}
}
}
});
}
});
/*
* Rule: Total number of rules should not exceed x.
*/
CSSLint.addRule({
//rule information
id: "rules-count",
name: "Rules Count",
desc: "Track how many rules there are.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var count = 0;
//count each rule
parser.addListener("startrule", function(){
count++;
});
parser.addListener("endstylesheet", function(){
reporter.stat("rule-count", count);
});
}
});
/*
* Rule: Warn people with approaching the IE 4095 limit
*/
CSSLint.addRule({
//rule information
id: "selector-max-approaching",
name: "Warn when approaching the 4095 selector limit for IE",
desc: "Will warn when selector count is >= 3800 selectors.",
browsers: "IE",
//initialization
init: function(parser, reporter) {
"use strict";
var rule = this, count = 0;
parser.addListener("startrule", function(event) {
count += event.selectors.length;
});
parser.addListener("endstylesheet", function() {
if (count >= 3800) {
reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,rule);
}
});
}
});
/*
* Rule: Warn people past the IE 4095 limit
*/
CSSLint.addRule({
//rule information
id: "selector-max",
name: "Error when past the 4095 selector limit for IE",
desc: "Will error when selector count is > 4095.",
browsers: "IE",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this, count = 0;
parser.addListener("startrule", function(event) {
count += event.selectors.length;
});
parser.addListener("endstylesheet", function() {
if (count > 4095) {
reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,rule);
}
});
}
});
/*
* Rule: Avoid new-line characters in selectors.
*/
CSSLint.addRule({
//rule information
id: "selector-newline",
name: "Disallow new-line characters in selectors",
desc: "New-line characters in selectors are usually a forgotten comma and not a descendant combinator.",
browsers: "All",
//initialization
init: function(parser, reporter) {
"use strict";
var rule = this;
function startRule(event) {
var i, len, selector, p, n, pLen, part, part2, type, currentLine, nextLine,
selectors = event.selectors;
for (i = 0, len = selectors.length; i < len; i++) {
selector = selectors[i];
for (p = 0, pLen = selector.parts.length; p < pLen; p++) {
for (n = p + 1; n < pLen; n++) {
part = selector.parts[p];
part2 = selector.parts[n];
type = part.type;
currentLine = part.line;
nextLine = part2.line;
if (type === "descendant" && nextLine > currentLine) {
reporter.report("newline character found in selector (forgot a comma?)", currentLine, selectors[i].parts[0].col, rule);
}
}
}
}
}
parser.addListener("startrule", startRule);
}
});
/*
* Rule: Use shorthand properties where possible.
*
*/
CSSLint.addRule({
//rule information
id: "shorthand",
name: "Require shorthand properties",
desc: "Use shorthand properties where possible.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
prop, i, len,
propertiesToCheck = {},
properties,
mapping = {
"margin": [
"margin-top",
"margin-bottom",
"margin-left",
"margin-right"
],
"padding": [
"padding-top",
"padding-bottom",
"padding-left",
"padding-right"
]
};
//initialize propertiesToCheck
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
for (i=0, len=mapping[prop].length; i < len; i++){
propertiesToCheck[mapping[prop][i]] = prop;
}
}
}
function startRule(){
properties = {};
}
//event handler for end of rules
function endRule(event){
var prop, i, len, total;
//check which properties this rule has
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
total=0;
for (i=0, len=mapping[prop].length; i < len; i++){
total += properties[mapping[prop][i]] ? 1 : 0;
}
if (total === mapping[prop].length){
reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase();
if (propertiesToCheck[name]){
properties[name] = 1;
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*
* Rule: Don't use properties with a star prefix.
*
*/
CSSLint.addRule({
//rule information
id: "star-property-hack",
name: "Disallow properties with a star prefix",
desc: "Checks for the star property hack (targets IE6/7)",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
//check if property name starts with "*"
parser.addListener("property", function(event){
var property = event.property;
if (property.hack === "*") {
reporter.report("Property with star prefix found.", event.property.line, event.property.col, rule);
}
});
}
});
/*
* Rule: Don't use text-indent for image replacement if you need to support rtl.
*
*/
CSSLint.addRule({
//rule information
id: "text-indent",
name: "Disallow negative text-indent",
desc: "Checks for text indent less than -99px",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
textIndent,
direction;
function startRule(){
textIndent = false;
direction = "inherit";
}
//event handler for end of rules
function endRule(){
if (textIndent && direction !== "ltr"){
reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule);
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase(),
value = event.value;
if (name === "text-indent" && value.parts[0].value < -99){
textIndent = event.property;
} else if (name === "direction" && value.toString() === "ltr"){
direction = "ltr";
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*
* Rule: Don't use properties with a underscore prefix.
*
*/
CSSLint.addRule({
//rule information
id: "underscore-property-hack",
name: "Disallow properties with an underscore prefix",
desc: "Checks for the underscore property hack (targets IE6)",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
//check if property name starts with "_"
parser.addListener("property", function(event){
var property = event.property;
if (property.hack === "_") {
reporter.report("Property with underscore prefix found.", event.property.line, event.property.col, rule);
}
});
}
});
/*
* Rule: Headings (h1-h6) should be defined only once.
*/
CSSLint.addRule({
//rule information
id: "unique-headings",
name: "Headings should only be defined once",
desc: "Headings should be defined only once.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
var headings = {
h1: 0,
h2: 0,
h3: 0,
h4: 0,
h5: 0,
h6: 0
};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
pseudo,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())){
for (j=0; j < part.modifiers.length; j++){
if (part.modifiers[j].type === "pseudo"){
pseudo = true;
break;
}
}
if (!pseudo){
headings[RegExp.$1]++;
if (headings[RegExp.$1] > 1) {
reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule);
}
}
}
}
});
parser.addListener("endstylesheet", function(){
var prop,
messages = [];
for (prop in headings){
if (headings.hasOwnProperty(prop)){
if (headings[prop] > 1){
messages.push(headings[prop] + " " + prop + "s");
}
}
}
if (messages.length){
reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule);
}
});
}
});
/*
* Rule: Don't use universal selector because it's slow.
*/
CSSLint.addRule({
//rule information
id: "universal-selector",
name: "Disallow universal selector",
desc: "The universal selector (*) is known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
i;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName === "*"){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
});
}
});
/*
* Rule: Don't use unqualified attribute selectors because they're just like universal selectors.
*/
CSSLint.addRule({
//rule information
id: "unqualified-attributes",
name: "Disallow unqualified attribute selectors",
desc: "Unqualified attribute selectors are known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.type === parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type === "attribute" && (!part.elementName || part.elementName === "*")){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
}
}
});
}
});
/*
* Rule: When using a vendor-prefixed property, make sure to
* include the standard one.
*/
CSSLint.addRule({
//rule information
id: "vendor-prefix",
name: "Require standard property with vendor prefix",
desc: "When using a vendor-prefixed property, make sure to include the standard one.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this,
properties,
num,
propertiesToCheck = {
"-webkit-border-radius": "border-radius",
"-webkit-border-top-left-radius": "border-top-left-radius",
"-webkit-border-top-right-radius": "border-top-right-radius",
"-webkit-border-bottom-left-radius": "border-bottom-left-radius",
"-webkit-border-bottom-right-radius": "border-bottom-right-radius",
"-o-border-radius": "border-radius",
"-o-border-top-left-radius": "border-top-left-radius",
"-o-border-top-right-radius": "border-top-right-radius",
"-o-border-bottom-left-radius": "border-bottom-left-radius",
"-o-border-bottom-right-radius": "border-bottom-right-radius",
"-moz-border-radius": "border-radius",
"-moz-border-radius-topleft": "border-top-left-radius",
"-moz-border-radius-topright": "border-top-right-radius",
"-moz-border-radius-bottomleft": "border-bottom-left-radius",
"-moz-border-radius-bottomright": "border-bottom-right-radius",
"-moz-column-count": "column-count",
"-webkit-column-count": "column-count",
"-moz-column-gap": "column-gap",
"-webkit-column-gap": "column-gap",
"-moz-column-rule": "column-rule",
"-webkit-column-rule": "column-rule",
"-moz-column-rule-style": "column-rule-style",
"-webkit-column-rule-style": "column-rule-style",
"-moz-column-rule-color": "column-rule-color",
"-webkit-column-rule-color": "column-rule-color",
"-moz-column-rule-width": "column-rule-width",
"-webkit-column-rule-width": "column-rule-width",
"-moz-column-width": "column-width",
"-webkit-column-width": "column-width",
"-webkit-column-span": "column-span",
"-webkit-columns": "columns",
"-moz-box-shadow": "box-shadow",
"-webkit-box-shadow": "box-shadow",
"-moz-transform" : "transform",
"-webkit-transform" : "transform",
"-o-transform" : "transform",
"-ms-transform" : "transform",
"-moz-transform-origin" : "transform-origin",
"-webkit-transform-origin" : "transform-origin",
"-o-transform-origin" : "transform-origin",
"-ms-transform-origin" : "transform-origin",
"-moz-box-sizing" : "box-sizing",
"-webkit-box-sizing" : "box-sizing"
};
//event handler for beginning of rules
function startRule(){
properties = {};
num = 1;
}
//event handler for end of rules
function endRule(){
var prop,
i,
len,
needed,
actual,
needsStandard = [];
for (prop in properties){
if (propertiesToCheck[prop]){
needsStandard.push({ actual: prop, needed: propertiesToCheck[prop]});
}
}
for (i=0, len=needsStandard.length; i < len; i++){
needed = needsStandard[i].needed;
actual = needsStandard[i].actual;
if (!properties[needed]){
reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
} else {
//make sure standard property is last
if (properties[needed][0].pos < properties[actual][0].pos){
reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startviewport", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (!properties[name]){
properties[name] = [];
}
properties[name].push({ name: event.property, value : event.value, pos:num++ });
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endviewport", endRule);
}
});
/*
* Rule: You don't need to specify units when a value is 0.
*/
CSSLint.addRule({
//rule information
id: "zero-units",
name: "Disallow units for 0 values",
desc: "You don't need to specify units when a value is 0.",
browsers: "All",
//initialization
init: function(parser, reporter){
"use strict";
var rule = this;
//count how many times "float" is used
parser.addListener("property", function(event){
var parts = event.value.parts,
i = 0,
len = parts.length;
while(i < len){
if ((parts[i].units || parts[i].type === "percentage") && parts[i].value === 0 && parts[i].type !== "time"){
reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule);
}
i++;
}
});
}
});
(function() {
"use strict";
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var xmlEscape = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/[\"&><]/g, function(match) {
switch (match) {
case "\"":
return """;
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
}
});
};
CSSLint.addFormatter({
//format information
id: "checkstyle-xml",
name: "Checkstyle XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</checkstyle>";
},
/**
* Returns message when there is a file read error.
* @param {String} filename The name of the file that caused the error.
* @param {String} message The error message
* @return {String} The error message.
*/
readError: function(filename, message) {
return "<file name=\"" + xmlEscape(filename) + "\"><error line=\"0\" column=\"0\" severty=\"error\" message=\"" + xmlEscape(message) + "\"></error></file>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename/*, options*/) {
var messages = results.messages,
output = [];
/**
* Generate a source string for a rule.
* Checkstyle source strings usually resemble Java class names e.g
* net.csslint.SomeRuleName
* @param {Object} rule
* @return rule source as {String}
*/
var generateSource = function(rule) {
if (!rule || !("name" in rule)) {
return "";
}
return "net.csslint." + rule.name.replace(/\s/g,"");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message) {
//ignore rollups for now
if (!message.rollup) {
output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" message=\"" + xmlEscape(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
}());
CSSLint.addFormatter({
//format information
id: "compact",
name: "Compact, 'porcelain' format",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
"use strict";
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
"use strict";
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
"use strict";
var messages = results.messages,
output = "";
options = options || {};
/**
* Capitalize and return given string.
* @param str {String} to capitalize
* @return {String} capitalized
*/
var capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
if (messages.length === 0) {
return options.quiet ? "" : filename + ": Lint Free!";
}
CSSLint.Util.forEach(messages, function(message) {
if (message.rollup) {
output += filename + ": " + capitalize(message.type) + " - " + message.message + "\n";
} else {
output += filename + ": " + "line " + message.line +
", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + " (" + message.rule.id + ")\n";
}
});
return output;
}
});
CSSLint.addFormatter({
//format information
id: "csslint-xml",
name: "CSSLint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
"use strict";
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
"use strict";
return "</csslint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename/*, options*/) {
"use strict";
var messages = results.messages,
output = [];
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
CSSLint.addFormatter({
//format information
id: "junit-xml",
name: "JUNIT XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
"use strict";
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><testsuites>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function() {
"use strict";
return "</testsuites>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename/*, options*/) {
"use strict";
var messages = results.messages,
output = [],
tests = {
"error": 0,
"failure": 0
};
/**
* Generate a source string for a rule.
* JUNIT source strings usually resemble Java class names e.g
* net.csslint.SomeRuleName
* @param {Object} rule
* @return rule source as {String}
*/
var generateSource = function(rule) {
if (!rule || !("name" in rule)) {
return "";
}
return "net.csslint." + rule.name.replace(/\s/g,"");
};
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
messages.forEach(function (message) {
// since junit has no warning class
// all issues as errors
var type = message.type === "warning" ? "error" : message.type;
//ignore rollups for now
if (!message.rollup) {
// build the test case seperately, once joined
// we'll add it to a custom array filtered by type
output.push("<testcase time=\"0\" name=\"" + generateSource(message.rule) + "\">");
output.push("<" + type + " message=\"" + escapeSpecialCharacters(message.message) + "\"><![CDATA[" + message.line + ":" + message.col + ":" + escapeSpecialCharacters(message.evidence) + "]]></" + type + ">");
output.push("</testcase>");
tests[type] += 1;
}
});
output.unshift("<testsuite time=\"0\" tests=\"" + messages.length + "\" skipped=\"0\" errors=\"" + tests.error + "\" failures=\"" + tests.failure + "\" package=\"net.csslint\" name=\"" + filename + "\">");
output.push("</testsuite>");
}
return output.join("");
}
});
CSSLint.addFormatter({
//format information
id: "lint-xml",
name: "Lint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
"use strict";
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
"use strict";
return "</lint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename/*, options*/) {
"use strict";
var messages = results.messages,
output = [];
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
var rule = "";
if (message.rule && message.rule.id) {
rule = "rule=\"" + escapeSpecialCharacters(message.rule.id) + "\" ";
}
output.push("<issue " + rule + "line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
CSSLint.addFormatter({
//format information
id: "text",
name: "Plain Text",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
"use strict";
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
"use strict";
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
"use strict";
var messages = results.messages,
output = "";
options = options || {};
if (messages.length === 0) {
return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + ".";
}
output = "\n\ncsslint: There ";
if (messages.length === 1) {
output += "is 1 problem";
} else {
output += "are " + messages.length + " problems";
}
output += " in " + filename + ".";
var pos = filename.lastIndexOf("/"),
shortFilename = filename;
if (pos === -1){
pos = filename.lastIndexOf("\\");
}
if (pos > -1){
shortFilename = filename.substring(pos+1);
}
CSSLint.Util.forEach(messages, function (message, i) {
output = output + "\n\n" + shortFilename;
if (message.rollup) {
output += "\n" + (i+1) + ": " + message.type;
output += "\n" + message.message;
} else {
output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col;
output += "\n" + message.message;
output += "\n" + message.evidence;
}
});
return output;
}
});
exports.CSSLint = CSSLint; | SimenB/csslint | dist/csslint-node.js | JavaScript | mit | 96,013 |
import { applyMiddleware, createStore, compose } from "redux";
//Connect react router with redux
import { syncHistoryWithStore } from "react-router-redux";
import { browserHistory } from "react-router";
import logger from "redux-logger";
import thunk from "redux-thunk";
import promise from "redux-promise-middleware";
import rootReducer from './reducers/index.js';
// axsios
//If making an initial state and passing as a preloadedState to createStore, need to make a reducer
//for each property in the intial state. The reason being the reducer has access to the state. So
//This is like setting the initial state for thee reducers here instead of doing it directly in the
//reducer function itself.
// const initialState = {
// allData: 123,
// sesssion
// }
const middleware = applyMiddleware(promise(), thunk, logger());
const store = createStore(rootReducer, middleware);
export const history = syncHistoryWithStore(browserHistory, store);
export default store; | nhoon2002/CodeFlo | src/store.js | JavaScript | mit | 982 |
var url = 'http://localhost:8313';
var kTickInterval = 5000;
var kEmailRequired = false;
window.onload = kRefreshState;
var stateErrorDetails = {
'not ready': 'It looks like the "iGrabber Capture" application is not ' +
'running. Launch it from Applications > iGrabber Capture. (If it ' +
'is already running, try force quitting it and then launching it.)',
'stuck': 'The "iGrabber Capture" application is stuck. Try switching ' +
'to it and clicking the "OK" button.'
};
function kRefreshState()
{
makeRequest('get', '/state', null, function () {
setTimeout(kRefreshState, kTickInterval);
});
}
function kLoadState(data)
{
$('#kStatus').text(data);
if (stateErrorDetails.hasOwnProperty(data)) {
$('.kError').css('display', 'block');
$('.kError').text(stateErrorDetails[data]);
} else {
$('.kError').css('display', 'none');
}
if (data == 'recording') {
$('#kButtonStart').prop('value',
'Start recording another race');
$('#kButtonStart').prop('disabled', false);
$('#kButtonStop').prop('disabled', false);
} else if (data == 'idle') {
$('#kButtonStart').prop('disabled', false);
$('#kButtonStop').prop('disabled', 'true');
} else {
$('#kButtonStart').prop('disabled', true);
$('#kButtonStop').prop('disabled', true);
}
}
function kLoadLog(elts)
{
var html =
'<table class="kLog">' +
elts.map(function (entry) {
return ('<tr><td class="kLogWhen">' +
new Date(entry[0]).toLocaleTimeString() +
'</td><td class="kLogMessage">' + entry[1] + '</td></tr>');
}).join('\n') + '</table>';
$('#kLog').html(html);
}
function kReset()
{
$('input[type=text]').val('');
}
function kStop()
{
makeRequest('post', '/stop', {});
}
function kStart()
{
var obj, npl, msg;
obj = {};
$('input[type=text]').each(
function (_, e) { obj[e.id] = $(e).val(); });
npl = $('#np3')[0].checked ? 3 : 4;
obj['nplayers'] = npl;
obj['level'] =
$('#50cc')[0].checked ? '50cc' :
$('#100cc')[0].checked ? '100cc' :
$('#150cc')[0].checked ? '150cc' : 'unknown';
if (!obj['p1handle'] || !obj['p2handle'] || !obj['p3handle'] ||
(npl == 4 && !obj['p4handle']))
msg = 'Handles are required. (Use "anon" for anonymous.)';
else if (kEmailRequired &&
(!obj['p1email'] || !obj['p2email'] || !obj['p3email'] ||
(npl == 4 && !obj['p4email'])))
msg = 'Email address is required.';
if (msg) {
alert(msg);
return;
}
makeRequest('post', '/start', obj);
}
function makeRequest(method, path, args, callback)
{
var options = {
'url': url + path,
'method': method,
'dataType': 'json',
'success': function (data) {
kLoadState(data['state']);
kLoadLog(data['ulog']);
if (callback)
callback();
},
'error': function (data) {
var msg;
try { msg = JSON.parse(data['responseText']); } catch (ex) {}
if (msg && msg['message'].substr(0, 'bad state: '.length) ==
'bad state: ')
kLoadState(msg['message'].substr('bad state: '.length));
else
console.error('failed request: ', path, data);
if (callback)
callback(new Error('failed'));
}
};
if (args) {
options['contentType'] = 'application/json';
options['data'] = JSON.stringify(args);
options['processData'] = false;
}
$.ajax(options);
}
function kNpChanged()
{
if ($('#np3')[0].checked) {
$('#p4handle, #p4email').prop('disabled', true);
$('#p4handle, #p4email').val('');
} else {
$('#p4handle, #p4email').prop('disabled', false);
}
}
| davepacheco/kartlytics-controller | www/recorder.js | JavaScript | mit | 3,469 |
//require last.fm api client
var LastFmNode = require('lastfm').LastFmNode;
//get api keys from config file
var config = require('../config.js');
//save.js to save json
var save = require('../save.js');
// fs to open json
var fs = require('fs');
//initialize api client
var lastfm = new LastFmNode({
api_key: config.lastfm.key, // sign-up for a key at http://www.last.fm/api
secret: config.lastfm.secret,
useragent: 'api.lukemil.es' // optional. defaults to lastfm-node.
});
// This job returns weekly last.fm play data.
job('music-weekly', function(done) {
//get user's weekly artist chart to do weekly play count
var request = lastfm.request("user.getWeeklyArtistChart", {
user: config.lastfm.username,
handlers: {
success: function(data) {
//create object to later save
var weeklySongs = new Object;
weeklySongs.interval = 7;
//eliminate unneeded data
data = data.weeklyartistchart.artist;
//get list of keys
var artistkeys = Object.keys(data);
// initialize plays variable
weeklySongs.plays = 0;
//initialize top artist variable
weeklySongs.topArtist = new Object;
// add number of unique artists to object
weeklySongs.uniqueArtists = artistkeys.length;
// iterate through keys
for( var i = 0, length = artistkeys.length; i < length; i++ ) {
//we have to do parseInt() because the JSON has the number as a string
weeklySongs.plays = parseInt(data[artistkeys[ i ] ].playcount) + weeklySongs.plays;
// save artist which is number 1
if (parseInt(data[artistkeys[i]]['@attr'].rank) === 1) {
weeklySongs.topArtist.name = data[artistkeys[i]].name;
weeklySongs.topArtist.count = parseInt(data[artistkeys[i]].playcount);
}
}
save.file("music-weekly", weeklySongs);
console.log('Weekly last.fm data updated.');
},
error: function(error) {
return;
}
}
});
}).every('1h');
// gets recent last fm data
job('music-recent', function(done) {
var request = lastfm.request("user.getRecentTracks", {
user: config.lastfm.username,
handlers: {
success: function(data) {
//create object to later save
var recentSongs = new Object;
// create object of just songs
recentSongs.songs = [];
recentSongs.interval = 1;
//eliminate unneeded data
recentSongs.nowPlaying = (data.recenttracks.track[0]["@attr"]) ? true : false;
data = data.recenttracks.track;
//iterate through artist data...
//get list of keys
var keys = Object.keys(data);
// iterate through keys
for(var i = 0, length = keys.length; i < length; i++) {
//create temport object for song
song = new Object;
// create temporary object for working song from api
lastSong = data[keys[i]];
//scoop up the data we want
song.artist = lastSong.artist["#text"];
song.name = lastSong.name;
song.album = lastSong.album["#text"];
song.image = lastSong.image[lastSong.image.length - 1]["#text"];
song.url = lastSong.url;
// convert spaces to plusses and construct URL
song.artistUrl = "http://www.last.fm/music/" + lastSong.artist["#text"].replace(/\s+/g, '+');
// cannot figure out why this line creates the error
// [TypeError: Cannot read property '#time' of undefined]
// it worked at first during my testing and stopped
// song["time"] = lastSong["date"]["#time"];
// song.date_unix = lastSong["date"].uts
//store data in main object
recentSongs.songs[keys[i]] = song;
}
save.file("music-recent", recentSongs);
console.log('Recent last.fm data updated.');
done(recentSongs);
},
error: function(error) {
console.log(error);
return;
}
}
});
}).every('90s');
job('music-combine', function(done, musicRecent) {
// only combine file if music-weekly exists
path = "json/music-weekly.json";
fs.exists(path, function(exists) {
if (exists) {
// synchronously open the weekly file
var musicWeekly = JSON.parse(fs.readFileSync(path).toString());
// create new object to dump data in
var music = new Object;
// merge files into one object
music.nowPlaying = musicRecent.nowPlaying;
music.recent = musicRecent.songs;
music.weeklyPlays = musicWeekly.plays;
music.weeklyTopArtist = musicWeekly.topArtist;
music.weeklyUniqueArtists = musicWeekly.uniqueArtists;
// save to music.json
console.log('music.json updated');
save.file("music", music);
}
});
}).after('music-recent');
| denolfe/api.elliotdenolf.com | jobs/lastfm.js | JavaScript | mit | 5,172 |
import React from "react";
import { shallow } from "enzyme";
import { Link } from "react-router";
import { createMockUser } from "../../utilities/tests/test-utils";
import NavBar from "./NavBar";
const notLoggedUser = createMockUser();
const authenticatedUser = createMockUser("user@test.com", true, true, "ADMIN");
const authenticatedViewer = createMockUser("user@test.com", true, true, "VIEWER");
const defaultProps = {
config: {
enableDatasetImport: false,
},
user: notLoggedUser,
rootPath: "/florence",
location: {},
};
const withPreviewNavProps = {
...defaultProps,
location: {
...defaultProps.location,
pathname: "/florence/collections/foo-1234/preview",
},
workingOn: {
id: "foo-1234",
name: "foo",
},
};
const NavbarItems = ["Collections", "Users and access", "Teams", "Security", "Sign out"];
describe("NavBar", () => {
describe("when user is not authenticated", () => {
it("should render only one link to Sign in", () => {
const component = shallow(<NavBar {...defaultProps} />);
expect(component.hasClass("global-nav__list")).toBe(true);
expect(component.find(Link)).toHaveLength(1);
expect(component.find("Link[to='/florence/login']").exists()).toBe(true);
});
});
describe("when user is authenticated as Admin", () => {
it("should render navigation with links", () => {
const component = shallow(<NavBar {...defaultProps} user={authenticatedUser} />);
const nav = component.find(Link);
expect(component.hasClass("global-nav__list")).toBe(true);
expect(component.find(Link)).toHaveLength(NavbarItems.length);
nav.forEach((n, i) => expect(n.getElement().props.children).toBe(NavbarItems[i]));
});
it("should not render Sign in link", () => {
const component = shallow(<NavBar {...defaultProps} user={authenticatedUser} />);
expect(component.hasClass("sign-in")).toBe(false);
});
it("should not display Datasets", () => {
const component = shallow(<NavBar {...defaultProps} user={authenticatedUser} />);
expect(component.find("Link[to='/florence/uploads/data']").exists()).toBe(false);
});
describe("when enableNewSignIn feature flag is enabled", () => {
const props = {
...defaultProps,
config: {
...defaultProps.config,
enableNewSignIn: true,
},
};
const component = shallow(<NavBar {...props} user={authenticatedUser} />);
it("Preview teams option should be present", () => {
const link = component.find("Link[to='/florence/groups']");
expect(link.getElement().props.children[0].includes("Preview teams"));
});
});
describe("when enabled dataset import", () => {
it("should display Datasets", () => {
const props = {
...defaultProps,
user: authenticatedUser,
config: {
...defaultProps.config,
enableDatasetImport: true,
},
};
const component = shallow(<NavBar {...props} />);
expect(component.find("Link[to='/florence/uploads/data']").exists()).toBe(true);
});
});
describe("when enabled dataset import", () => {
it("should display Datasets", () => {
const props = {
...defaultProps,
user: authenticatedUser,
config: {
...defaultProps.config,
enableDatasetImport: true,
},
};
const component = shallow(<NavBar {...props} />);
expect(component.find("Link[to='/florence/uploads/data']").exists()).toBe(true);
});
});
describe("when on collections", () => {
it("should display Working On: ", () => {
const props = {
...defaultProps,
user: authenticatedUser,
location: {
pathname: "/florence/collections/foo-1234",
},
workingOn: {
id: "foo-1234",
name: "foo",
},
};
const wrapper = shallow(<NavBar {...props} />);
const link = wrapper.find("Link[to='/florence/collections/foo-1234']");
link.getElement().props.children[0].includes("Working on:");
link.getElement().props.children[0].includes("foo");
});
});
});
describe("when user is authenticated as Viewer", () => {
it("should render navigation with links", () => {
const NavbarItems = ["Collections", "Sign out"];
const component = shallow(<NavBar {...defaultProps} user={authenticatedViewer} />);
const nav = component.find(Link);
expect(component.hasClass("global-nav__list")).toBe(true);
expect(component.find(Link)).toHaveLength(NavbarItems.length);
nav.forEach((n, i) => expect(n.getElement().props.children).toBe(NavbarItems[i]));
});
describe("when on collections url", () => {
it("should render PreviewNav component", () => {
const component = shallow(<NavBar {...withPreviewNavProps} user={authenticatedViewer} />);
expect(component.find("Connect(PreviewNav)")).toHaveLength(1);
});
});
});
});
| ONSdigital/florence | src/app/components/navbar/NavBar.test.js | JavaScript | mit | 5,855 |
'use strict';
module.exports = {
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/friend-around',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
}
}; | friend-around/friend_around | config/env/production.js | JavaScript | mit | 1,635 |
/* eslint-disable no-shadow */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { StyleSheet, RefreshControl, Share } from 'react-native';
import { ListItem } from 'react-native-elements';
import ActionSheet from 'react-native-actionsheet';
import Toast from 'react-native-simple-toast';
import {
ViewContainer,
LoadingRepositoryProfile,
RepositoryProfile,
MembersList,
SectionList,
ParallaxScroll,
LoadingUserListItem,
UserListItem,
IssueListItem,
LoadingMembersList,
LoadingModal,
TopicsList,
} from 'components';
import { translate, openURLInView } from 'utils';
import { colors, fonts } from 'config';
import {
getRepositoryInfo,
changeStarStatusRepo,
forkRepo,
subscribeToRepo,
unSubscribeToRepo,
} from '../repository.action';
const mapStateToProps = state => ({
username: state.auth.user.login,
locale: state.auth.locale,
repository: state.repository.repository,
contributors: state.repository.contributors,
issues: state.repository.issues,
starred: state.repository.starred,
forked: state.repository.forked,
subscribed: state.repository.subscribed,
hasRepoExist: state.repository.hasRepoExist,
hasReadMe: state.repository.hasReadMe,
isPendingRepository: state.repository.isPendingRepository,
isPendingContributors: state.repository.isPendingContributors,
isPendingIssues: state.repository.isPendingIssues,
isPendingCheckReadMe: state.repository.isPendingCheckReadMe,
isPendingCheckStarred: state.repository.isPendingCheckStarred,
isPendingFork: state.repository.isPendingFork,
isPendingTopics: state.repository.isPendingTopics,
isPendingSubscribe: state.repository.isPendingSubscribe,
topics: state.repository.topics,
error: state.repository.error,
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
getRepositoryInfo,
changeStarStatusRepo,
forkRepo,
subscribeToRepo,
unSubscribeToRepo,
},
dispatch
);
const styles = StyleSheet.create({
listTitle: {
color: colors.black,
...fonts.fontPrimary,
},
listContainerStyle: {
borderBottomColor: colors.greyLight,
borderBottomWidth: 1,
},
});
class Repository extends Component {
props: {
getRepositoryInfo: Function,
changeStarStatusRepo: Function,
forkRepo: Function,
// repositoryName: string,
repository: Object,
contributors: Array,
hasRepoExist: boolean,
hasReadMe: boolean,
issues: Array,
starred: boolean,
// forked: boolean,
isPendingRepository: boolean,
isPendingContributors: boolean,
isPendingCheckReadMe: boolean,
isPendingIssues: boolean,
isPendingCheckStarred: boolean,
isPendingFork: boolean,
isPendingTopics: boolean,
isPendingSubscribe: boolean,
// isPendingCheckForked: boolean,
navigation: Object,
username: string,
locale: string,
subscribed: boolean,
subscribeToRepo: Function,
unSubscribeToRepo: Function,
topics: Array,
error: Object,
};
state: {
refreshing: boolean,
};
constructor(props) {
super(props);
this.state = {
refreshing: false,
};
}
componentDidMount() {
const {
repository: repo,
repositoryUrl: repoUrl,
} = this.props.navigation.state.params;
this.props.getRepositoryInfo(repo ? repo.url : repoUrl);
}
componentDidUpdate() {
if (!this.props.hasRepoExist && this.props.error.message) {
Toast.showWithGravity(this.props.error.message, Toast.LONG, Toast.CENTER);
}
}
showMenuActionSheet = () => {
this.ActionSheet.show();
};
handlePress = index => {
const {
starred,
subscribed,
repository,
changeStarStatusRepo,
forkRepo,
navigation,
username,
} = this.props;
const showFork = repository.owner.login !== username;
if (index === 0) {
changeStarStatusRepo(repository.owner.login, repository.name, starred);
} else if (index === 1 && showFork) {
forkRepo(repository.owner.login, repository.name).then(json => {
navigation.navigate('Repository', { repository: json });
});
} else if ((index === 2 && showFork) || (index === 1 && !showFork)) {
const subscribeMethod = !subscribed
? this.props.subscribeToRepo
: this.props.unSubscribeToRepo;
subscribeMethod(repository.owner.login, repository.name);
} else if ((index === 3 && showFork) || (index === 2 && !showFork)) {
this.shareRepository(repository);
} else if ((index === 4 && showFork) || (index === 3 && !showFork)) {
openURLInView(repository.html_url);
}
};
fetchRepoInfo = () => {
const {
repository: repo,
repositoryUrl: repoUrl,
} = this.props.navigation.state.params;
this.setState({ refreshing: true });
this.props.getRepositoryInfo(repo ? repo.url : repoUrl).finally(() => {
this.setState({ refreshing: false });
});
};
shareRepository = repository => {
const { locale } = this.props;
const title = translate('repository.main.shareRepositoryTitle', locale, {
repoName: repository.name,
});
Share.share(
{
title,
message: translate('repository.main.shareRepositoryMessage', locale, {
repoName: repository.name,
repoUrl: repository.html_url,
}),
url: undefined,
},
{
dialogTitle: title,
excludedActivityTypes: [],
}
);
};
render() {
const {
repository,
contributors,
hasRepoExist,
hasReadMe,
issues,
topics,
starred,
locale,
isPendingRepository,
isPendingContributors,
isPendingCheckReadMe,
isPendingIssues,
isPendingCheckStarred,
isPendingFork,
isPendingSubscribe,
isPendingTopics,
navigation,
username,
subscribed,
} = this.props;
const { refreshing } = this.state;
const initalRepository = navigation.state.params.repository;
const pulls = issues.filter(issue => issue.hasOwnProperty('pull_request')); // eslint-disable-line no-prototype-builtins
const pureIssues = issues.filter(issue => {
// eslint-disable-next-line no-prototype-builtins
return !issue.hasOwnProperty('pull_request');
});
const openPulls = pulls.filter(pull => pull.state === 'open');
const openIssues = pureIssues.filter(issue => issue.state === 'open');
const showFork =
repository && repository.owner && repository.owner.login !== username;
const repositoryActions = [
starred
? translate('repository.main.unstarAction', locale)
: translate('repository.main.starAction', locale),
subscribed
? translate('repository.main.unwatchAction', locale)
: translate('repository.main.watchAction', locale),
translate('repository.main.shareAction', locale),
translate('common.openInBrowser', locale),
];
if (showFork) {
repositoryActions.splice(
1,
0,
translate('repository.main.forkAction', locale)
);
}
const loader = isPendingFork ? <LoadingModal /> : null;
const isSubscribed =
isPendingRepository || isPendingSubscribe ? false : subscribed;
const isStarred =
isPendingRepository || isPendingCheckStarred ? false : starred;
const showReadMe = !isPendingCheckReadMe && hasReadMe;
return (
<ViewContainer>
{loader}
<ParallaxScroll
renderContent={() => {
if (isPendingRepository && !initalRepository) {
return <LoadingRepositoryProfile locale={locale} />;
}
return (
<RepositoryProfile
repository={isPendingRepository ? initalRepository : repository}
starred={isStarred}
loading={isPendingRepository}
navigation={navigation}
subscribed={isSubscribed}
locale={locale}
/>
);
}}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={this.fetchRepoInfo}
/>
}
stickyTitle={repository.name}
showMenu={
hasRepoExist && !isPendingRepository && !isPendingCheckStarred
}
menuAction={this.showMenuActionSheet}
navigation={navigation}
navigateBack
>
{!isPendingTopics &&
topics.length > 0 && (
<TopicsList
title={translate('repository.main.topicsTitle', locale)}
topics={topics}
/>
)}
{initalRepository &&
!initalRepository.owner &&
isPendingRepository && (
<SectionList
title={translate('repository.main.ownerTitle', locale)}
>
<LoadingUserListItem />
</SectionList>
)}
{!(initalRepository && initalRepository.owner) &&
(repository && repository.owner) &&
!isPendingRepository && (
<SectionList
title={translate('repository.main.ownerTitle', locale)}
>
<UserListItem user={repository.owner} navigation={navigation} />
</SectionList>
)}
{hasRepoExist &&
initalRepository &&
initalRepository.owner && (
<SectionList
title={translate('repository.main.ownerTitle', locale)}
>
<UserListItem
user={initalRepository.owner}
navigation={navigation}
/>
</SectionList>
)}
{(isPendingRepository || isPendingContributors) && (
<LoadingMembersList
title={translate('repository.main.contributorsTitle', locale)}
/>
)}
{!isPendingContributors && (
<MembersList
title={translate('repository.main.contributorsTitle', locale)}
members={contributors}
noMembersMessage={translate(
'repository.main.noContributorsMessage',
locale
)}
navigation={navigation}
/>
)}
<SectionList title={translate('repository.main.sourceTitle', locale)}>
{showReadMe && (
<ListItem
title={translate('repository.main.readMe', locale)}
leftIcon={{
name: 'book',
color: colors.grey,
type: 'octicon',
}}
titleStyle={styles.listTitle}
containerStyle={styles.listContainerStyle}
onPress={() =>
navigation.navigate('ReadMe', {
repository,
})
}
underlayColor={colors.greyLight}
/>
)}
<ListItem
title={translate('repository.main.viewSource', locale)}
titleStyle={styles.listTitle}
containerStyle={styles.listContainerStyle}
leftIcon={{
name: 'code',
color: colors.grey,
type: 'octicon',
}}
onPress={() =>
navigation.navigate('RepositoryCodeList', {
title: translate('repository.codeList.title', locale),
topLevel: true,
})
}
underlayColor={colors.greyLight}
disabled={!hasRepoExist}
/>
</SectionList>
{!repository.fork &&
repository.has_issues && (
<SectionList
loading={isPendingIssues}
title={translate('repository.main.issuesTitle', locale)}
noItems={openIssues.length === 0}
noItemsMessage={
pureIssues.length === 0
? translate('repository.main.noIssuesMessage', locale)
: translate('repository.main.noOpenIssuesMessage', locale)
}
showButton
buttonTitle={
pureIssues.length > 0
? translate('repository.main.viewAllButton', locale)
: translate('repository.main.newIssueButton', locale)
}
buttonAction={() => {
if (pureIssues.length > 0) {
navigation.navigate('IssueList', {
title: translate('repository.issueList.title', locale),
type: 'issue',
issues: pureIssues,
});
} else {
navigation.navigate('NewIssue', {
title: translate('issue.newIssue.title', locale),
});
}
}}
>
{openIssues
.slice(0, 3)
.map(item => (
<IssueListItem
key={item.id}
type="issue"
issue={item}
navigation={navigation}
/>
))}
</SectionList>
)}
<SectionList
loading={isPendingIssues}
title={translate('repository.main.pullRequestTitle', locale)}
noItems={openPulls.length === 0}
noItemsMessage={
pulls.length === 0
? translate('repository.main.noPullRequestsMessage', locale)
: translate('repository.main.noOpenPullRequestsMessage', locale)
}
showButton={pulls.length > 0}
buttonTitle={translate('repository.main.viewAllButton', locale)}
buttonAction={() =>
navigation.navigate('PullList', {
title: translate('repository.pullList.title', locale),
type: 'pull',
issues: pulls,
})
}
>
{openPulls
.slice(0, 3)
.map(item => (
<IssueListItem
key={item.id}
type="pull"
issue={item}
navigation={navigation}
locale={locale}
/>
))}
</SectionList>
</ParallaxScroll>
<ActionSheet
ref={o => {
this.ActionSheet = o;
}}
title={translate('repository.main.repoActions', locale)}
options={[...repositoryActions, translate('common.cancel', locale)]}
cancelButtonIndex={repositoryActions.length}
onPress={this.handlePress}
/>
</ViewContainer>
);
}
}
export const RepositoryScreen = connect(mapStateToProps, mapDispatchToProps)(
Repository
);
| dyesseyumba/git-point | src/repository/screens/repository.screen.js | JavaScript | mit | 15,144 |
/**
* Presets of sentenceSeparator, clauseRegExp, wordRegExp, wordBoundaryRegExp, abbrRegExp
* for each languages.
*/
export default {
en: {
sentenceSeparator: /\n/g,
clauseRegExp: /[^,:"?!.]+/g,
wordRegExp: /[\w'\-.]+(?!\s*\.\s*$)/g,
wordBoundaryRegExp: /\b/,
abbrRegExp: /\.\.\./g,
},
ojp: {
sentenceSeparator: /(?:。|[\n\r]+|「|」|『|』)(?:\s+)?/g,
clauseRegExp: /[^、。「」『』]+/g,
wordRegExp: /\S+/g,
wordBoundaryRegExp: / /,
abbrRegExp: /〜/g,
},
};
| nodaguti/word-quiz-generator | src/constants/regexp-presets.js | JavaScript | mit | 522 |
'use strict';
describe("A suite", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
});
| Joseph22/Comments-TDD | app/tests/unit/jasmine-demo.js | JavaScript | mit | 149 |
/**
* Created by sasha on 18.11.13.
*/
| sashasashas11/test | lessons10.js | JavaScript | mit | 41 |
'use strict';
var BigNumber = require('bignumber.js');
var upperLimitMb = BigNumber(1024).times(16);
var min = function(x, y) { return x.comparedTo(y) < 0 ? x : y };
var quotaMb = function(invites) { return min(BigNumber(2048).plus(BigNumber(512).times(invites)), upperLimitMb) };
module.exports = {
cycles: {
$subscription: {
storageUsedMb: {},
invites: {}
}
},
values: {
storageQuotaMb: function(invites) { return quotaMb(invites) }
},
notifications: {
storage10pcntLeft: function(storageUsedMb, storageQuotaMb) {
return BigNumber(storageUsedMb).gt(BigNumber(storageQuotaMb).times(0.9))
},
storageOverUsed: function(storageUsedMb, storageQuotaMb) { return BigNumber(storageUsedMb).gt(storageQuotaMb) }
}
};
| KillingBilling/js-example-dropbox | src/basic.js | JavaScript | mit | 770 |
import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import * as views from 'views';
import * as admin from 'views/admin';
import { RouteConstants } from 'constants';
const {
HomeView,
LayoutView
} = views;
const {
AdminHomeView,
AdminLayoutView
} = admin;
export default class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Router history={createBrowserHistory()}>
<Route path='/' component={LayoutView}>
<IndexRoute component={HomeView} />
<Route path={RouteConstants.ADMIN} component={AdminLayoutView}>
<IndexRoute component={AdminHomeView} />
</Route>
</Route>
</Router>
);
}
}
| nitrog7/impulse | src/components/App.js | JavaScript | mit | 831 |
import Image from 'next/image'
import styles from '../styles/Home.module.scss'
import About from '../components/About/About'
import Header from '../components/Header/Header'
import Photo from '../components/Photo/Photo'
import { HomeContextProvider } from '../contexts/HomeContext/HomeContext'
import Events from '../components/Events/Events'
import Social from '../components/Social/Social'
import casualImg from '../public/casual.jpeg'
import scrumImg from '../public/scrum.jpeg'
import presentationImg from '../public/presentation.jpg'
import anniversaryImg from '../public/anniversary_cake.jpg'
import bgImg from '../public/bg.jpg'
export default function Home() {
return (
<HomeContextProvider>
<div className={styles.container}>
<div className={styles.bg}>
<Image
src={bgImg}
placeholder="blur"
layout="fill"
objectFit="cover"
objectPosition="center"
/>
</div>
<div className={styles.scrim} />
<Header />
<div className={styles.items}>
<About />
<Photo src={casualImg} />
<Photo src={scrumImg} />
<Photo src={presentationImg} />
<Events />
<Photo src={anniversaryImg} />
</div>
<Social />
</div>
</HomeContextProvider>
)
}
| qccoders/qccoders.org | pages/index.js | JavaScript | mit | 1,350 |
const SET_BLOGINFO = 'set/blog/info';
/* const SET_BLOGINFO_SUCCESS = 'set/blog/info/success';
const SET_BLOGINFO_FAIL = 'set/blog/info/fail'; */
const initialState = {
data: require('../../db/jsonData/blogGroup.json').blogGroupBox
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case SET_BLOGINFO:
return {
...state,
data: action.result
};
default:
return state;
}
}
| kahn1990/redux-project-example | src/redux/modules/blog.js | JavaScript | mit | 465 |
'use strict';
// MODULES //
var isNumber = require( 'validate.io-number-primitive' ),
isArrayLike = require( 'validate.io-array-like' ),
isTypedArrayLike = require( 'validate.io-typed-array-like' ),
isMatrixLike = require( 'validate.io-matrix-like' ),
ctors = require( 'compute-array-constructors' ),
matrix = require( 'dstructs-matrix' ),
validate = require( './validate.js' );
// FUNCTIONS //
var pdf1 = require( './number.js' ),
pdf2 = require( './array.js' ),
pdf3 = require( './accessor.js' ),
pdf4 = require( './deepset.js' ),
pdf5 = require( './matrix.js' ),
pdf6 = require( './typedarray.js' );
// PDF //
/**
* FUNCTION: pdf( x[, opts] )
* Evaluates the probability density function (PDF) for a Laplace distribution.
*
* @param {Number|Number[]|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Matrix} x - input value
* @param {Object} [opts] - function options
* @param {Number} [opts.mu=0] - location parameter
* @param {Number} [opts.b=1] - scale parameter
* @param {Boolean} [opts.copy=true] - boolean indicating if the function should return a new data structure
* @param {Function} [opts.accessor] - accessor function for accessing array values
* @param {String} [opts.path] - deep get/set key path
* @param {String} [opts.sep="."] - deep get/set key path separator
* @param {String} [opts.dtype="float64"] - output data type
* @returns {Number|Number[]|Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array|Matrix} evaluated PDF
*/
function pdf( x, options ) {
/* jshint newcap:false */
var opts = {},
ctor,
err,
out,
dt,
d;
if ( arguments.length > 1 ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
opts.mu = typeof opts.mu !== 'undefined' ? opts.mu : 0;
opts.b = typeof opts.b !== 'undefined' ? opts.b : 1;
if ( isNumber( x ) ) {
return pdf1( x, opts.mu, opts.b );
}
if ( isMatrixLike( x ) ) {
if ( opts.copy !== false ) {
dt = opts.dtype || 'float64';
ctor = ctors( dt );
if ( ctor === null ) {
throw new Error( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' );
}
// Create an output matrix:
d = new ctor( x.length );
out = matrix( d, x.shape, dt );
} else {
out = x;
}
return pdf5( out, x, opts.mu, opts.b );
}
if ( isTypedArrayLike( x ) ) {
if ( opts.copy === false ) {
out = x;
} else {
dt = opts.dtype || 'float64';
ctor = ctors( dt );
if ( ctor === null ) {
throw new Error( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + dt + '`.' );
}
out = new ctor( x.length );
}
return pdf6( out, x, opts.mu, opts.b );
}
if ( isArrayLike( x ) ) {
// Handle deepset first...
if ( opts.path ) {
opts.sep = opts.sep || '.';
return pdf4( x, opts.mu, opts.b, opts.path, opts.sep );
}
// Handle regular and accessor arrays next...
if ( opts.copy === false ) {
out = x;
}
else if ( opts.dtype ) {
ctor = ctors( opts.dtype );
if ( ctor === null ) {
throw new TypeError( 'pdf()::invalid option. Data type option does not have a corresponding array constructor. Option: `' + opts.dtype + '`.' );
}
out = new ctor( x.length );
}
else {
out = new Array( x.length );
}
if ( opts.accessor ) {
return pdf3( out, x, opts.mu, opts.b, opts.accessor );
}
return pdf2( out, x, opts.mu, opts.b );
}
return NaN;
} // end FUNCTION pdf()
// EXPORTS //
module.exports = pdf;
| distributions-io/laplace-pdf | lib/index.js | JavaScript | mit | 3,613 |
'use strict';
module.exports = {
port: 443,
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://root:root@ds125481.mlab.com:25481/clubs-manager',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.min.js',
'public/lib/angular-animate/angular-animate.min.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'https://localhost:443/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
| DowntoTres/finalproj | config/env/secure.js | JavaScript | mit | 1,994 |
/* global _, angular */
'use strict';
function myChildrenCtrl ($scope, $state, $translate, ownProfile, cdUsersService) {
$scope.parentProfileData = ownProfile.data;
$scope.tabs = [];
function loadChildrenTabs () {
$scope.tabs = [];
cdUsersService.loadChildrenForUser($scope.parentProfileData.userId, function (children) {
$scope.children = _.sortBy(children, [
function (child) {
return child.name.toLowerCase();
}
]);
$scope.tabs = $scope.children.map(function (child) {
return {
state: 'my-children.child',
stateParams: {id: child.userId},
tabImage: '/api/2.0/profiles/' + child.id + '/avatar_img',
tabTitle: child.name,
tabSubTitle: child.alias
};
});
$scope.tabs.push({
state: 'my-children.add',
tabImage: '/img/avatars/avatar.png',
tabTitle: $translate.instant('Add Child')
});
});
}
loadChildrenTabs();
$scope.$on('$stateChangeStart', function (e, toState, params) {
if (toState.name === 'my-children.child') {
var childLoaded = _.some($scope.children, function (child) {
return child.userId === params.id;
});
if (!childLoaded) {
loadChildrenTabs();
}
}
});
}
angular.module('cpZenPlatform')
.controller('my-children-controller', ['$scope', '$state', '$translate', 'ownProfile', 'cdUsersService', myChildrenCtrl]);
| CoderDojo/cp-zen-platform | web/public/js/controllers/my-children-controller.js | JavaScript | mit | 1,458 |
angular.module('app')
.filter('date', function(){
'use strict';
return function(timestamp, format){
return timestamp ? moment(timestamp).format(format ? format : 'll') : '<date>';
};
})
.filter('datetime', function(){
'use strict';
return function(timestamp, format){
return timestamp ? moment(timestamp).format(format ? format : 'D MMM YYYY, HH:mm:ss') : '<datetime>';
};
})
.filter('time', function(){
'use strict';
return function(timestamp, format){
return timestamp ? moment(timestamp).format(format ? format : 'LT') : '<time>';
};
})
.filter('humanTime', function(){
'use strict';
return function(timestamp){
return timestamp ? moment(timestamp).fromNow(true) : '<humanTime>';
};
})
.filter('duration', function(){
'use strict';
return function(seconds, humanize){
if(seconds || seconds === 0){
if(humanize){
return moment.duration(seconds, 'seconds').humanize();
} else {
var prefix = -60 < seconds && seconds < 60 ? '00:' : '';
return prefix + moment.duration(seconds, 'seconds').format('hh:mm:ss');
}
} else {
console.warn('Unable to format duration', seconds);
return '<duration>';
}
};
})
.filter('mynumber', function($filter){
'use strict';
return function(number, round){
var mul = Math.pow(10, round ? round : 0);
return $filter('number')(Math.round(number*mul)/mul);
};
})
.filter('rating', function($filter){
'use strict';
return function(rating, max, withText){
var stars = rating ? new Array(Math.floor(rating)+1).join('★') : '';
var maxStars = max ? new Array(Math.floor(max)-Math.floor(rating)+1).join('☆') : '';
var text = withText ? ' ('+$filter('mynumber')(rating, 1)+' / '+$filter('mynumber')(max, 1)+')' : '';
return stars+maxStars+text;
};
});
| loicknuchel/angular-starter | app/scripts/filters.js | JavaScript | mit | 1,829 |
import MPopper from '../m-popper.vue';
import pick from 'lodash/pick';
/**
* 默认显示一个按钮,hover 上去有提示
*/
export const UIconTooltip = {
name: 'u-icon-tooltip',
props: {
type: { type: String, default: 'info' }, // 按钮名称
size: { type: String, default: 'normal' }, // 提示大小
content: String,
trigger: { type: String, default: 'hover' },
placement: { type: String, default: 'bottom' },
...pick(MPopper.props, [
'opened',
'reference',
'hideDelay',
'boundariesElement',
'followCursor',
'offset',
'disabled',
]),
},
};
export default UIconTooltip;
| vusion/proto-ui | src/components/u-icon-tooltip.vue/index.js | JavaScript | mit | 733 |
'use strict';
var
path = require('path'),
express = require('express'),
errors = require('./errors'),
debug = require('debug')('express-toybox:logger'),
DEBUG = debug.enabled;
/**
* logger middleware using "morgan" or "debug".
*
* @param {*|String} options or log format.
* @param {Number|Boolean} [options.buffer]
* @param {Boolean} [options.immediate]
* @param {Function} [options.skip]
* @param {*} [options.stream]
* @param {String} [options.format='combined'] log format. "combined", "common", "dev", "short", "tiny" or "default".
* @param {String} [options.file] file to emit log.
* @param {String} [options.debug] namespace for tj's debug namespace to emit log.
* @returns {Function} connect/express middleware function
*/
function logger(options) {
DEBUG && debug('configure http logger middleware', options);
var format;
if (typeof options === 'string') {
format = options;
options = {};
} else {
format = options.format || 'combined';
delete options.format;
}
if (options.debug) {
try {
return require('morgan-debug')(options.debug, format, options);
} catch (e) {
console.error('**fatal** failed to configure logger with debug', e);
return process.exit(2);
}
}
if (options.file) {
try {
var file = path.resolve(process.cwd(), options.file);
// replace stream options with stream object
delete options.file;
options.stream = require('fs').createWriteStream(file, {flags: 'a'});
} catch (e) {
console.error('**fatal** failed to configure logger with file stream', e);
return process.exit(2);
}
}
console.warn('**fallback** use default logger middleware');
return require('morgan')(format, options);
}
module.exports = logger;
| iolo/express-toybox | logger.js | JavaScript | mit | 1,903 |
/* eslint-disable new-cap */
/* eslint-disable no-console */
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./server/routes');
const config = require('./server/config');
const app = express();
const apiRouter = express.Router();
const env = process.env.NODE_ENV;
if (env === 'test') {
config.database = config.test_database;
config.port = 8080;
}
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes(apiRouter));
app.use((req, res, next) => {
res.setHeader('Access-Coontrol-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type');
next();
});
mongoose.connect(config.database, (err) => {
if (err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
app.listen(config.port, (err) => {
if (err) {
console.log('Connection error', err);
} else {
console.log('Listening on port:', config.port);
}
});
module.exports = app;
| andela-skieha/document-management-system | index.js | JavaScript | mit | 1,227 |
/* globals describe, it */
import Compiler from '../src/transpiler/compiler';
import assert from 'assert';
import fs from 'fs';
function compare(source, target) {
const compiler = new Compiler(source);
assert.equal(target, compiler.compiled);
}
describe('Transpiler', function() {
it('should transpile a empty program', function() {
compare('', '');
});
it('should transpile a declaration with no value', function() {
compare('politico salario.,', 'var salario;');
});
it('should transpile a declaration with int value', function() {
compare('politico salario = 100000.,', 'var salario = 100000;');
});
it('should transpile a declaration with string value', function() {
compare('politico salario = \'salario\'.,', 'var salario = \'salario\';');
});
it('should transpile a declaration with boolean value', function() {
compare('politico salario = true.,', 'var salario = true;');
compare('politico salario = false.,', 'var salario = false;');
});
it('should transpile a attribution of an expression', function() {
compare('salario = salario + i.,', 'salario = salario + i;');
});
it('should transpile a print with no value', function() {
compare('midiaGolpista().,', 'console.log();');
});
it('should transpile a print with string', function() {
compare('midiaGolpista(\'Número abaixo de 100.000: \').,', 'console.log(\'Número abaixo de 100.000: \');');
});
it('should transpile a print with expression', function() {
compare('midiaGolpista(\'Número abaixo de 100.000: \' + 1000).,', 'console.log(\'Número abaixo de 100.000: \' + 1000);');
});
it('should transpile a print with multiple values', function() {
compare('midiaGolpista(\'Número abaixo de 100.000: \', 1000).,', 'console.log(\'Número abaixo de 100.000: \', 1000);');
});
it('should transpile a empty loop', function() {
compare('euViVoceVeja (i = 0., i < 10000., i++) {}', 'for (i = 0; i < 10000; i++) {\n}');
});
it('should transpile a empty if', function() {
compare('porque (salario < 100000) {}', 'if (salario < 100000) {\n}');
});
it('should transpile a empty if with empty else', function() {
compare('porque (salario < 100000) {} casoContrario {}', 'if (salario < 100000) {\n}');
});
it('should transpile expression `1 + 1`', function() {
compare('1 + 1', '1 + 1;');
});
it('should transpile expression `1 + 4 / 2`', function() {
compare('1 + 4 / 2', '1 + 4 / 2;');
});
it('should transpile expression `4 / 2 + 1`', function() {
compare('4 / 2 + 1', '4 / 2 + 1;');
});
it('should transpile expression `4 / 2 + 1 * 3 - 2`', function() {
compare('4 / 2 + 1 * 3 - 2', '4 / 2 + 1 * 3 - 2;');
});
it('should transpile example 1', function() {
const source = fs.readFileSync('Example - Loop.dilmalang').toString();
const target = fs.readFileSync('Example - Loop.js').toString().replace(/\n$/, '');
compare(source, target);
});
});
| rafaelks/Dilmalang | test/transpiler.js | JavaScript | mit | 2,901 |
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"2":"8 C D e K I N J"},C:{"2":"0 1 2 3 4 5 7 9 gB BB F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB aB ZB"},D:{"2":"0 1 2 3 4 5 7 8 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB"},E:{"1":"6 E A B C D XB YB p bB","2":"4 F L H G SB KB UB VB WB"},F:{"2":"0 1 2 3 5 6 7 E B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z cB dB eB fB p AB hB"},G:{"1":"D oB pB qB rB sB tB uB vB","2":"G KB iB FB kB lB MB nB"},H:{"2":"wB"},I:{"2":"BB F O xB yB zB 0B FB 1B 2B"},J:{"2":"H A"},K:{"2":"6 A B C M p AB"},L:{"2":"LB"},M:{"2":"O"},N:{"2":"A B"},O:{"2":"3B"},P:{"2":"F 4B 5B 6B 7B 8B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"2":"BC"}},B:7,C:"selector list argument of :nth-child and :nth-last-child CSS pseudo-classes"};
| Dans-labs/dariah | client/node_modules/caniuse-lite/data/features/css-nth-child-of.js | JavaScript | mit | 960 |
/**
*
* @description Convert attribute value to boolean value
* @param attribute
* @return {Boolean}
* @private
*/
jDoc.engines.OXML.prototype._attributeToBoolean = function (attribute) {
return (!!attribute && (attribute.value == 'true' || attribute.value == '1' || attribute.value == 'on'));
}; | bardt/jDoc | src/engines/OXML/reader/private/_attributeToBoolean.js | JavaScript | mit | 315 |
/*
Copyright (c) 2014 Dominik Moritz
This file is part of the leaflet locate control. It is licensed under the MIT license.
You can find the project at: https://github.com/domoritz/leaflet-locatecontrol
*/
L.Control.Locate = L.Control.extend({
options: {
position: 'topleft',
drawCircle: true,
follow: false, // follow with zoom and pan the user's location
stopFollowingOnDrag: false, // if follow is true, stop following when map is dragged (deprecated)
// range circle
circleStyle: {
color: '#136AEC',
fillColor: '#136AEC',
fillOpacity: 0.15,
weight: 2,
opacity: 0.5
},
// inner marker
markerStyle: {
color: '#136AEC',
fillColor: '#2A93EE',
fillOpacity: 0.7,
weight: 2,
opacity: 0.9,
radius: 5
},
// changes to range circle and inner marker while following
// it is only necessary to provide the things that should change
followCircleStyle: {},
followMarkerStyle: {
//color: '#FFA500',
//fillColor: '#FFB000'
},
circlePadding: [0, 0],
metric: true,
onLocationError: function(err) {
// this event is called in case of any location error
// that is not a time out error.
alert(err.message);
},
onLocationOutsideMapBounds: function(context) {
// this event is repeatedly called when the location changes
alert(context.options.strings.outsideMapBoundsMsg);
},
setView: true, // automatically sets the map view to the user's location
strings: {
title: "Show me where I am",
popup: "You are within {distance} {unit} from this point",
outsideMapBoundsMsg: "You seem located outside the boundaries of the map"
},
locateOptions: {
maxZoom: Infinity,
watch: true // if you overwrite this, visualization cannot be updated
}
},
onAdd: function (map) {
var container = L.DomUtil.create('div',
'leaflet-control-locate leaflet-bar leaflet-control');
var self = this;
this._layer = new L.LayerGroup();
this._layer.addTo(map);
this._event = undefined;
this._locateOptions = this.options.locateOptions;
L.extend(this._locateOptions, this.options.locateOptions);
L.extend(this._locateOptions, {
setView: false // have to set this to false because we have to
// do setView manually
});
// extend the follow marker style and circle from the normal style
var tmp = {};
L.extend(tmp, this.options.markerStyle, this.options.followMarkerStyle);
this.options.followMarkerStyle = tmp;
tmp = {};
L.extend(tmp, this.options.circleStyle, this.options.followCircleStyle);
this.options.followCircleStyle = tmp;
var link = L.DomUtil.create('a', 'leaflet-bar-part leaflet-bar-part-single', container);
link.href = '#';
link.title = this.options.strings.title;
L.DomEvent
.on(link, 'click', L.DomEvent.stopPropagation)
.on(link, 'click', L.DomEvent.preventDefault)
.on(link, 'click', function() {
if (self._active && (self._event === undefined || map.getBounds().contains(self._event.latlng) || !self.options.setView ||
isOutsideMapBounds())) {
stopLocate();
} else {
locate();
}
})
.on(link, 'dblclick', L.DomEvent.stopPropagation);
var locate = function () {
if (self.options.setView) {
self._locateOnNextLocationFound = true;
}
if(!self._active) {
map.locate(self._locateOptions);
}
self._active = true;
if (self.options.follow) {
startFollowing();
}
if (!self._event) {
L.DomUtil.addClass(self._container, "requesting");
L.DomUtil.removeClass(self._container, "active");
L.DomUtil.removeClass(self._container, "following");
} else {
visualizeLocation();
}
};
var onLocationFound = function (e) {
// no need to do anything if the location has not changed
if (self._event &&
(self._event.latlng.lat === e.latlng.lat &&
self._event.latlng.lng === e.latlng.lng &&
self._event.accuracy === e.accuracy)) {
return;
}
if (!self._active) {
return;
}
self._event = e;
if (self.options.follow && self._following) {
self._locateOnNextLocationFound = true;
}
visualizeLocation();
};
var startFollowing = function() {
map.fire('startfollowing');
self._following = true;
if (self.options.stopFollowingOnDrag) {
map.on('dragstart', stopFollowing);
}
};
var stopFollowing = function() {
map.fire('stopfollowing');
self._following = false;
if (self.options.stopFollowingOnDrag) {
map.off('dragstart', stopFollowing);
}
visualizeLocation();
};
var isOutsideMapBounds = function () {
if (self._event === undefined)
return false;
return map.options.maxBounds &&
!map.options.maxBounds.contains(self._event.latlng);
};
var visualizeLocation = function() {
if (self._event.accuracy === undefined)
self._event.accuracy = 0;
var radius = self._event.accuracy;
if (self._locateOnNextLocationFound) {
if (isOutsideMapBounds()) {
self.options.onLocationOutsideMapBounds(self);
} else {
map.fitBounds(self._event.bounds, {
padding: self.options.circlePadding,
maxZoom: self._locateOptions.maxZoom
});
}
self._locateOnNextLocationFound = false;
}
// circle with the radius of the location's accuracy
var style, o;
if (self.options.drawCircle) {
if (self._following) {
style = self.options.followCircleStyle;
} else {
style = self.options.circleStyle;
}
if (!self._circle) {
self._circle = L.circle(self._event.latlng, radius, style)
.addTo(self._layer);
} else {
self._circle.setLatLng(self._event.latlng).setRadius(radius);
for (o in style) {
self._circle.options[o] = style[o];
}
}
}
var distance, unit;
if (self.options.metric) {
distance = radius.toFixed(0);
unit = "meters";
} else {
distance = (radius * 3.2808399).toFixed(0);
unit = "feet";
}
// small inner marker
var mStyle;
if (self._following) {
mStyle = self.options.followMarkerStyle;
} else {
mStyle = self.options.markerStyle;
}
var t = self.options.strings.popup;
if (!self._circleMarker) {
self._circleMarker = L.circleMarker(self._event.latlng, mStyle)
.bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
.addTo(self._layer);
} else {
self._circleMarker.setLatLng(self._event.latlng)
.bindPopup(L.Util.template(t, {distance: distance, unit: unit}))
._popup.setLatLng(self._event.latlng);
for (o in mStyle) {
self._circleMarker.options[o] = mStyle[o];
}
}
if (!self._container)
return;
if (self._following) {
L.DomUtil.removeClass(self._container, "requesting");
L.DomUtil.addClass(self._container, "active");
L.DomUtil.addClass(self._container, "following");
} else {
L.DomUtil.removeClass(self._container, "requesting");
L.DomUtil.addClass(self._container, "active");
L.DomUtil.removeClass(self._container, "following");
}
};
var resetVariables = function() {
self._active = false;
self._locateOnNextLocationFound = self.options.setView;
self._following = false;
};
resetVariables();
var stopLocate = function() {
map.stopLocate();
map.off('dragstart', stopFollowing);
L.DomUtil.removeClass(self._container, "requesting");
L.DomUtil.removeClass(self._container, "active");
L.DomUtil.removeClass(self._container, "following");
resetVariables();
self._layer.clearLayers();
self._circleMarker = undefined;
self._circle = undefined;
};
var onLocationError = function (err) {
// ignore time out error if the location is watched
if (err.code == 3 && this._locateOptions.watch) {
return;
}
stopLocate();
self.options.onLocationError(err);
};
// event hooks
map.on('locationfound', onLocationFound, self);
map.on('locationerror', onLocationError, self);
// make locate functions available to outside world
this.locate = locate;
this.stopLocate = stopLocate;
this.stopFollowing = stopFollowing;
return container;
}
});
L.Map.addInitHook(function () {
if (this.options.locateControl) {
this.locateControl = L.control.locate();
this.addControl(this.locateControl);
}
});
L.control.locate = function (options) {
return new L.Control.Locate(options);
};
| codeforboston/willtheytow.me | js/L.Control.Locate.js | JavaScript | mit | 10,603 |
import Component from '@glimmer/component';
import {action} from '@ember/object';
export default class KoenigMenuContentComponent extends Component {
@action
scrollIntoView(element, [doScroll]) {
if (doScroll) {
element.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
});
}
}
}
| TryGhost/Ghost-Admin | lib/koenig-editor/addon/components/koenig-menu-content.js | JavaScript | mit | 369 |
'use strict';var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var jit_proto_change_detector_1 = require('./jit_proto_change_detector');
var pregen_proto_change_detector_1 = require('./pregen_proto_change_detector');
var proto_change_detector_1 = require('./proto_change_detector');
var iterable_differs_1 = require('./differs/iterable_differs');
var default_iterable_differ_1 = require('./differs/default_iterable_differ');
var keyvalue_differs_1 = require('./differs/keyvalue_differs');
var default_keyvalue_differ_1 = require('./differs/default_keyvalue_differ');
var interfaces_1 = require('./interfaces');
var di_1 = require('angular2/di');
var collection_1 = require('angular2/src/core/facade/collection');
var lang_1 = require('angular2/src/core/facade/lang');
var ast_1 = require('./parser/ast');
exports.ASTWithSource = ast_1.ASTWithSource;
exports.AST = ast_1.AST;
exports.AstTransformer = ast_1.AstTransformer;
exports.PropertyRead = ast_1.PropertyRead;
exports.LiteralArray = ast_1.LiteralArray;
exports.ImplicitReceiver = ast_1.ImplicitReceiver;
var lexer_1 = require('./parser/lexer');
exports.Lexer = lexer_1.Lexer;
var parser_1 = require('./parser/parser');
exports.Parser = parser_1.Parser;
var locals_1 = require('./parser/locals');
exports.Locals = locals_1.Locals;
var exceptions_1 = require('./exceptions');
exports.DehydratedException = exceptions_1.DehydratedException;
exports.ExpressionChangedAfterItHasBeenCheckedException = exceptions_1.ExpressionChangedAfterItHasBeenCheckedException;
exports.ChangeDetectionError = exceptions_1.ChangeDetectionError;
var interfaces_2 = require('./interfaces');
exports.ChangeDetection = interfaces_2.ChangeDetection;
exports.ChangeDetectorDefinition = interfaces_2.ChangeDetectorDefinition;
exports.DebugContext = interfaces_2.DebugContext;
exports.ChangeDetectorGenConfig = interfaces_2.ChangeDetectorGenConfig;
var constants_1 = require('./constants');
exports.ChangeDetectionStrategy = constants_1.ChangeDetectionStrategy;
var proto_change_detector_2 = require('./proto_change_detector');
exports.DynamicProtoChangeDetector = proto_change_detector_2.DynamicProtoChangeDetector;
var binding_record_1 = require('./binding_record');
exports.BindingRecord = binding_record_1.BindingRecord;
exports.BindingTarget = binding_record_1.BindingTarget;
var directive_record_1 = require('./directive_record');
exports.DirectiveIndex = directive_record_1.DirectiveIndex;
exports.DirectiveRecord = directive_record_1.DirectiveRecord;
var dynamic_change_detector_1 = require('./dynamic_change_detector');
exports.DynamicChangeDetector = dynamic_change_detector_1.DynamicChangeDetector;
var change_detector_ref_1 = require('./change_detector_ref');
exports.ChangeDetectorRef = change_detector_ref_1.ChangeDetectorRef;
var iterable_differs_2 = require('./differs/iterable_differs');
exports.IterableDiffers = iterable_differs_2.IterableDiffers;
var keyvalue_differs_2 = require('./differs/keyvalue_differs');
exports.KeyValueDiffers = keyvalue_differs_2.KeyValueDiffers;
var change_detection_util_1 = require('./change_detection_util');
exports.WrappedValue = change_detection_util_1.WrappedValue;
/**
* Structural diffing for `Object`s and `Map`s.
*/
exports.keyValDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_keyvalue_differ_1.DefaultKeyValueDifferFactory())]);
/**
* Structural diffing for `Iterable` types such as `Array`s.
*/
exports.iterableDiff = lang_1.CONST_EXPR([lang_1.CONST_EXPR(new default_iterable_differ_1.DefaultIterableDifferFactory())]);
exports.defaultIterableDiffers = lang_1.CONST_EXPR(new iterable_differs_1.IterableDiffers(exports.iterableDiff));
exports.defaultKeyValueDiffers = lang_1.CONST_EXPR(new keyvalue_differs_1.KeyValueDiffers(exports.keyValDiff));
/**
* Map from {@link ChangeDetectorDefinition#id} to a factory method which takes a
* {@link Pipes} and a {@link ChangeDetectorDefinition} and generates a
* {@link ProtoChangeDetector} associated with the definition.
*/
// TODO(kegluneq): Use PregenProtoChangeDetectorFactory rather than Function once possible in
// dart2js. See https://github.com/dart-lang/sdk/issues/23630 for details.
exports.preGeneratedProtoDetectors = {};
/**
* Implements change detection using a map of pregenerated proto detectors.
*/
var PreGeneratedChangeDetection = (function (_super) {
__extends(PreGeneratedChangeDetection, _super);
function PreGeneratedChangeDetection(config, protoChangeDetectorsForTest) {
_super.call(this);
this._dynamicChangeDetection = new DynamicChangeDetection();
this._protoChangeDetectorFactories = lang_1.isPresent(protoChangeDetectorsForTest) ?
protoChangeDetectorsForTest :
exports.preGeneratedProtoDetectors;
this._genConfig =
lang_1.isPresent(config) ? config : new interfaces_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), lang_1.assertionsEnabled(), false);
}
PreGeneratedChangeDetection.isSupported = function () { return pregen_proto_change_detector_1.PregenProtoChangeDetector.isSupported(); };
PreGeneratedChangeDetection.prototype.getProtoChangeDetector = function (id, definition) {
if (collection_1.StringMapWrapper.contains(this._protoChangeDetectorFactories, id)) {
return collection_1.StringMapWrapper.get(this._protoChangeDetectorFactories, id)(definition);
}
return this._dynamicChangeDetection.getProtoChangeDetector(id, definition);
};
Object.defineProperty(PreGeneratedChangeDetection.prototype, "genConfig", {
get: function () { return this._genConfig; },
enumerable: true,
configurable: true
});
Object.defineProperty(PreGeneratedChangeDetection.prototype, "generateDetectors", {
get: function () { return true; },
enumerable: true,
configurable: true
});
PreGeneratedChangeDetection = __decorate([
di_1.Injectable(),
__metadata('design:paramtypes', [interfaces_1.ChangeDetectorGenConfig, Object])
], PreGeneratedChangeDetection);
return PreGeneratedChangeDetection;
})(interfaces_1.ChangeDetection);
exports.PreGeneratedChangeDetection = PreGeneratedChangeDetection;
/**
* Implements change detection that does not require `eval()`.
*
* This is slower than {@link JitChangeDetection}.
*/
var DynamicChangeDetection = (function (_super) {
__extends(DynamicChangeDetection, _super);
function DynamicChangeDetection(config) {
_super.call(this);
this._genConfig =
lang_1.isPresent(config) ? config : new interfaces_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), lang_1.assertionsEnabled(), false);
}
DynamicChangeDetection.prototype.getProtoChangeDetector = function (id, definition) {
return new proto_change_detector_1.DynamicProtoChangeDetector(definition);
};
Object.defineProperty(DynamicChangeDetection.prototype, "genConfig", {
get: function () { return this._genConfig; },
enumerable: true,
configurable: true
});
Object.defineProperty(DynamicChangeDetection.prototype, "generateDetectors", {
get: function () { return true; },
enumerable: true,
configurable: true
});
DynamicChangeDetection = __decorate([
di_1.Injectable(),
__metadata('design:paramtypes', [interfaces_1.ChangeDetectorGenConfig])
], DynamicChangeDetection);
return DynamicChangeDetection;
})(interfaces_1.ChangeDetection);
exports.DynamicChangeDetection = DynamicChangeDetection;
/**
* Implements faster change detection by generating source code.
*
* This requires `eval()`. For change detection that does not require `eval()`, see
* {@link DynamicChangeDetection} and {@link PreGeneratedChangeDetection}.
*/
var JitChangeDetection = (function (_super) {
__extends(JitChangeDetection, _super);
function JitChangeDetection(config) {
_super.call(this);
this._genConfig =
lang_1.isPresent(config) ? config : new interfaces_1.ChangeDetectorGenConfig(lang_1.assertionsEnabled(), lang_1.assertionsEnabled(), false);
}
JitChangeDetection.isSupported = function () { return jit_proto_change_detector_1.JitProtoChangeDetector.isSupported(); };
JitChangeDetection.prototype.getProtoChangeDetector = function (id, definition) {
return new jit_proto_change_detector_1.JitProtoChangeDetector(definition);
};
Object.defineProperty(JitChangeDetection.prototype, "genConfig", {
get: function () { return this._genConfig; },
enumerable: true,
configurable: true
});
Object.defineProperty(JitChangeDetection.prototype, "generateDetectors", {
get: function () { return true; },
enumerable: true,
configurable: true
});
JitChangeDetection = __decorate([
di_1.Injectable(),
__metadata('design:paramtypes', [interfaces_1.ChangeDetectorGenConfig])
], JitChangeDetection);
return JitChangeDetection;
})(interfaces_1.ChangeDetection);
exports.JitChangeDetection = JitChangeDetection;
//# sourceMappingURL=change_detection.js.map | rehnen/potato | node_modules/angular2/src/core/change_detection/change_detection.js | JavaScript | mit | 10,244 |
/**
* Created by hbzhang on 8/7/15.
*/
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Widget = mongoose.model('Widget'),
Upload = mongoose.model('Upload'),
_ = require('lodash'),
grid = require('gridfs-stream');
/**
* Find widget by id
*/
exports.widget = function(req, res, next, id) {
//console.log(id);
Widget.load(id, function(err, widget) {
if (err) return next(err);
if (!widget) return next(new Error('Failed to load the widget' + id));
req.widget = widget;
next();
});
};
exports.view = function(req, res) {
//res.jsonp(req.class_);
Widget.findOne({_id: req.param('widgetID') }, function (err, widget){
res.jsonp(widget);
console.log(widget);
});
};
/**
* Create a widget
*/
exports.create = function(req, res) {
//console.log(req.body);
var widget = new Widget(req.body);
//console.log(form);
/* var e = dateValidation(class_);
if (e !== '') {
console.log(e);
return res.jsonp(500, {
error: e
});
}
*/
widget.save(function(err) {
if (err) {
console.log(err);
return res.jsonp(500, {error: 'cannot save the widget'});
}
res.jsonp(widget);
});
};
/**
* List all widgets
*/
exports.all = function(req, res) {
var populateQuery = [{path:'widgetcreator'}];
Widget.find({}, '_id widgetbasicinformation widgetformbuilder widgetroles').populate(populateQuery).exec(function(err, widgets) {
if (err) {
return res.jsonp(500, {
error: 'Cannot list all the widgets'
});
}
res.jsonp(widgets);
});
};
/**
* Delete a widget
*/
exports.destroy = function(req, res) {
//var event = req.event;
//console.log(req.param('eventID'));
Widget.remove({ _id: req.param('widgetID') }, function(err) {
if (err) {
return res.jsonp(500, {
error: 'Cannot delete the widget'
});
}
res.jsonp({ _id: req.param('widgetID') });
});
};
/**
* Update a widget
*/
exports.update = function(req, res) {
Widget.findOne({_id: req.param('widgetID') }, function (err, widget){
widget.widgetbasicinformation = req.param('widgetbasicinformation');
widget.widgetformbuilder = req.param('widgetformbuilder');
widget.widgetcreator = req.param('widgetcreator');
widget.widgetroles = req.param('widgetroles');
widget.save();
res.jsonp(widget);
});
};
| hbzhang/me | me/packages/custom/admin/server/controllers/main/adminwidget.js | JavaScript | mit | 2,577 |
const sensor = require('node-dht-sensor');
const logger = require('../logging/Logger');
/**
* Reads pin 4 of the raspberry PI to obtain temperature and humidity information.
* @return {Promise} A promise that will resolve with the results. In the
* case where there was an error reading, will return a zero filled object,
* with an additional error field.
* { temperature: Number,
* humidity: Number,
* error: Error|undefined }
*/
exports.getHumidityTemperature = function() {
return new Promise( (resolve, reject) => {
sensor.read(22, 4, (err, temperature, humidity) => {
if(err) {
logger.error("Could not read from the DHT sensor. " + err);
return resolve({
temperature: 0,
humidity: 0,
error: err});
}
resolve({
temperature: temperature * 1.8 + 32,
humidity: humidity});
});
});
}
| malbanese/hydroponic-monitoring-system | src/sensor/HumidTemp.js | JavaScript | mit | 943 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const React = require('react');
const Scheduler = require('scheduler');
import type {Direction} from '../useLoadMoreFunction';
import type {OperationDescriptor, Variables} from 'relay-runtime';
const {useEffect, useTransition, useMemo, useState} = React;
const TestRenderer = require('react-test-renderer');
const invariant = require('invariant');
const useBlockingPaginationFragmentOriginal = require('../useBlockingPaginationFragment');
const ReactRelayContext = require('react-relay/ReactRelayContext');
const {
ConnectionHandler,
FRAGMENT_OWNER_KEY,
FRAGMENTS_KEY,
ID_KEY,
createOperationDescriptor,
graphql,
getRequest,
getFragment,
} = require('relay-runtime');
const {createMockEnvironment} = require('relay-test-utils');
// TODO: We're switching the tuple order of useTransition so for ~1 day we
// need to disable this test so we can flip in www then fbsource.
const TEMPORARY_SKIP_WHILE_REFACTORING_USE_TRANSITION = true;
describe('useBlockingPaginationFragment with useTransition', () => {
if (
TEMPORARY_SKIP_WHILE_REFACTORING_USE_TRANSITION ||
typeof React.useTransition !== 'function'
) {
it('empty test to prevent Jest from failing', () => {
// This suite is only useful with experimental React build
});
} else {
let environment;
let initialUser;
let gqlQuery;
let gqlQueryWithoutID;
let gqlPaginationQuery;
let gqlFragment;
let query;
let queryWithoutID;
let paginationQuery;
let variables;
let variablesWithoutID;
let setOwner;
let renderFragment;
let loadNext;
let refetch;
let forceUpdate;
let release;
let Renderer;
class ErrorBoundary extends React.Component<any, any> {
state = {error: null};
componentDidCatch(error) {
this.setState({error});
}
render() {
const {children, fallback} = this.props;
const {error} = this.state;
if (error) {
return React.createElement(fallback, {error});
}
return children;
}
}
function useBlockingPaginationFragmentWithSuspenseTransition(
fragmentNode,
fragmentRef,
) {
const [isPendingNext, startTransition] = useTransition();
// $FlowFixMe[incompatible-call]
const {data, ...result} = useBlockingPaginationFragmentOriginal(
fragmentNode,
// $FlowFixMe[prop-missing]
// $FlowFixMe[incompatible-call]
fragmentRef,
);
loadNext = (...args) => {
let disposable = {dispose: () => {}};
startTransition(() => {
disposable = result.loadNext(...args);
});
return disposable;
};
refetch = result.refetch;
// $FlowFixMe[prop-missing]
result.isPendingNext = isPendingNext;
useEffect(() => {
Scheduler.unstable_yieldValue({data, ...result});
});
return {data, ...result};
}
function assertYieldsWereCleared() {
const actualYields = Scheduler.unstable_clearYields();
if (actualYields.length !== 0) {
throw new Error(
'Log of yielded values is not empty. ' +
'Call expect(Scheduler).toHaveYielded(...) first.',
);
}
}
function assertYield(expected, actual) {
expect(actual.data).toEqual(expected.data);
expect(actual.isPendingNext).toEqual(expected.isPendingNext);
expect(actual.hasNext).toEqual(expected.hasNext);
expect(actual.hasPrevious).toEqual(expected.hasPrevious);
}
function expectFragmentResults(
expectedYields: $ReadOnlyArray<{|
data: $FlowFixMe,
isPendingNext: boolean,
hasNext: boolean,
hasPrevious: boolean,
|}>,
) {
assertYieldsWereCleared();
Scheduler.unstable_flushNumberOfYields(expectedYields.length);
const actualYields = Scheduler.unstable_clearYields();
expect(actualYields.length).toEqual(expectedYields.length);
expectedYields.forEach((expected, idx) =>
assertYield(expected, actualYields[idx]),
);
}
function expectRequestIsInFlight(expected) {
expect(environment.execute).toBeCalledTimes(expected.requestCount);
expect(
environment.mock.isLoading(
gqlPaginationQuery,
expected.paginationVariables,
{force: true},
),
).toEqual(expected.inFlight);
}
function expectFragmentIsPendingOnPagination(
renderer,
direction: Direction,
expected: {|
data: mixed,
hasNext: boolean,
hasPrevious: boolean,
paginationVariables: Variables,
|},
) {
// Assert fragment sets isPending to true
expectFragmentResults([
{
data: expected.data,
isPendingNext: direction === 'forward',
hasNext: expected.hasNext,
hasPrevious: expected.hasPrevious,
},
]);
// Assert refetch query was fetched
expectRequestIsInFlight({...expected, inFlight: true, requestCount: 1});
}
function createFragmentRef(id, owner) {
return {
[ID_KEY]: id,
[FRAGMENTS_KEY]: {
useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment: {},
},
[FRAGMENT_OWNER_KEY]: owner.request,
};
}
beforeEach(() => {
// Set up mocks
jest.resetModules();
jest.mock('warning');
jest.mock('scheduler', () => {
return jest.requireActual('scheduler/unstable_mock');
});
// Supress `act` warnings since we are intentionally not
// using it for most tests here. `act` currently always
// flushes Suspense fallbacks, and that's not what we want
// when asserting pending/suspended states,
const originalLogError = console.error.bind(console);
jest.spyOn(console, 'error').mockImplementation((message, ...args) => {
if (typeof message === 'string' && message.includes('act(...)')) {
return;
}
originalLogError(message, ...args);
});
// Set up environment and base data
environment = createMockEnvironment({
handlerProvider: () => ConnectionHandler,
});
release = jest.fn();
environment.retain.mockImplementation((...args) => {
return {
dispose: release,
};
});
graphql`
fragment useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment on User {
username
}
`;
gqlFragment = getFragment(graphql`
fragment useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment on User
@refetchable(
queryName: "useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragmentPaginationQuery"
)
@argumentDefinitions(
isViewerFriendLocal: {type: "Boolean", defaultValue: false}
orderby: {type: "[String]"}
) {
id
name
friends(
after: $after
first: $first
before: $before
last: $last
orderby: $orderby
isViewerFriend: $isViewerFriendLocal
) @connection(key: "UserFragment_friends") {
edges {
node {
id
name
...useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment
}
}
}
}
`);
gqlQuery = getRequest(
graphql`
query useBlockingPaginationFragmentWithSuspenseTransitionTestUserQuery(
$id: ID!
$after: ID
$first: Int
$before: ID
$last: Int
$orderby: [String]
$isViewerFriend: Boolean
) {
node(id: $id) {
actor {
...useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment
@arguments(
isViewerFriendLocal: $isViewerFriend
orderby: $orderby
)
}
}
}
`,
);
gqlQueryWithoutID = getRequest(graphql`
query useBlockingPaginationFragmentWithSuspenseTransitionTestUserQueryWithoutIDQuery(
$after: ID
$first: Int
$before: ID
$last: Int
$orderby: [String]
$isViewerFriend: Boolean
) {
viewer {
actor {
...useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment
@arguments(
isViewerFriendLocal: $isViewerFriend
orderby: $orderby
)
}
}
}
`);
variablesWithoutID = {
after: null,
first: 1,
before: null,
last: null,
isViewerFriend: false,
orderby: ['name'],
};
variables = {
...variablesWithoutID,
id: '<feedbackid>',
};
gqlPaginationQuery = require('./__generated__/useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragmentPaginationQuery.graphql');
query = createOperationDescriptor(gqlQuery, variables);
queryWithoutID = createOperationDescriptor(
gqlQueryWithoutID,
variablesWithoutID,
);
paginationQuery = createOperationDescriptor(
gqlPaginationQuery,
variables,
);
environment.commitPayload(query, {
node: {
__typename: 'Feedback',
id: '<feedbackid>',
actor: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
},
});
environment.commitPayload(queryWithoutID, {
viewer: {
actor: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
username: 'username:node:1',
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
},
},
});
// Set up renderers
Renderer = props => null;
const Container = (props: {
userRef?: {...},
owner: $FlowFixMe,
fragment: $FlowFixMe,
...
}) => {
// We need a render a component to run a Hook
const [owner, _setOwner] = useState(props.owner);
const [_, _setCount] = useState(0);
const fragment = props.fragment ?? gqlFragment;
const artificialUserRef = useMemo(() => {
const snapshot = environment.lookup(owner.fragment);
return (snapshot.data: $FlowFixMe)?.node?.actor;
}, [owner]);
const userRef = props.hasOwnProperty('userRef')
? props.userRef
: artificialUserRef;
setOwner = _setOwner;
forceUpdate = _setCount;
const {
data: userData,
} = useBlockingPaginationFragmentWithSuspenseTransition(
fragment,
// $FlowFixMe[prop-missing]
userRef,
);
return <Renderer user={userData} />;
};
const ContextProvider = ({children}) => {
// TODO(T39494051) - We set empty variables in relay context to make
// Flow happy, but useBlockingPaginationFragment does not use them, instead it uses
// the variables from the fragment owner.
const relayContext = useMemo(() => ({environment}), []);
return (
<ReactRelayContext.Provider value={relayContext}>
{children}
</ReactRelayContext.Provider>
);
};
const Fallback = () => {
useEffect(() => {
Scheduler.unstable_yieldValue('Fallback');
});
return 'Fallback';
};
renderFragment = (args?: {
isConcurrent?: boolean,
owner?: $FlowFixMe,
userRef?: $FlowFixMe,
fragment?: $FlowFixMe,
...
}): $FlowFixMe => {
const {isConcurrent = true, ...props} = args ?? {};
return TestRenderer.create(
<ErrorBoundary fallback={({error}) => `Error: ${error.message}`}>
<React.Suspense fallback={<Fallback />}>
<ContextProvider>
<Container owner={query} {...props} />
</ContextProvider>
</React.Suspense>
</ErrorBoundary>,
// $FlowFixMe[prop-missing] - error revealed when flow-typing ReactTestRenderer
{unstable_isConcurrent: isConcurrent},
);
};
initialUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
],
pageInfo: {
endCursor: 'cursor:1',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
});
afterEach(() => {
environment.mockClear();
jest.dontMock('scheduler');
});
describe('loadNext', () => {
const direction = 'forward';
// Sanity check test, should already be tested in useBlockingPagination test
it('loads and renders next items in connection', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
loadNext(1, {onComplete: callback});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
};
expectFragmentIsPendingOnPagination(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
});
expect(callback).toBeCalledTimes(0);
expect(renderer.toJSON()).toEqual(null);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('renders pending flag correctly if pagination update is interrupted before it commits (unsuspends)', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
loadNext(1, {onComplete: callback});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
};
expectFragmentIsPendingOnPagination(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
});
expect(callback).toBeCalledTimes(0);
expect(renderer.toJSON()).toEqual(null);
// Schedule a high-pri update while the component is
// suspended on pagination
Scheduler.unstable_runWithPriority(
Scheduler.unstable_UserBlockingPriority,
() => {
forceUpdate(prev => prev + 1);
},
);
// Assert high-pri update is rendered when initial update
// that suspended hasn't committed
// Assert that the avoided Suspense fallback isn't rendered
expect(renderer.toJSON()).toEqual(null);
expectFragmentResults([
{
data: initialUser,
// Assert that isPending flag is still true
isPendingNext: true,
hasNext: true,
hasPrevious: false,
},
]);
// Assert list is updated after pagination request completes
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('loads more correctly when original variables do not include an id', () => {
const callback = jest.fn();
const viewer = environment.lookup(queryWithoutID.fragment).data?.viewer;
const userRef =
typeof viewer === 'object' && viewer != null ? viewer?.actor : null;
invariant(userRef != null, 'Expected to have cached test data');
let expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithoutID),
},
},
],
},
};
const renderer = renderFragment({owner: queryWithoutID, userRef});
expectFragmentResults([
{
data: expectedUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
loadNext(1, {onComplete: callback});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
};
expectFragmentIsPendingOnPagination(renderer, direction, {
data: expectedUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
});
expect(callback).toBeCalledTimes(0);
expect(renderer.toJSON()).toEqual(null);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', queryWithoutID),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', queryWithoutID),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
it('calls callback with error when error occurs during fetch', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
loadNext(1, {onComplete: callback});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
};
expectFragmentIsPendingOnPagination(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
});
expect(callback).toBeCalledTimes(0);
expect(renderer.toJSON()).toEqual(null);
const error = new Error('Oops');
environment.mock.reject(gqlPaginationQuery, error);
// We pass the error in the callback, but do not throw during render
// since we want to continue rendering the existing items in the
// connection
expect(callback).toBeCalledTimes(1);
expect(callback).toBeCalledWith(error);
});
it('preserves pagination request if re-rendered with same fragment ref', () => {
const callback = jest.fn();
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
loadNext(1, {onComplete: callback});
const paginationVariables = {
id: '1',
after: 'cursor:1',
first: 1,
before: null,
last: null,
isViewerFriendLocal: false,
orderby: ['name'],
};
expectFragmentIsPendingOnPagination(renderer, direction, {
data: initialUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
});
expect(callback).toBeCalledTimes(0);
expect(renderer.toJSON()).toEqual(null);
setOwner({...query});
// Assert that request is still in flight after re-rendering
// with new fragment ref that points to the same data.
expectRequestIsInFlight({
inFlight: true,
requestCount: 1,
gqlPaginationQuery,
paginationVariables,
});
expect(callback).toBeCalledTimes(0);
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
username: 'username:node:2',
},
},
],
pageInfo: {
startCursor: 'cursor:2',
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const expectedUser = {
...initialUser,
friends: {
...initialUser.friends,
edges: [
{
cursor: 'cursor:1',
node: {
__typename: 'User',
id: 'node:1',
name: 'name:node:1',
...createFragmentRef('node:1', query),
},
},
{
cursor: 'cursor:2',
node: {
__typename: 'User',
id: 'node:2',
name: 'name:node:2',
...createFragmentRef('node:2', query),
},
},
],
pageInfo: {
endCursor: 'cursor:2',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:1',
},
},
};
expectFragmentResults([
{
data: expectedUser,
isPendingNext: true,
hasNext: true,
hasPrevious: false,
},
{
data: expectedUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
expect(callback).toBeCalledTimes(1);
});
});
describe('refetch', () => {
// The bulk of refetch behavior is covered in useRefetchableFragmentNode-test,
// so this suite covers the pagination-related test cases.
function expectRefetchRequestIsInFlight(expected) {
expect(environment.executeWithSource).toBeCalledTimes(
expected.requestCount,
);
expect(
environment.mock.isLoading(
expected.gqlRefetchQuery ?? gqlPaginationQuery,
expected.refetchVariables,
{force: true},
),
).toEqual(expected.inFlight);
}
function expectFragmentSuspendedOnRefetch(
renderer,
expected: {|
data: mixed,
hasNext: boolean,
hasPrevious: boolean,
refetchVariables: Variables,
refetchQuery?: OperationDescriptor,
gqlRefetchQuery?: $FlowFixMe,
|},
flushFallback: boolean = true,
) {
assertYieldsWereCleared();
TestRenderer.act(() => {
// Wrap in act to ensure passive effects are run
jest.runAllImmediates();
});
Scheduler.unstable_flushNumberOfYields(1);
const actualYields = Scheduler.unstable_clearYields();
if (flushFallback) {
// Flushing fallbacks by running a timer could cause other side-effects
// such as releasing retained queries. Until React has a better way to flush
// fallbacks, we can't test fallbacks and other timeout based effects at the same time.
jest.runOnlyPendingTimers(); // Tigger fallbacks.
// Assert component suspendeds
expect(actualYields.length).toEqual(1);
expect(actualYields[0]).toEqual('Fallback');
expect(renderer.toJSON()).toEqual('Fallback');
}
// Assert refetch query was fetched
expectRefetchRequestIsInFlight({
...expected,
inFlight: true,
requestCount: 1,
});
// Assert query is retained by loadQuery
// and tentatively retained while component is suspended
expect(environment.retain).toBeCalledTimes(2);
expect(environment.retain.mock.calls[0][0]).toEqual(
expected.refetchQuery,
);
}
it('loads more items correctly after refetching', () => {
const renderer = renderFragment();
expectFragmentResults([
{
data: initialUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
refetch({isViewerFriendLocal: true, orderby: ['lastname']});
// Assert that fragment is refetching with the right variables and
// suspends upon refetch
const refetchVariables = {
after: null,
first: 1,
before: null,
last: null,
id: '1',
isViewerFriendLocal: true,
orderby: ['lastname'],
};
paginationQuery = createOperationDescriptor(
gqlPaginationQuery,
refetchVariables,
{force: true},
);
expectFragmentSuspendedOnRefetch(
renderer,
{
data: initialUser,
hasNext: true,
hasPrevious: false,
refetchVariables,
refetchQuery: paginationQuery,
},
false,
);
// Mock network response
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
username: 'username:node:100',
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
},
},
});
// Assert fragment is rendered with new data
const expectedUser = {
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
...createFragmentRef('node:100', paginationQuery),
},
},
],
pageInfo: {
endCursor: 'cursor:100',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
};
jest.runAllImmediates();
expectFragmentResults([
{
data: expectedUser,
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
// Assert refetch query was retained by loadQuery and component
expect(release).not.toBeCalled();
expect(environment.retain).toBeCalledTimes(2);
expect(environment.retain.mock.calls[0][0]).toEqual(paginationQuery);
// Paginate after refetching
environment.execute.mockClear();
loadNext(1);
const paginationVariables = {
id: '1',
after: 'cursor:100',
first: 1,
before: null,
last: null,
isViewerFriendLocal: true,
orderby: ['lastname'],
};
expectFragmentIsPendingOnPagination(renderer, 'forward', {
data: expectedUser,
hasNext: true,
hasPrevious: false,
paginationVariables,
});
environment.mock.resolve(gqlPaginationQuery, {
data: {
node: {
__typename: 'User',
id: '1',
name: 'Alice',
friends: {
edges: [
{
cursor: 'cursor:200',
node: {
__typename: 'User',
id: 'node:200',
name: 'name:node:200',
username: 'username:node:200',
},
},
],
pageInfo: {
startCursor: 'cursor:200',
endCursor: 'cursor:200',
hasNextPage: true,
hasPreviousPage: true,
},
},
},
},
});
const paginatedUser = {
...expectedUser,
friends: {
...expectedUser.friends,
edges: [
{
cursor: 'cursor:100',
node: {
__typename: 'User',
id: 'node:100',
name: 'name:node:100',
...createFragmentRef('node:100', paginationQuery),
},
},
{
cursor: 'cursor:200',
node: {
__typename: 'User',
id: 'node:200',
name: 'name:node:200',
...createFragmentRef('node:200', paginationQuery),
},
},
],
pageInfo: {
endCursor: 'cursor:200',
hasNextPage: true,
hasPreviousPage: false,
startCursor: 'cursor:100',
},
},
};
expectFragmentResults([
{
data: paginatedUser,
// Assert pending flag is set back to false
isPendingNext: false,
hasNext: true,
hasPrevious: false,
},
]);
});
});
}
});
| atxwebs/relay | packages/react-relay/relay-hooks/__tests__/useBlockingPaginationFragment-with-suspense-transition-test.js | JavaScript | mit | 37,656 |
var chartPrevious = [
{"Name":"", "Description":"charts"},
{"Name":"1 hour", "Description":"1 hour"},
{"Name":"2 hours", "Description":"2 hours"},
{"Name":"10 hours", "Description":"10 hours"},
{"Name":"1 day", "Description":"1 day"},
{"Name":"2 days", "Description":"2 days"},
{"Name":"3 days", "Description":"3 days"},
{"Name":"7 days", "Description":"7 days"},
{"Name":"14 days", "Description":"14 days"},
{"Name":"30 days", "Description":"30 days"}
];
var employees = [
{"name":"Employee10", "surname":"Employee1", "filename" : "sav3.png", "department":"marketing"},
{"name":"Employee11", "surname":"Employee1", "filename" : "who3.png", "department":"marketing"},
{"name":"Employee12", "surname":"Employee1", "filename" : "jac4.png", "department":"digital"},
{"name":"Employee13", "surname":"Employee1", "filename" : "mart4.png", "department":"digital"},
{"name":"Employee14", "surname":"Employee1", "filename" : "sav4.png", "department":"digital"},
{"name":"Employee15", "surname":"Employee1", "filename" : "who4.png", "department":"digital"},
{"name":"Employee16", "surname":"Employee1", "filename" : "jac5.png", "department":"digital"},
{"name":"Employee17", "surname":"Employee1", "filename" : "mart5.png", "department":"marketing"},
{"name":"Employee18", "surname":"Employee1", "filename" : "sav5.png", "department":"digital"},
{"name":"Employee19", "surname":"Employee1", "filename" : "who5.png", "department":"digital"},
{"name":"Employee1", "surname":"Employee1", "filename" : "jac1.png", "department":"marketing"},
{"name":"Employee2", "surname":"Employee1", "filename" : "mart1.png", "department":"marketing"},
{"name":"Employee3", "surname":"Employee1", "filename" : "sav1.png", "department":"marketing"},
{"name":"Employee4", "surname":"Employee1", "filename" : "who1.png", "department":"marketing"},
{"name":"Employee5", "surname":"Employee1", "filename" : "jac2.png", "department":"marketing"},
{"name":"Employee6", "surname":"Employee1", "filename" : "mart2.png", "department":"marketing"},
{"name":"Employee6", "surname":"Employee1", "filename" : "sav2.png", "department":"marketing"},
{"name":"Employee7", "surname":"Employee1", "filename" : "who2.png", "department":"marketing"},
{"name":"Employee8", "surname":"Employee1", "filename" : "jac3.png", "department":"marketing"},
{"name":"Employee9", "surname":"Employee1", "filename" : "mart3.png", "department":"marketing"},
{"name":"Employee20", "surname":"Employee1", "filename" : "jac6.png", "department":"marketing"},
{"name":"Employee21", "surname":"Employee1", "filename" : "mart6.png", "department":"marketing"},
{"name":"Employee22", "surname":"Employee1", "filename" : "sav6.png", "department":"marketing"},
{"name":"Employee23", "surname":"Employee1", "filename" : "who6.png", "department":"marketing"},
{"name":"Employee24", "surname":"Employee1", "filename" : "jac7.png", "department":"marketing"},
{"name":"Employee25", "surname":"Employee1", "filename" : "mart7.png", "department":"marketing"},
{"name":"Employee26", "surname":"Employee1", "filename" : "sav7.png", "department":"marketing"},
{"name":"Employee27", "surname":"Employee1", "filename" : "who7.png", "department":"marketing"},
{"name":"Employee28", "surname":"Employee1", "filename" : "jac8.png", "department":"staff"},
{"name":"Employee29", "surname":"Employee1", "filename" : "mart8.png", "department":"staff"},
{"name":"Employee40", "surname":"Employee1", "filename" : "jac11.png", "department":"staff"},
{"name":"Employee41", "surname":"Employee1", "filename" : "mart11.png", "department":"marketing"},
{"name":"Employee42", "surname":"Employee1", "filename" : "sav11.png", "department":"marketing"},
{"name":"Employee43", "surname":"Employee1", "filename" : "who11.png", "department":"marketing"},
{"name":"Employee44", "surname":"Employee1", "filename" : "jac12.png", "department":"staff"},
{"name":"Employee45", "surname":"Employee1", "filename" : "mart12.png", "department":"staff"},
{"name":"Employee46", "surname":"Employee1", "filename" : "sav12.png", "department":"staff"},
{"name":"Employee47", "surname":"Employee1", "filename" : "who12.png", "department":"staff"},
{"name":"Employee48", "surname":"Employee1", "filename" : "jac13.png", "department":"staff"},
{"name":"Employee49", "surname":"Employee1", "filename" : "mart13.png", "department":"staff"},
{"name":"Employee30", "surname":"Employee1", "filename" : "sav8.png", "department":"marketing"},
{"name":"Employee31", "surname":"Employee1", "filename" : "who8.png", "department":"marketing"},
{"name":"Employee32", "surname":"Employee1", "filename" : "jac9.png", "department":"marketing"},
{"name":"Employee33", "surname":"Employee1", "filename" : "mart9.png", "department":"staff"},
{"name":"Employee34", "surname":"Employee1", "filename" : "sav9.png", "department":"staff"},
{"name":"Employee35", "surname":"Employee1", "filename" : "who9.png", "department":"marketing"},
{"name":"Employee36", "surname":"Employee1", "filename" : "jac10.png", "department":"marketing"},
{"name":"Employee37", "surname":"Employee1", "filename" : "mart10.png", "department":"staff"},
{"name":"Employee38", "surname":"Employee1", "filename" : "sav10.png", "department":"staff"},
{"name":"Employee39", "surname":"Employee1", "filename" : "who10.png", "department":"staff"}
]; | toddbadams/UmbracoCMS | js/data.js | JavaScript | mit | 5,277 |
/*requires core.js*/
/*requires load.js*/
/*requires ajax.js*/
/*requires dom.js*/
/*requires selector.js*/
/*requires ua.js*/
/*requires event.js*/
/*requires ui.js*/
/*requires ui.tab.js*/
/*requires ui.slide.js*/
/*requires ui.nav.js*/
/**
* nova.ui.flow
* 在页面中四处飘浮的广告
* 遇到边界则改变飘浮方向
* @param number width element&img's width
* @param number height element&img's height
* @param string img's src
* @param string anchor href
*/
nova.ui.flow = function() {
var doc = document,
html = doc.documentElement,
body = doc.body,
opt = arguments[0],
xPos = 300,
yPos = 200,
step = 1,
delay = 30,
height = 0,
Hoffset = 0,
Woffset = 0,
yon = 0,
xon = 0,
pause = true,
interval;
//生成广告元素
var elm = doc.createElement("div");
nova.dom.addClass(elm, "nova-ui-flow");
elm.innerHTML = '<a href="'+ opt.href + '"><img src="' + opt.src + '" width="' + opt.width + '" height="' + opt.height + '"></a>';
nova.dom.setCSS([elm], {
position: "absolute",
zIndex: "100",
top: yPos + "px",
left: "2px",
width: opt.width + "px",
height: opt.height + "px",
visibility: "visible"
});
body.appendChild(elm);
var changePos = function () {
width = body.clientWidth;
height = html.clientHeight;
Hoffset = elm.offsetHeight;
Woffset = elm.offsetWidth;
nova.dom.setCSS([elm], {
left: xPos + doc.body.scrollLeft + "px",
top: yPos + doc.body.scrollTop + "px"
});
if (yon) {
yPos = yPos + step;
} else {
yPos = yPos - step;
}
if (yPos < 0) {
yon = 1;
yPos = 0;
}
if (yPos >= (height - Hoffset)) {
yon = 0;
yPos = (height - Hoffset);
}
if (xon) {
xPos = xPos + step;
} else {
xPos = xPos - step;
}
if (xPos < 0) {
xon = 1;
xPos = 0;
}
if (xPos >= (width - Woffset)) {
xon = 0;
xPos = (width - Woffset);
}
};
var pauseResume = function () {
if (pause) {
clearInterval(interval);
pause = false;
} else {
interval = setInterval(changePos, delay);
pause = true;
}
};
nova.Event.add(elm, "mouseover", pauseResume);
nova.Event.add(elm, "mouseout", pauseResume);
interval = setInterval(changePos, delay);
};
| qiushilee/frostnova | src/ui/ui.flow.js | JavaScript | mit | 2,235 |
$(document).ready(function () {
$('#userData').hide();
$('#topScores').show();
// enchanced method addEventListener
function addEventListener(selector, eventType, listener) {
$(selector).on(eventType, listener);
}
function trigerClick($button) {
$button.click();
}
var GameManager = (function () {
var numberToGuess = [];
var guessNumber = [];
var guesses = 0;
function getRandomNumber() {
var newNumber = [];
guesses = 0;
newNumber[0] = Math.round(Math.random() * 8 + 1); // first digit must be bigger than 0
newNumber[1] = Math.round(Math.random() * 9);
newNumber[2] = Math.round(Math.random() * 9);
newNumber[3] = Math.round(Math.random() * 9);
numberToGuess = newNumber;
}
function getUserInput(value) {
value = validateNumber(value);
guessNumber = String(parseInt(value)).split('');
}
function validateNumber(number) {
number = number.trim();
if (number.length != 4) {
throw new Error("The number must be 4 digits long!");
}
number = String(parseInt(number));
if (isNaN(number) || (number < 1000 || number > 10000)) {
throw new Error("This is not a 4 digit number!");
}
return number;
}
function checkNumber() {
var rams = 0;
var sheeps = 0;
guesses += 1;
//numberToGuess = [6, 1, 5, 4];
//guessNumber = [2, 3, 4, 5];
//numberToGuess = [5, 5, 8, 8];
//guessNumber = [8, 8, 8, 5];
var counted = [false, false, false, false];
//console.log(numberToGuess);
//console.log(guessNumber);
for (var i = 0; i < numberToGuess.length; i++) {
if (guessNumber[i] == numberToGuess[i]) {
//console.log(i + ' - ' + guessNumber[i] + ' ' + numberToGuess[i] + ' <- ram');
rams++;
if (counted[i]) {
sheeps--;
}
counted[i] = true;
}
else {
for (var j = 0; j < numberToGuess.length; j++) {
if (!counted[j] && guessNumber[i] == numberToGuess[j]) {
//console.log(i + ' ' + j + ' - ' + guessNumber[i] + ' ' + numberToGuess[j] + ' <- sheep');
sheeps++;
counted[j] = true;
break;
}
}
}
}
manageResult(guessNumber, rams, sheeps);
}
function manageResult(guessNumber, rams, sheeps) {
var ul = $('#guesses ul');
var li = $('<li>');
if (rams < 4) {
li.text(guesses + ': (' + guessNumber.join('') + ') You have ' + rams + ' rams and ' + sheeps + ' sheeps!');
ul.prepend(li);
}
else {
$('#guesses').hide();
$('#userData').fadeIn();
}
}
function getUserName(name) {
//validations
return name;
}
function getUserGuesses() {
return guesses;
}
return {
getRandomNumber: getRandomNumber,
getUserInput: getUserInput,
getUserName: getUserName,
getUserGuesses: getUserGuesses,
checkNumber: checkNumber
}
})();
var HighScores = (function () {
var ramsAndSheepsHighScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || [];
function addScore(name, guesses) {
var user = {
name: name,
score: guesses
}
ramsAndSheepsHighScores.push(user);
var sortedHighScores = _.chain(ramsAndSheepsHighScores)
.sortBy(function (user) { return user.name; })
.sortBy(function (user) { return user.score; })
.first(5).value();
console.log(sortedHighScores);
localStorage.setItem('ramsAndSheepsHighScores', JSON.stringify(sortedHighScores));
}
function showAll() {
var allScores = JSON.parse(localStorage.getItem('ramsAndSheepsHighScores')) || [];
var ol = $('#topScores ol');
ol.empty();
_.chain(ramsAndSheepsHighScores)
.each(function (user) {
var li = $('<li>');
li.text(user.name + ' ' + user.score);
ol.append(li);
});
}
return {
addScore: addScore,
showAll: showAll
}
})();
// hack the input for non digits
$("#userInput").on({
// When a new character was typed in
keydown: function (e) {
var key = e.which;
// the enter key code
if (key == 13) {
trigerClick($('#guessBtn'));
return false;
}
// if something else than [0-9] or BackSpace (BS == 8) is pressed, cancel the input
if (((key < 48 || key > 57) && (key < 96 || key > 105)) && key !== 8) {
return false;
}
},
// When non digits managed to "sneak in" via copy/paste
change: function () {
// Regex-remove all non digits in the final value
this.value = this.value.replace(/\D/g, "")
}
});
addEventListener('#guessBtn', 'click', function (event) {
var $userInput = $('#userInput');
GameManager.getUserInput($userInput[0].value);
GameManager.checkNumber();
});
addEventListener('#getNameBtn', 'click', function (event) {
var $userName = $('#userName');
var userName = GameManager.getUserName($userName[0].value);
HighScores.addScore(userName, GameManager.getUserGuesses());
$('#userData').hide();
HighScores.showAll();
$('#topScores').fadeIn();
});
addEventListener('#resetBtn', 'click', function (event) {
var userInput = $('#userInput');
var guessesUl = $('#guesses ul');
guessesUl.empty();
userInput[0].value = "";
GameManager.getRandomNumber();
});
// add the scores
HighScores.showAll();
// start the game
GameManager.getRandomNumber();
}); | Steffkn/TelerikAcademy | HTML and CSS/JS/04.JS Applications/02.WebStorages/js/ramsAndSheeps.js | JavaScript | mit | 6,642 |
/**
* process_sqlite.js
*/
var fs = require('fs-extra')
var debug = require('debug')('hostview')
var async = require('async')
var sqlite = require('sqlite3')
var utils = require('./utils')
/**
* Process a single sqlite file from Hostview.
*
* We assume that each sqlite file corresponds to a 'session' and
* all that all raw data related to this session is in this sqlite file.
*/
module.exports.process = function (file, db, cb) {
if (!file || !db) { return cb(new Error('[process_sqlite] missing arguments')) }
// wrap everything in a transaction on the backend db --
// any failure to write there will cancel the file processing
// anc call cb with error
// the session of this file
var session = {
file_id: file.id,
device_id: file.device_id,
started_at: null,
ended_at: null,
start_event: null,
stop_event: null
}
var readloopESM = function (client, sql, dsttable, dstrow, callback) {
var e = null
var survey_session = {}
var elementsToInsert = []
var loop = function () {
if (elementsToInsert.length === 0) {
return callback(null,survey_session) // done
}
var a = elementsToInsert.shift()
db._db.insert(dsttable, a).returning('*').row(function (err, res) {
if (err) return callback(err)
else {
survey_session[res.started_at] = res.id
loop()
}
})
}
file.db.each(sql, function (err, row) {
if (e || err) {
// we can't abort the .each(), so just record the error
// -- alternative is to do .all() but .each avoids reading
// all the data in memory (some tables can be huge !!)
if (!e) debug('readloopESM fail: ' + dsttable, err)
e = e || err
return
}
// map from sqlite row to backend db row
var o = dstrow(row)
// track the latest data row just in case
if (o.logged_at) { session.ended_at = utils.datemax(session.ended_at, o.logged_at) }
elementsToInsert.push(o)
}, function (err) {
e = e || err
loop()
})
}
// helper func to refactor out the common processing pattern
// (read rows from sqlite and insert to the backend fb)
var readloop = function (client, sql, dsttable, dstrow, callback) {
var e = null
// fetch data from the sqlite
file.db.each(sql, function (err, row) {
if (e || err) {
// we can't abort the .each(), so just record the error
// -- alternative is to do .all() but .each avoids reading
// all the data in memory (some tables can be huge !!)
if (!e) debug('readloop fail: ' + dsttable, err)
e = e || err
return
}
// map from sqlite row to backend db row
var o = dstrow(row)
// track the latest data row just in case
if (o.logged_at) { session.ended_at = utils.datemax(session.ended_at, o.logged_at) }
// add to the backend table
client.insert(dsttable, o).run(function (err, res) {
// we can't abort the .each(), so just record the error
// -- alternative is to do .all() but .each avoids reading
// all the data in memory (some tables can be huge !!)
// TODO: does this really work or there's some race conditions here ?
if (!e && err) debug('readloop insert fail: ' + dsttable, err)
e = e || err
})
}, function (err) {
// .each() completed - pass on any error (or nothing on success)
e = e || err
debug('readloop complete: ' + dsttable, e)
callback(e)
})
}
// another helper to convert empty strings to nulls
var getstr = function (row, col) {
if (!row[col] || row[col] === '' || row[col].trim() === '') { return null }
return row[col].trim()
}
// the processing goes as follows:
//
// 1) uncompress the file to a temp location
// 2) open sqlite connection to the temp file
// 3) create the session on the backend db
// 4) bulk of the work: map sqlite tables to backend db
// 5) process other derived tables and data
// 6) cleanup temp file
async.waterfall([
function (callback) {
callback(null, file.path, '/tmp/' + file.device_id)
},
utils.uncompress,
function (path, callback) {
debug('sqlite connect ' + path)
file.uncompressed_path = path
file.db = new sqlite.Database(path, sqlite.OPEN_READONLY, callback)
},
function (callback) {
// get session start event (there should only be one)
debug('select session start')
var sql = `SELECT timestamp started_at, event start_event
FROM session
WHERE event IN ('start','restart','autorestart','resume','autostart')
ORDER BY timestamp ASC`
file.db.get(sql, callback)
},
function (row, callback) {
debug('session start', row)
// stop here - there's no start event so the db is (assumed?) empty
if (!row) return callback(new Error('no data'))
session.started_at = new Date(row.started_at)
session.start_event = row.start_event
// get session end event (there should only be zero or one)
var sql = `SELECT timestamp ended_at, event stop_event
FROM session
WHERE event IN ('pause','stop','autostop','suspend')
ORDER BY timestamp DESC`
file.db.get(sql, callback)
},
function (row, callback) {
debug('session stop', row)
if (row) {
session.ended_at = new Date(row.ended_at)
session.stop_event = row.stop_event
} else {
// can happen if the hostview cli crashed
session.stop_event = 'missing'
session.ended_at = session.started_at
}
// store the session, returns the inserted row
db._db.insert('sessions', session).returning('*').row(callback)
},
function (row, callback) {
session.id = row.id
debug('session', session)
callback(null)
},
function (callback) {
debug('wifistats')
var sql = `SELECT * FROM wifistats ORDER BY timestamp ASC`
readloop(db._db, sql, 'wifi_stats', function (row) {
return {
session_id: session.id,
guid: getstr(row, 'guid'),
t_speed: row.tspeed,
r_speed: row.rspeed,
signal: row.signal,
rssi: row.rssi,
state: row.state,
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('processes')
var sql = `SELECT * FROM procs ORDER BY timestamp ASC LIMIT 10`
readloop(db._db, sql, 'processes', function (row) {
return {
session_id: session.id,
pid: row.pid,
name: getstr(row, 'name'),
memory: row.memory,
cpu: row.cpu,
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('powerstates')
var sql = `SELECT * FROM powerstate ORDER BY timestamp ASC`
readloop(db._db, sql, 'power_states', function (row) {
return {
session_id: session.id,
event: row.event,
value: row.value,
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('ports')
var sql = `SELECT * FROM ports ORDER BY timestamp ASC`
readloop(db._db, sql, 'ports', function (row) {
return {
session_id: session.id,
pid: row.pid,
name: getstr(row, 'name'),
protocol: row.protocol,
source_ip: getstr(row, 'srcip'),
destination_ip: getstr(row, 'destip'),
source_port: row.srcport,
destination_port: row.destport,
state: row.state,
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('io')
var sql = `SELECT * FROM io ORDER BY timestamp ASC`
readloop(db._db, sql, 'io', function (row) {
return {
session_id: session.id,
device: row.device,
pid: row.pid,
name: getstr(row, 'name'),
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('deviceinfo')
var sql = `SELECT * FROM sysinfo ORDER BY timestamp ASC`
readloop(db._db, sql, 'device_info', function (row) {
return {
session_id: session.id,
manufacturer: row.manufacturer,
product: row.product,
operating_system: row.os,
cpu: row.cpu,
memory_installed: row.totalRAM,
hdd_capacity: row.totalHDD,
serial_number: row.serial,
hostview_version: row.hostview_version,
settings_version: row.settings_version,
timezone: row.timezone,
timezone_offset: row.timezone_offset,
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('netlabels')
var sql = `SELECT * FROM netlabel ORDER BY timestamp ASC`
readloop(db._db, sql, 'netlabels', function (row) {
return {
session_id: session.id,
guid: getstr(row, 'guid'),
gateway: getstr(row, 'gateway'),
label: getstr(row, 'label'),
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('browseractivity')
var sql = `SELECT * FROM browseractivity ORDER BY timestamp ASC`
readloop(db._db, sql, 'browser_activity', function (row) {
return {
session_id: session.id,
browser: getstr(row, 'browser'),
location: getstr(row, 'location'),
logged_at: new Date(row.timestamp)
}
}, callback)
},
function (callback) {
debug('esm')
var sql = `SELECT * FROM esm ORDER BY timestamp ASC`
readloopESM(db._db, sql, 'surveys', function (row) {
return {
session_id: session.id,
ondemand: row.ondemand,
qoe_score: row.qoe_score,
duration: row.duration,
started_at: new Date(row.timestamp),
ended_at: new Date(row.timestamp + row.duration)
}
}, callback)
},
function (survey_session, callback) {
debug('esm activity')
if (!survey_session) {
callback("cannot fill survey info because survey_session is empty (esm activity)" ) //what should we do here?
}else{
for (var elem in survey_session)
debug('survey_session ' + elem)
}
var e = null
var sql = `SELECT * FROM esm_activity_tags ORDER BY timestamp ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
return
};
var surveyId = survey_session[new Date(row.timestamp)]
if (surveyId == null){
debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere
}else{
debug('find the corresponding survery with id ' + surveyId)
var params = {
survey_id : surveyId,
process_name : row.appname,
process_desc : row.description,
tags : row.tags.split(',')
}
db._db.insert('survey_activity_tags', params).run(function (err, res) {
e = e || err
})}
}, function (err) {
// .each complete
e = e || err
callback(e, survey_session)
})
},
function (survey_session, callback) {
debug('esm problems')
if (!survey_session) {
callback("cannot fill survey info because survey_session is empty (esm problems)") //what should we do here?
}
var e = null
var sql = `SELECT * FROM esm_problem_tags ORDER BY timestamp ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
return
};
var surveyId = survey_session[new Date(row.timestamp)]
if (surveyId == null){
debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere
}else{
var params = {
survey_id : surveyId,
process_name : row.appname,
process_desc : row.description,
tags : row.tags.split(',')
}
db._db.insert('survey_problem_tags', params).run(function (err, res) {
e = e || err
})}
}, function (err) {
// .each complete
e = e || err
callback(e,survey_session)
})
},
function (survey_session, callback) {
debug('esm activity qoe')
if (!survey_session) {
callback("cannot fill survey info because survey_session is empty (esm activity qoe)") //what should we do here?
}
var e = null
var sql = `SELECT * FROM esm_activity_qoe ORDER BY timestamp ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
return
};
var surveyId = survey_session[new Date(row.timestamp)]
if (surveyId == null){
debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere
}else{
var params = {
survey_id : surveyId,
process_name : row.appname,
process_desc : row.description,
qoe : row.qoe
}
db._db.insert('survey_activity_qoe', params).run(function (err, res) {
e = e || err
})}
}, function (err) {
// .each complete
e = e || err
callback(e,survey_session)
})
},
function (survey_session, callback) {
debug('esm activity importance')
if (!survey_session) {
callback("cannot fill survey info because survey_session is empty (esm activity importance)") //what should we do here?
}
var e = null
var sql = `SELECT * FROM esm_activity_importance ORDER BY timestamp ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
return
};
var surveyId = survey_session[new Date(row.timestamp)]
if (surveyId == null){
debug ('something is wrong, we couldn\'t find a survey with the same start time') //keep trying with the other elements; todo we should report the failure somewhere
}else{
var params = {
survey_id : surveyId,
process_name : row.appname,
process_desc : row.description,
importance : row.importance
}
db._db.insert('survey_activity_importance', params).run(function (err, res) {
e = e || err
})}
}, function (err) {
// .each complete
e = e || err
callback(e)
})
},
function (callback) {
debug('activity')
// reading one ahead so we can log the finish as well
var prev
var rows = []
var e = null
var sql = `SELECT * FROM activity ORDER BY timestamp ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
prev = undefined
return
};
var o = {
session_id: session.id,
user_name: getstr(row, 'user'),
pid: row.pid,
name: getstr(row, 'name'),
description: getstr(row, 'description'),
fullscreen: row.fullscreen,
idle: row.idle,
logged_at: new Date(row.timestamp)
}
session.ended_at = utils.datemax(session.ended_at, o.logged_at)
if (prev) {
// ends when the new event happens
prev.finished_at = new Date(row.timestamp)
rows.push(prev)
}
prev = o
}, function (err) {
// .each complete
e = e || err
if (prev) {
// insert the last activity event
prev.finished_at = session.ended_at
rows.push(prev)
}
debug('activies read, found ' + rows.length, e)
if (e) return callback(e) // something failed during .each
// now add all rows
var loop = function () {
if (rows.length === 0) return callback(null) // done
var a = rows.shift()
db._db.insert('activities', a).run(function (err, res) {
if (err) return callback(err)
loop()
})
}
loop()
})
},
db._db.update('sessions', { ended_at: session.ended_at })
.where({ id: session.id }).run,
function (res, callback) {
debug('connectivity')
// FIXME:: this is really slow on sqlite - there's no indexes
// or nothing so takes forever, do as with activity !!!
var e = null
var sql = `SELECT
a.*,
l.public_ip,
l.reverse_dns,
l.asnumber,
l.asname,
l.countryCode,
l.city,
l.lat,
l.lon,
l.connstart l_timestamp,
a.timestamp started_at,
MIN(b.timestamp) ended_at
FROM connectivity a
LEFT JOIN connectivity b
ON a.mac = b.mac
AND b.connected = 0
AND a.timestamp <= b.timestamp
LEFT JOIN location l
ON a.timestamp = l.connstart
WHERE a.connected = 1
GROUP BY a.timestamp
ORDER BY a.mac ASC, started_at ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
return
};
var doconn = function (lid) {
var o = {
session_id: session.id,
location_id: lid,
started_at: new Date(row.started_at),
ended_at: (row.ended_at ? new Date(row.ended_at) : session.ended_at),
guid: getstr(row, 'guid'),
friendly_name: getstr(row, 'row.friendlyname'),
description: getstr(row, 'row.description'),
dns_suffix: getstr(row, 'dnssuffix'),
mac: getstr(row, 'mac'),
ips: row.ips.split(','),
gateways: row.gateways.split(','),
dnses: row.dnses.split(','),
t_speed: row.tspeed,
r_speed: row.rspeed,
wireless: row.wireless,
profile: getstr(row, 'profile'),
ssid: getstr(row, 'ssid'),
bssid: getstr(row, 'bssid'),
bssid_type: getstr(row, 'bssidtype'),
phy_type: getstr(row, 'phytype'),
phy_index: row.phyindex,
channel: row.channel
}
db._db.insert('connections', o).run(function (err, res) {
e = e || err
})
}
if (row.public_ip) {
// insert/get the location first
var l = {
public_ip: getstr(row, 'public_ip'),
reverse_dns: getstr(row, 'reverse_dns'),
asn_number: getstr(row, 'asnumber'),
asn_name: getstr(row, 'asname'),
country_code: getstr(row, 'countryCode'),
city: getstr(row, 'city'),
latitude: getstr(row, 'lat'),
longitude: getstr(row, 'lon')
}
var locations = 'locations'
db._db.select('*').from(locations)
.where(l).rows(function (err, rows) {
if (err) return callback(err)
if (rows.length === 0) {
db._db.insert(locations, row).returning('*').row(function (err, res) {
if (err) return callback(err)
doconn(res.id)
})
} else {
doconn(rows[0].id)
}
})
} else {
doconn(null)
}
}, function (err) {
// .each complete
e = e || err
callback(e)
})
},
function (callback) {
debug('dnslogs')
var isql = `
INSERT INTO dns_logs(connection_id,
type, ip, host, protocol,
source_ip, destination_ip,
source_port, destination_port, logged_at)
SELECT c.id,
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9
FROM connections c WHERE c.started_at = $10;`
var e = null
var sql = `SELECT * FROM dns ORDER BY timestamp ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
return
};
var params = [
row.type, row.ip, row.host, row.protocol,
row.srcip, row.destip, row.srcport, row.destport,
new Date(row.timestamp), new Date(row.connstart)
]
db._db.raw(isql, params).run(function (err, res) {
e = e || err
})
}, function (err) {
// .each complete
e = e || err
callback(e)
})
},
function (callback) {
debug('httplogs')
var isql = `
INSERT INTO http_logs(
connection_id,
http_verb,
http_verb_param,
http_status_code,
http_host,
referer,
content_type,
content_length,
protocol,
source_ip,
destination_ip,
source_port,
destination_port,
logged_at)
SELECT c.id,
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13
FROM connections c WHERE c.started_at = $14;`
var e = null
var sql = `SELECT * FROM http ORDER BY timestamp ASC`
file.db.each(sql, function (err, row) {
if (e || err) {
e = e || err
return
};
var params = [
getstr(row, 'httpverb'),
getstr(row, 'httpverbparam'),
getstr(row, 'httpstatuscode'),
getstr(row, 'httphost'),
getstr(row, 'referer'),
getstr(row, 'contenttype'),
getstr(row, 'contentlength'),
row['protocol'],
getstr(row, 'srcip'),
getstr(row, 'destip'),
row['srcport'],
row['destport'],
new Date(row.timestamp),
new Date(row.connstart)
]
db._db.raw(isql, params).run(function (err, res) {
e = e || err
})
}, function (err) {
// .each complete
e = e || err
callback(e)
})
}
/*,
TODO: these are working but do we need these ?
function(callback) {
debug('activity_io');
// Count foreground/background io for activities (running apps)
//
// FIXME: interpretation of the count really depends on the polling
// interval, it would make more sense to store the real duration
// instead no ... ??
//
var sql = `INSERT INTO activity_io
SELECT
a.id,
a.session_id,
a.name,
a.description,
a.idle,
a.pid,
a.logged_at,
a.finished_at,
COUNT(io.logged_at)
FROM activities a
LEFT JOIN io
ON io.logged_at BETWEEN a.logged_at AND a.finished_at
AND io.pid = a.pid
AND io.name = a.name
AND io.session_id = a.session_id
WHERE a.session_id = $1
GROUP BY a.id
ORDER BY a.id;`;
db._db.raw(sql, [session.id]).run(callback);
},
function(res, callback) {
debug('processes_running');
// Fill the processes_running table
// TODO: what's with the intervals in the queries .. ?
var sql = `INSERT INTO processes_running
SELECT
$1::integer as device_id,
$2::integer as session_id,
p.dname,
(
SELECT
COUNT(*)
FROM
(
SELECT 1 AS count
FROM processes
WHERE name = p.dname
AND session_id = $2::integer
AND logged_at BETWEEN $3::timestamp AND $4::timestamp
GROUP BY date_trunc('minute',logged_at + interval '30 seconds')
) sq
)::integer AS process_running,
(
SELECT
EXTRACT (
EPOCH FROM (
LEAST(date_trunc('minute',ended_at + interval '30 seconds'), $4::timestamp)
-
GREATEST(date_trunc('minute',started_at + interval '30 seconds'), $3::timestamp)
)
)/60
FROM sessions
WHERE id = $2::integer
) AS session_running,
$3::timestamp as start_at,
$4::timestamp as end_at
FROM(
SELECT
DISTINCT name AS dname
FROM processes
WHERE session_id = $2::integer
) p`;
// run the above query for 1h bins from session start to end
var bin = 60 * 60 * 1000;
var from = Math.floor(session.started_at.getTime()/bin)*bin;
var to = Math.floor(session.ended_at.getTime()/bin+1)*bin;
var loop = function(d) {
if (d>=to) return callback(null);
var args = [session.device_id,
session.id,
new Date(d),
new Date(d+bin)];
db._db.raw(sql, args).run(function(err,res) {
if (err) return callback(err); // stop on error
process.nextTick(loop,d+bin);
});
};
loop(from);
}
*/
],
function (err) {
// if we receive error here, something went wrong above ...
async.waterfall([
function (callback) {
if (err) {
debug('failed to process session ' + session.id, err)
if (session.id) { db._db.delete('sessions').where({ id: session.id }).run(callback) }
callback(err)
} else {
debug('session inserted ' + session.id)
callback(null, null)
}
},
function (res, callback) {
if (file.db) { // sqlite conn
file.db.close(function () { callback(null) })
} else { callback(null) }
},
function (callback) {
if (file.uncompressed_path) { // tmp file
fs.unlink(file.uncompressed_path, function () { callback(null) })
} else { callback(null) }
}
], function () {
// return the original error (if any)
return cb(err)
}) // cleanup waterfall
}) // main watefall
} // process
| inria-muse/hostview-processing | app/lib/process_sqlite.js | JavaScript | mit | 29,384 |
version https://git-lfs.github.com/spec/v1
oid sha256:082a71326f3ffc5d4a12f1e2d1226bde6726d7e65fd21e9e633e1aa7bdd656d8
size 117145
| yogeshsaroya/new-cdnjs | ajax/libs/angular-data/0.4.1/angular-data.js | JavaScript | mit | 131 |
define(['jquery', 'pubsub'], function($, pubsub) {
function AudioPlayer(audio){
this.audio = audio;
this._initSubscribe();
this.startPos = 0;
this.endPos = 0;
this.loopEnabled = false;
}
AudioPlayer.prototype._initSubscribe = function() {
var self = this;
$.subscribe("AudioCursor-clickedAudio", function(el, posCursor) {
self.startPos = posCursor;
self.audio.disableLoop();
});
$.subscribe("AudioCursor-selectedAudio", function(el, startPos, endPos) {
self.startPos = startPos;
self.endPos = endPos;
self.audio.loop(startPos, endPos);
});
$.subscribe("ToPlayer-play", function() {
self.audio.play(self.startPos);
});
$.subscribe("ToPlayer-pause", function() {
self.startPos = null;
self.audio.pause();
});
$.subscribe("Audio-end", function(){
self.startPos = null;
});
$.subscribe("ToPlayer-stop", function() {
self.startPos = null;
self.audio.stop();
});
$.subscribe('ToAudioPlayer-disable', function(){
self.audio.disable(true); //true to not disable audio
});
$.subscribe('ToAudioPlayer-enable', function(){
self.audio.enable(true); //true to not disable audio
});
$.subscribe('ToPlayer-playPause', function() {
if (self.audio.isPlaying){
$.publish('ToPlayer-pause');
} else {
self.audio.play(self.startPos);
}
});
$.subscribe('ToPlayer-toggleLoop', function() {
var toggle;
if (self.loopEnabled){
toggle = self.audio.disableLoopSong();
}else{
toggle = self.audio.enableLoopSong();
}
if (toggle){
self.loopEnabled = !self.loopEnabled;
$.publish('PlayerModel-toggleLoop', self.loopEnabled);
}
});
};
return AudioPlayer;
}); | dmmz/LeadsheetJS | modules/Audio/src/AudioPlayer.js | JavaScript | mit | 1,676 |
export class Schema {
constructor(){
}
createErrorMessage(schemaErrorObj, root){
let {errors, path} = schemaErrorObj;
let pathName = path.replace('$root', root);
let errorList = errors.reduce((errorListTemp, error, index)=>{
return `${errorListTemp}
${index+1}. ${error}`
}, '')
let errorMessage = `
Schema Error:
Path: ${pathName}
Errors: ${errorList}
`
return errorMessage;
}
}; | influencetech/ivx-js | src/modules/validation/schema/schema.js | JavaScript | mit | 525 |
// Welcome. In this kata, you are asked to square every digit of a number.
//
// For example, if we run 9119 through the function, 811181 will come out.
//
// Note: The function accepts an integer and returns an integer
function squareDigits(num){
let digits = (""+num).split("");
let arr=[];
for (var i = 0; i < digits.length; i++) {
arr.push(Math.pow(digits[i],2));
}
return +arr.join('')
}
//top codewars solution
function squareDigits(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}
| mariajcb/codewars | 7kyu/square-every-digit.js | JavaScript | mit | 552 |
(function( $ ) {
'use strict';
var that;
var fgj2wp = {
plugin_id: 'fgj2wp',
fatal_error: '',
/**
* Manage the behaviour of the Skip Media checkbox
*/
hide_unhide_media: function() {
$("#media_import_box").toggle(!$("#skip_media").is(':checked'));
},
/**
* Security question before deleting WordPress content
*/
check_empty_content_option: function () {
var confirm_message;
var action = $('input:radio[name=empty_action]:checked').val();
switch ( action ) {
case 'newposts':
confirm_message = objectL10n.delete_new_posts_confirmation_message;
break;
case 'all':
confirm_message = objectL10n.delete_all_confirmation_message;
break;
default:
alert(objectL10n.delete_no_answer_message);
return false;
break;
}
return confirm(confirm_message);
},
/**
* Start the logger
*/
start_logger: function() {
that.stop_logger_triggered = false;
clearTimeout(that.timeout);
that.timeout = setTimeout(that.update_display, 1000);
},
/**
* Stop the logger
*/
stop_logger: function() {
that.stop_logger_triggered = true;
},
/**
* Update the display
*/
update_display: function() {
that.timeout = setTimeout(that.update_display, 1000);
// Actions
if ( $("#logger_autorefresh").is(":checked") ) {
that.display_logs();
}
that.update_progressbar();
that.update_wordpress_info();
if ( that.stop_logger_triggered ) {
clearTimeout(that.timeout);
}
},
/**
* Display the logs
*/
display_logs: function() {
$.ajax({
url: objectPlugin.log_file_url,
cache: false
}).done(function(result) {
$("#logger").html('');
result.split("\n").forEach(function(row) {
if ( row.substr(0, 7) === '[ERROR]' || row === 'IMPORT STOPPED BY USER') {
row = '<span class="error_msg">' + row + '</span>'; // Mark the errors in red
}
// Test if the import is complete
else if ( row === 'IMPORT COMPLETE' ) {
row = '<span class="complete_msg">' + row + '</span>'; // Mark the complete message in green
$('#action_message').html(objectL10n.import_complete)
.removeClass('failure').addClass('success');
}
$("#logger").append(row + "<br />\n");
});
$("#logger").append('<span class="error_msg">' + that.fatal_error + '</span>' + "<br />\n");
});
},
/**
* Update the progressbar
*/
update_progressbar: function() {
$.ajax({
url: objectPlugin.progress_url,
cache: false,
dataType: 'json'
}).done(function(result) {
// Move the progress bar
var progress = Number(result.current) / Number(result.total) * 100;
$('#progressbar').progressbar('option', 'value', progress);
});
},
/**
* Update WordPress database info
*/
update_wordpress_info: function() {
var data = 'action=' + that.plugin_id + '_import&plugin_action=update_wordpress_info';
$.ajax({
method: "POST",
url: ajaxurl,
data: data
}).done(function(result) {
$('#fgj2wp_database_info_content').html(result);
});
},
/**
* Empty WordPress content
*
* @returns {Boolean}
*/
empty_wp_content: function() {
if (that.check_empty_content_option()) {
// Start displaying the logs
that.start_logger();
$('#empty').attr('disabled', 'disabled'); // Disable the button
var data = $('#form_empty_wordpress_content').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=empty';
$.ajax({
method: "POST",
url: ajaxurl,
data: data
}).done(function() {
that.stop_logger();
$('#empty').removeAttr('disabled'); // Enable the button
alert(objectL10n.content_removed_from_wordpress);
});
}
return false;
},
/**
* Test the database connection
*
* @returns {Boolean}
*/
test_database: function() {
// Start displaying the logs
that.start_logger();
$('#test_database').attr('disabled', 'disabled'); // Disable the button
var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=test_database';
$.ajax({
method: 'POST',
url: ajaxurl,
data: data,
dataType: 'json'
}).done(function(result) {
that.stop_logger();
$('#test_database').removeAttr('disabled'); // Enable the button
if ( typeof result.message !== 'undefined' ) {
$('#database_test_message').toggleClass('success', result.status === 'OK')
.toggleClass('failure', result.status !== 'OK')
.html(result.message);
}
}).fail(function(result) {
that.stop_logger();
$('#test_database').removeAttr('disabled'); // Enable the button
that.fatal_error = result.responseText;
});
return false;
},
/**
* Test the FTP connection
*
* @returns {Boolean}
*/
test_ftp: function() {
// Start displaying the logs
that.start_logger();
$('#test_ftp').attr('disabled', 'disabled'); // Disable the button
var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=test_ftp';
$.ajax({
method: 'POST',
url: ajaxurl,
data: data,
dataType: 'json'
}).done(function(result) {
that.stop_logger();
$('#test_ftp').removeAttr('disabled'); // Enable the button
if ( typeof result.message !== 'undefined' ) {
$('#ftp_test_message').toggleClass('success', result.status === 'OK')
.toggleClass('failure', result.status !== 'OK')
.html(result.message);
}
}).fail(function(result) {
that.stop_logger();
$('#test_ftp').removeAttr('disabled'); // Enable the button
that.fatal_error = result.responseText;
});
return false;
},
/**
* Save the settings
*
* @returns {Boolean}
*/
save: function() {
// Start displaying the logs
that.start_logger();
$('#save').attr('disabled', 'disabled'); // Disable the button
var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=save';
$.ajax({
method: "POST",
url: ajaxurl,
data: data
}).done(function() {
that.stop_logger();
$('#save').removeAttr('disabled'); // Enable the button
alert(objectL10n.settings_saved);
});
return false;
},
/**
* Start the import
*
* @returns {Boolean}
*/
start_import: function() {
that.fatal_error = '';
// Start displaying the logs
that.start_logger();
// Disable the import button
that.import_button_label = $('#import').val();
$('#import').val(objectL10n.importing).attr('disabled', 'disabled');
// Show the stop button
$('#stop-import').show();
// Clear the action message
$('#action_message').html('');
// Run the import
var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=import';
$.ajax({
method: "POST",
url: ajaxurl,
data: data
}).done(function(result) {
if (result) {
that.fatal_error = result;
}
that.stop_logger();
that.reactivate_import_button();
});
return false;
},
/**
* Reactivate the import button
*
*/
reactivate_import_button: function() {
$('#import').val(that.import_button_label).removeAttr('disabled');
$('#stop-import').hide();
},
/**
* Stop import
*
* @returns {Boolean}
*/
stop_import: function() {
$('#stop-import').attr('disabled', 'disabled');
$('#action_message').html(objectL10n.import_stopped_by_user)
.removeClass('success').addClass('failure');
// Stop the import
var data = $('#form_import').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=stop_import';
$.ajax({
method: "POST",
url: ajaxurl,
data: data
}).done(function() {
$('#stop-import').removeAttr('disabled'); // Enable the button
that.reactivate_import_button();
});
return false;
},
/**
* Modify the internal links
*
* @returns {Boolean}
*/
modify_links: function() {
// Start displaying the logs
that.start_logger();
$('#modify_links').attr('disabled', 'disabled'); // Disable the button
var data = $('#form_modify_links').serialize() + '&action=' + that.plugin_id + '_import&plugin_action=modify_links';
$.ajax({
method: "POST",
url: ajaxurl,
data: data
}).done(function(result) {
if (result) {
that.fatal_error = result;
}
that.stop_logger();
$('#modify_links').removeAttr('disabled'); // Enable the button
alert(objectL10n.internal_links_modified);
});
return false;
}
};
/**
* Actions to run when the DOM is ready
*/
$(function() {
that = fgj2wp;
$('#progressbar').progressbar({value : 0});
// Skip media checkbox
$("#skip_media").bind('click', that.hide_unhide_media);
that.hide_unhide_media();
// Empty WordPress content confirmation
$("#form_empty_wordpress_content").bind('submit', that.check_empty_content_option);
// Partial import checkbox
$("#partial_import").hide();
$("#partial_import_toggle").click(function() {
$("#partial_import").slideToggle("slow");
});
// Empty button
$('#empty').click(that.empty_wp_content);
// Test database button
$('#test_database').click(that.test_database);
// Test FTP button
$('#test_ftp').click(that.test_ftp);
// Save settings button
$('#save').click(that.save);
// Import button
$('#import').click(that.start_import);
// Stop import button
$('#stop-import').click(that.stop_import);
// Modify links button
$('#modify_links').click(that.modify_links);
// Display the logs
$('#logger_autorefresh').click(that.display_logs);
});
/**
* Actions to run when the window is loaded
*/
$( window ).load(function() {
});
})( jQuery );
| Magnition/innova-partnerships | www/wordpress/wp-content/plugins/fg-joomla-to-wordpress/admin/js/fg-joomla-to-wordpress-admin.js | JavaScript | mit | 10,268 |
$(function()
{
$("#content").focus(function()
{
$(this).animate({"height": "85px",}, "fast" );
$("#button_block").slideDown("fast");
return false;
});
$("#cancel").click(function()
{
$("#content").animate({"height": "30px",}, "fast" );
$("#button_block").slideUp("fast");
return false;
});
function dragDrop(drag,i,j){
$(drag+i).draggable({
helper: 'clone',
revert : function(event, ui) {
// on older version of jQuery use "draggable"
// $(this).data("draggable")
// on 2.x versions of jQuery use "ui-draggable"
// $(this).data("ui-draggable")
$(this).data("uiDraggable").originalPosition = {
top : 0,
left : 0
};
// return boolean
return !event;
// that evaluate like this:
// return event !== false ? false : true;
}
});
if(j==0){
$('#dropzone'+j).droppable({
tolerance: 'touch',
activeClass: 'ui-state-default',
hoverClass: 'ui-state-hover',
drop: function(event, ui) {
var id = ui.draggable.attr("id");
var res = id.substr(9,9);
var post = parseInt(res);
text = $('div#contenttext'+post).text();
// alert(id);
$('#text').val(text);
$.ajax({
type: "POST",
url: "index.php",
data: text,
success:function(data){
$( ".tw-posts" ).prepend("<div class='tw-update'> <div class='post-container2'>"+text+"</div></div>");
$( "#button" ).trigger( "click" );
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
console.log(text);
}
});
} else {
$('#dropzone'+j).droppable({
tolerance: 'touch',
activeClass: 'ui-state-default',
hoverClass: 'ui-state-hover'+j,
drop: function(event, ui) {
var id = ui.draggable.attr("id");
var res = id.substr(9,9);
var post = parseInt(res);
text = $('div#contenttext'+post).text();
// alert(id);
$('#text').val(text);
$.ajax({
type: "POST",
url: "index.php",
data: text,
success:function(data){
$( ".tw-posts" ).prepend("<div class='tw-update'> <div class='post-container2'>"+text+"</div></div>");
$( "#button" ).trigger( "click" );
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
console.log(text);
}
});
}
}
for (i=0;i<10; i++)
{
dragDrop("#draggable",i,0);
dragDrop("#draggabletw",i,1);
}
$('#publish').click(
function(){
$.ajax({
type: "POST",
url: "index.php",
data: $("#form2").serialize(), // serializes the form's elements.
beforeSend: function(){
},
success: function(data)
{
alert(data); // show response from the php script.
}
});
}
);
/*$("#form2").submit(function() {
var url = "publish.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#form2").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});*/
});
| DarioMundjar/dashpool | js/main.js | JavaScript | mit | 3,272 |
'use strict';
angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
function($scope, $http, $location, Authentication) {
$scope.authentication = Authentication;
$(".signin").parent("section").css("height", "100%");
// If user is signed in then redirect back home
if ($scope.authentication.user) $location.path('/timeline');
$scope.signup = function() {
$http.post('/auth/signup', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/signin');
}).error(function(response) {
$scope.error = response.message;
});
};
$scope.signin = function() {
$http.post('/auth/signin', $scope.credentials).success(function(response) {
// If successful we assign the response to the global user model
$scope.authentication.user = response;
// And redirect to the index page
$location.path('/timeline');
}).error(function(response) {
$scope.error = response.message;
});
};
}
]); | mars2601/Eventure-Prod | public/modules/users/controllers/authentication.client.controller.js | JavaScript | mit | 1,190 |
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
'use strict';
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
var util = require('./util');
var binarySearch = require('./binary-search');
var ArraySet = require('./array-set').ArraySet;
var base64VLQ = require('./base64-vlq');
var quickSort = require('./quick-sort').quickSort;
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap);
}
SourceMapConsumer.fromSourceMap = function (aSourceMap) {
return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function get() {
if (!this.__generatedMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function get() {
if (!this.__originalMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
var c = aStr.charAt(index);
return c === ";" || c === ",";
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
throw new Error("Subclasses must implement _parseMappings");
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer.LEAST_UPPER_BOUND = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source === null ? null : this._sources.at(mapping.source);
if (source != null && sourceRoot != null) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name === null ? null : this._names.at(mapping.name)
};
}, this).forEach(aCallback, context);
};
/**
* Returns all generated line and column information for the original source,
* line, and column provided. If no column is provided, returns all mappings
* corresponding to a either the line we are searching for or the next
* closest line that has any mappings. Otherwise, returns all mappings
* corresponding to the given line and either the column we are searching for
* or the next closest column that has any offsets.
*
* The only argument is an object with the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: Optional. the column number in the original source.
*
* and an array of objects is returned, each with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
var line = util.getArg(aArgs, 'line');
// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
// returns the index of the closest mapping less than the needle. By
// setting needle.originalColumn to 0, we thus find the last mapping for
// the given line, provided such a mapping exists.
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: line,
originalColumn: util.getArg(aArgs, 'column', 0)
};
if (this.sourceRoot != null) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
if (!this._sources.has(needle.source)) {
return [];
}
needle.source = this._sources.indexOf(needle.source);
var mappings = [];
var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND);
if (index >= 0) {
var mapping = this._originalMappings[index];
if (aArgs.column === undefined) {
var originalLine = mapping.originalLine;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we found. Since
// mappings are sorted, this is guaranteed to find all mappings for
// the line we found.
while (mapping && mapping.originalLine === originalLine) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
} else {
var originalColumn = mapping.originalColumn;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we were searching for.
// Since mappings are sorted, this is guaranteed to find all mappings for
// the line we are searching for.
while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
}
}
return mappings;
};
exports.SourceMapConsumer = SourceMapConsumer;
/**
* A BasicSourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: Optional. The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function BasicSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
// Some source maps produce relative source paths like "./foo.js" instead of
// "foo.js". Normalize these first so that future comparisons will succeed.
// See bugzil.la/1090768.
sources = sources.map(util.normalize);
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns BasicSourceMapConsumer
*/
BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(BasicSourceMapConsumer.prototype);
var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
smc.file = aSourceMap._file;
// Because we are modifying the entries (by converting string sources and
// names to indices into the sources and names ArraySets), we have to make
// a copy of the entry or else bad things happen. Shared mutable state
// strikes again! See github issue #191.
var generatedMappings = aSourceMap._mappings.toArray().slice();
var destGeneratedMappings = smc.__generatedMappings = [];
var destOriginalMappings = smc.__originalMappings = [];
for (var i = 0, length = generatedMappings.length; i < length; i++) {
var srcMapping = generatedMappings[i];
var destMapping = new Mapping();
destMapping.generatedLine = srcMapping.generatedLine;
destMapping.generatedColumn = srcMapping.generatedColumn;
if (srcMapping.source) {
destMapping.source = sources.indexOf(srcMapping.source);
destMapping.originalLine = srcMapping.originalLine;
destMapping.originalColumn = srcMapping.originalColumn;
if (srcMapping.name) {
destMapping.name = names.indexOf(srcMapping.name);
}
destOriginalMappings.push(destMapping);
}
destGeneratedMappings.push(destMapping);
}
quickSort(smc.__originalMappings, util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
BasicSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
get: function get() {
return this._sources.toArray().map(function (s) {
return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
/**
* Provide the JIT with a nice shape / hidden class.
*/
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var length = aStr.length;
var index = 0;
var cachedSegments = {};
var temp = {};
var originalMappings = [];
var generatedMappings = [];
var mapping, str, segment, end, value;
while (index < length) {
if (aStr.charAt(index) === ';') {
generatedLine++;
index++;
previousGeneratedColumn = 0;
} else if (aStr.charAt(index) === ',') {
index++;
} else {
mapping = new Mapping();
mapping.generatedLine = generatedLine;
// Because each offset is encoded relative to the previous one,
// many segments often have the same encoding. We can exploit this
// fact by caching the parsed variable length fields of each segment,
// allowing us to avoid a second parse if we encounter the same
// segment again.
for (end = index; end < length; end++) {
if (this._charIsMappingSeparator(aStr, end)) {
break;
}
}
str = aStr.slice(index, end);
segment = cachedSegments[str];
if (segment) {
index += str.length;
} else {
segment = [];
while (index < end) {
base64VLQ.decode(aStr, index, temp);
value = temp.value;
index = temp.rest;
segment.push(value);
}
if (segment.length === 2) {
throw new Error('Found a source, but no line and column');
}
if (segment.length === 3) {
throw new Error('Found a source and line, but no column');
}
cachedSegments[str] = segment;
}
// Generated column.
mapping.generatedColumn = previousGeneratedColumn + segment[0];
previousGeneratedColumn = mapping.generatedColumn;
if (segment.length > 1) {
// Original source.
mapping.source = previousSource + segment[1];
previousSource += segment[1];
// Original line.
mapping.originalLine = previousOriginalLine + segment[2];
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
// Original column.
mapping.originalColumn = previousOriginalColumn + segment[3];
previousOriginalColumn = mapping.originalColumn;
if (segment.length > 4) {
// Original name.
mapping.name = previousName + segment[4];
previousName += segment[4];
}
}
generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
originalMappings.push(mapping);
}
}
}
quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
this.__generatedMappings = generatedMappings;
quickSort(originalMappings, util.compareByOriginalPositions);
this.__originalMappings = originalMappings;
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
};
/**
* Compute the last column for each generated mapping. The last column is
* inclusive.
*/
BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
for (var index = 0; index < this._generatedMappings.length; ++index) {
var mapping = this._generatedMappings[index];
// Mappings do not contain a field for the last generated columnt. We
// can come up with an optimistic estimate, however, by assuming that
// mappings are contiguous (i.e. given two consecutive mappings, the
// first mapping ends where the second one starts).
if (index + 1 < this._generatedMappings.length) {
var nextMapping = this._generatedMappings[index + 1];
if (mapping.generatedLine === nextMapping.generatedLine) {
mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
continue;
}
}
// The last mapping for each line spans the entire line.
mapping.lastGeneratedColumn = Infinity;
}
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index >= 0) {
var mapping = this._generatedMappings[index];
if (mapping.generatedLine === needle.generatedLine) {
var source = util.getArg(mapping, 'source', null);
if (source !== null) {
source = this._sources.at(source);
if (this.sourceRoot != null) {
source = util.join(this.sourceRoot, source);
}
}
var name = util.getArg(mapping, 'name', null);
if (name !== null) {
name = this._names.at(name);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: name
};
}
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
if (!this.sourcesContent) {
return false;
}
return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) {
return sc == null;
});
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* availible.
*/
BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot != null) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
}
if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
// This function is used recursively from
// IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
// don't want to throw if we can't find the source - we just want to
// return null, so we provide a flag to exit gracefully.
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
var source = util.getArg(aArgs, 'source');
if (this.sourceRoot != null) {
source = util.relative(this.sourceRoot, source);
}
if (!this._sources.has(source)) {
return {
line: null,
column: null,
lastColumn: null
};
}
source = this._sources.indexOf(source);
var needle = {
source: source,
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index >= 0) {
var mapping = this._originalMappings[index];
if (mapping.source === needle.source) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
};
}
}
return {
line: null,
column: null,
lastColumn: null
};
};
exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
/**
* An IndexedSourceMapConsumer instance represents a parsed source map which
* we can query for information. It differs from BasicSourceMapConsumer in
* that it takes "indexed" source maps (i.e. ones with a "sections" field) as
* input.
*
* The only parameter is a raw source map (either as a JSON string, or already
* parsed to an object). According to the spec for indexed source maps, they
* have the following attributes:
*
* - version: Which version of the source map spec this map is following.
* - file: Optional. The generated file this source map is associated with.
* - sections: A list of section definitions.
*
* Each value under the "sections" field has two fields:
* - offset: The offset into the original specified at which this section
* begins to apply, defined as an object with a "line" and "column"
* field.
* - map: A source map definition. This source map could also be indexed,
* but doesn't have to be.
*
* Instead of the "map" field, it's also possible to have a "url" field
* specifying a URL to retrieve a source map from, but that's currently
* unsupported.
*
* Here's an example source map, taken from the source map spec[0], but
* modified to omit a section which uses the "url" field.
*
* {
* version : 3,
* file: "app.js",
* sections: [{
* offset: {line:100, column:10},
* map: {
* version : 3,
* file: "section.js",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AAAA,E;;ABCDE;"
* }
* }],
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
*/
function IndexedSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sections = util.getArg(sourceMap, 'sections');
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
this._sources = new ArraySet();
this._names = new ArraySet();
var lastOffset = {
line: -1,
column: 0
};
this._sections = sections.map(function (s) {
if (s.url) {
// The url field will require support for asynchronicity.
// See https://github.com/mozilla/source-map/issues/16
throw new Error('Support for url field in sections not implemented.');
}
var offset = util.getArg(s, 'offset');
var offsetLine = util.getArg(offset, 'line');
var offsetColumn = util.getArg(offset, 'column');
if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
throw new Error('Section offsets must be ordered and non-overlapping.');
}
lastOffset = offset;
return {
generatedOffset: {
// The offset fields are 0-based, but we use 1-based indices when
// encoding/decoding from VLQ.
generatedLine: offsetLine + 1,
generatedColumn: offsetColumn + 1
},
consumer: new SourceMapConsumer(util.getArg(s, 'map'))
};
});
}
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
/**
* The version of the source mapping spec that we are consuming.
*/
IndexedSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
get: function get() {
var sources = [];
for (var i = 0; i < this._sections.length; i++) {
for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
sources.push(this._sections[i].consumer.sources[j]);
}
};
return sources;
}
});
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
// Find the section containing the generated position we're trying to map
// to an original position.
var sectionIndex = binarySearch.search(needle, this._sections, function (needle, section) {
var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
if (cmp) {
return cmp;
}
return needle.generatedColumn - section.generatedOffset.generatedColumn;
});
var section = this._sections[sectionIndex];
if (!section) {
return {
source: null,
line: null,
column: null,
name: null
};
}
return section.consumer.originalPositionFor({
line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
bias: aArgs.bias
});
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
return this._sections.every(function (s) {
return s.consumer.hasContentsOfAllSources();
});
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var content = section.consumer.sourceContentFor(aSource, true);
if (content) {
return content;
}
}
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
// Only consider this section if the requested source is in the list of
// sources of the consumer.
if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
continue;
}
var generatedPosition = section.consumer.generatedPositionFor(aArgs);
if (generatedPosition) {
var ret = {
line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
};
return ret;
}
}
return {
line: null,
column: null
};
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
this.__generatedMappings = [];
this.__originalMappings = [];
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var sectionMappings = section.consumer._generatedMappings;
for (var j = 0; j < sectionMappings.length; j++) {
var mapping = sectionMappings[i];
var source = section.consumer._sources.at(mapping.source);
if (section.consumer.sourceRoot !== null) {
source = util.join(section.consumer.sourceRoot, source);
}
this._sources.add(source);
source = this._sources.indexOf(source);
var name = section.consumer._names.at(mapping.name);
this._names.add(name);
name = this._names.indexOf(name);
// The mappings coming from the consumer for the section have
// generated positions relative to the start of the section, so we
// need to offset them to be relative to the start of the concatenated
// generated file.
var adjustedMapping = {
source: source,
generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
generatedColumn: mapping.column + (section.generatedOffset.generatedLine === mapping.generatedLine) ? section.generatedOffset.generatedColumn - 1 : 0,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: name
};
this.__generatedMappings.push(adjustedMapping);
if (typeof adjustedMapping.originalLine === 'number') {
this.__originalMappings.push(adjustedMapping);
}
};
};
quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
quickSort(this.__originalMappings, util.compareByOriginalPositions);
};
exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
});
//# sourceMappingURL=source-map-consumer-compiled.js.map | patelsan/fetchpipe | node_modules/source-map/lib/source-map/source-map-consumer-compiled.js | JavaScript | mit | 38,276 |
export const x = {"viewBox":"0 0 12 16","children":[{"name":"path","attribs":{"fill-rule":"evenodd","d":"M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"},"children":[]}],"attribs":{}}; | wmira/react-icons-kit | src/oct/x.js | JavaScript | mit | 254 |
// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*-
// vim:set ft=javascript ts=2 sw=2 sts=2 cindent:
require('./lib/webfont');
//jquery
var $ = require('jquery');
var Util = (function(window, undefined) {
var fontLoadTimeout = 5000; // 5 seconds
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var isMac = navigator.platform == 'MacIntel'; // XXX should we go broader?
var cmp = function(a,b) {
return a < b ? -1 : a > b ? 1 : 0;
};
var cmpArrayOnFirstElement = function(a,b) {
a = a[0];
b = b[0];
return a < b ? -1 : a > b ? 1 : 0;
};
var unitAgo = function(n, unit) {
if (n == 1) return "" + n + " " + unit + " ago";
return "" + n + " " + unit + "s ago";
};
var formatTimeAgo = function(time) {
if (time == -1000) {
return "never"; // FIXME make the server return the server time!
}
var nowDate = new Date();
var now = nowDate.getTime();
var diff = Math.floor((now - time) / 1000);
if (!diff) return "just now";
if (diff < 60) return unitAgo(diff, "second");
diff = Math.floor(diff / 60);
if (diff < 60) return unitAgo(diff, "minute");
diff = Math.floor(diff / 60);
if (diff < 24) return unitAgo(diff, "hour");
diff = Math.floor(diff / 24);
if (diff < 7) return unitAgo(diff, "day");
if (diff < 28) return unitAgo(Math.floor(diff / 7), "week");
var thenDate = new Date(time);
var result = thenDate.getDate() + ' ' + monthNames[thenDate.getMonth()];
if (thenDate.getYear() != nowDate.getYear()) {
result += ' ' + thenDate.getFullYear();
}
return result;
};
var realBBox = function(span) {
var box = span.rect.getBBox();
var chunkTranslation = span.chunk.translation;
var rowTranslation = span.chunk.row.translation;
box.x += chunkTranslation.x + rowTranslation.x;
box.y += chunkTranslation.y + rowTranslation.y;
return box;
};
var escapeHTML = function(str) {
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
};
var escapeHTMLandQuotes = function(str) {
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\"/g,'"');
};
var escapeHTMLwithNewlines = function(str) {
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/\n/g,'<br/>');
};
var escapeQuotes = function(str) {
// we only use double quotes for HTML attributes
return str.replace(/\"/g,'"');
};
var getSpanLabels = function(spanTypes, spanType) {
var type = spanTypes[spanType];
return type && type.labels || [];
};
var spanDisplayForm = function(spanTypes, spanType) {
var labels = getSpanLabels(spanTypes, spanType);
return labels[0] || spanType;
};
var getArcLabels = function(spanTypes, spanType, arcType, relationTypesHash) {
var type = spanTypes[spanType];
var arcTypes = type && type.arcs || [];
var arcDesc = null;
// also consider matches without suffix number, if any
var noNumArcType;
if (arcType) {
var splitType = arcType.match(/^(.*?)(\d*)$/);
noNumArcType = splitType[1];
}
$.each(arcTypes, function(arcno, arcDescI) {
if (arcDescI.type == arcType || arcDescI.type == noNumArcType) {
arcDesc = arcDescI;
return false;
}
});
// fall back to relation types for unconfigured or missing def
if (!arcDesc) {
arcDesc = $.extend({}, relationTypesHash[arcType] || relationTypesHash[noNumArcType]);
}
return arcDesc && arcDesc.labels || [];
};
var arcDisplayForm = function(spanTypes, spanType, arcType, relationTypesHash) {
var labels = getArcLabels(spanTypes, spanType, arcType, relationTypesHash);
return labels[0] || arcType;
};
// TODO: switching to use of $.param(), this function should
// be deprecated and removed.
var objectToUrlStr = function(o) {
a = [];
$.each(o, function(key,value) {
a.push(key+"="+encodeURIComponent(value));
});
return a.join("&");
};
// color name RGB list, converted from
// http://www.w3schools.com/html/html_colornames.asp
// with perl as
// perl -e 'print "var colors = {\n"; while(<>) { /(\S+)\s+\#([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})\s*/i or die "Failed to parse $_"; ($r,$g,$b)=(hex($2),hex($3),hex($4)); print " '\''",lc($1),"'\'':\[$r,$g,$b\],\n" } print "};\n" '
var colors = {
'aliceblue':[240,248,255],
'antiquewhite':[250,235,215],
'aqua':[0,255,255],
'aquamarine':[127,255,212],
'azure':[240,255,255],
'beige':[245,245,220],
'bisque':[255,228,196],
'black':[0,0,0],
'blanchedalmond':[255,235,205],
'blue':[0,0,255],
'blueviolet':[138,43,226],
'brown':[165,42,42],
'burlywood':[222,184,135],
'cadetblue':[95,158,160],
'chartreuse':[127,255,0],
'chocolate':[210,105,30],
'coral':[255,127,80],
'cornflowerblue':[100,149,237],
'cornsilk':[255,248,220],
'crimson':[220,20,60],
'cyan':[0,255,255],
'darkblue':[0,0,139],
'darkcyan':[0,139,139],
'darkgoldenrod':[184,134,11],
'darkgray':[169,169,169],
'darkgrey':[169,169,169],
'darkgreen':[0,100,0],
'darkkhaki':[189,183,107],
'darkmagenta':[139,0,139],
'darkolivegreen':[85,107,47],
'darkorange':[255,140,0],
'darkorchid':[153,50,204],
'darkred':[139,0,0],
'darksalmon':[233,150,122],
'darkseagreen':[143,188,143],
'darkslateblue':[72,61,139],
'darkslategray':[47,79,79],
'darkslategrey':[47,79,79],
'darkturquoise':[0,206,209],
'darkviolet':[148,0,211],
'deeppink':[255,20,147],
'deepskyblue':[0,191,255],
'dimgray':[105,105,105],
'dimgrey':[105,105,105],
'dodgerblue':[30,144,255],
'firebrick':[178,34,34],
'floralwhite':[255,250,240],
'forestgreen':[34,139,34],
'fuchsia':[255,0,255],
'gainsboro':[220,220,220],
'ghostwhite':[248,248,255],
'gold':[255,215,0],
'goldenrod':[218,165,32],
'gray':[128,128,128],
'grey':[128,128,128],
'green':[0,128,0],
'greenyellow':[173,255,47],
'honeydew':[240,255,240],
'hotpink':[255,105,180],
'indianred':[205,92,92],
'indigo':[75,0,130],
'ivory':[255,255,240],
'khaki':[240,230,140],
'lavender':[230,230,250],
'lavenderblush':[255,240,245],
'lawngreen':[124,252,0],
'lemonchiffon':[255,250,205],
'lightblue':[173,216,230],
'lightcoral':[240,128,128],
'lightcyan':[224,255,255],
'lightgoldenrodyellow':[250,250,210],
'lightgray':[211,211,211],
'lightgrey':[211,211,211],
'lightgreen':[144,238,144],
'lightpink':[255,182,193],
'lightsalmon':[255,160,122],
'lightseagreen':[32,178,170],
'lightskyblue':[135,206,250],
'lightslategray':[119,136,153],
'lightslategrey':[119,136,153],
'lightsteelblue':[176,196,222],
'lightyellow':[255,255,224],
'lime':[0,255,0],
'limegreen':[50,205,50],
'linen':[250,240,230],
'magenta':[255,0,255],
'maroon':[128,0,0],
'mediumaquamarine':[102,205,170],
'mediumblue':[0,0,205],
'mediumorchid':[186,85,211],
'mediumpurple':[147,112,216],
'mediumseagreen':[60,179,113],
'mediumslateblue':[123,104,238],
'mediumspringgreen':[0,250,154],
'mediumturquoise':[72,209,204],
'mediumvioletred':[199,21,133],
'midnightblue':[25,25,112],
'mintcream':[245,255,250],
'mistyrose':[255,228,225],
'moccasin':[255,228,181],
'navajowhite':[255,222,173],
'navy':[0,0,128],
'oldlace':[253,245,230],
'olive':[128,128,0],
'olivedrab':[107,142,35],
'orange':[255,165,0],
'orangered':[255,69,0],
'orchid':[218,112,214],
'palegoldenrod':[238,232,170],
'palegreen':[152,251,152],
'paleturquoise':[175,238,238],
'palevioletred':[216,112,147],
'papayawhip':[255,239,213],
'peachpuff':[255,218,185],
'peru':[205,133,63],
'pink':[255,192,203],
'plum':[221,160,221],
'powderblue':[176,224,230],
'purple':[128,0,128],
'red':[255,0,0],
'rosybrown':[188,143,143],
'royalblue':[65,105,225],
'saddlebrown':[139,69,19],
'salmon':[250,128,114],
'sandybrown':[244,164,96],
'seagreen':[46,139,87],
'seashell':[255,245,238],
'sienna':[160,82,45],
'silver':[192,192,192],
'skyblue':[135,206,235],
'slateblue':[106,90,205],
'slategray':[112,128,144],
'slategrey':[112,128,144],
'snow':[255,250,250],
'springgreen':[0,255,127],
'steelblue':[70,130,180],
'tan':[210,180,140],
'teal':[0,128,128],
'thistle':[216,191,216],
'tomato':[255,99,71],
'turquoise':[64,224,208],
'violet':[238,130,238],
'wheat':[245,222,179],
'white':[255,255,255],
'whitesmoke':[245,245,245],
'yellow':[255,255,0],
'yellowgreen':[154,205,50],
};
// color parsing function originally from
// http://plugins.jquery.com/files/jquery.color.js.txt
// (with slight modifications)
// Parse strings looking for color tuples [255,255,255]
var rgbNumRE = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
var rgbPercRE = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/;
var rgbHash6RE = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/;
var rgbHash3RE = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/;
var strToRgb = function(color) {
var result;
// Check if we're already dealing with an array of colors
// if ( color && color.constructor == Array && color.length == 3 )
// return color;
// Look for rgb(num,num,num)
if (result = rgbNumRE.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = rgbPercRE.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = rgbHash6RE.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = rgbHash3RE.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Otherwise, we're most likely dealing with a named color
return colors[$.trim(color).toLowerCase()];
};
var rgbToStr = function(rgb) {
// TODO: there has to be a better way, even in JS
var r = Math.floor(rgb[0]).toString(16);
var g = Math.floor(rgb[1]).toString(16);
var b = Math.floor(rgb[2]).toString(16);
// pad
r = r.length < 2 ? '0' + r : r;
g = g.length < 2 ? '0' + g : g;
b = b.length < 2 ? '0' + b : b;
return ('#'+r+g+b);
};
// Functions rgbToHsl and hslToRgb originally from
// http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
// implementation of functions in Wikipedia
// (with slight modifications)
// RGB to HSL color conversion
var rgbToHsl = function(rgb) {
var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h, s, l];
};
var hue2rgb = function(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
};
var hslToRgb = function(hsl) {
var h = hsl[0], s = hsl[1], l = hsl[2];
var r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [r * 255, g * 255, b * 255];
};
var adjustLightnessCache = {};
// given color string and -1<=adjust<=1, returns color string
// where lightness (in the HSL sense) is adjusted by the given
// amount, the larger the lighter: -1 gives black, 1 white, and 0
// the given color.
var adjustColorLightness = function(colorstr, adjust) {
if (!(colorstr in adjustLightnessCache)) {
adjustLightnessCache[colorstr] = {}
}
if (!(adjust in adjustLightnessCache[colorstr])) {
var rgb = strToRgb(colorstr);
if (rgb === undefined) {
// failed color string conversion; just return the input
adjustLightnessCache[colorstr][adjust] = colorstr;
} else {
var hsl = rgbToHsl(rgb);
if (adjust > 0.0) {
hsl[2] = 1.0 - ((1.0-hsl[2])*(1.0-adjust));
} else {
hsl[2] = (1.0+adjust)*hsl[2];
}
var lightRgb = hslToRgb(hsl);
adjustLightnessCache[colorstr][adjust] = rgbToStr(lightRgb);
}
}
return adjustLightnessCache[colorstr][adjust];
};
// Partially stolen from: http://documentcloud.github.com/underscore/
// MIT-License
// TODO: Mention in LICENSE.md
var isEqual = function(a, b) {
// Check object identity.
if (a === b) return true;
// Different types?
var atype = typeof(a), btype = typeof(b);
if (atype != btype) return false;
// Basic equality test (watch out for coercions).
if (a == b) return true;
// One is falsy and the other truthy.
if ((!a && b) || (a && !b)) return false;
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') return false;
// Check for different array lengths before comparing contents.
if (a.length && (a.length !== b.length)) return false;
// Nothing else worked, deep compare the contents.
for (var key in b) if (!(key in a)) return false;
// Recursive comparison of contents.
for (var key in a) if (!(key in b) || !isEqual(a[key], b[key])) return false;
return true;
};
var keyValRE = /^([^=]+)=(.*)$/; // key=value
var isDigitsRE = /^[0-9]+$/;
var deparam = function(str) {
var args = str.split('&');
var len = args.length;
if (!len) return null;
var result = {};
for (var i = 0; i < len; i++) {
var parts = args[i].match(keyValRE);
if (!parts || parts.length != 3) break;
var val = [];
var arr = parts[2].split(',');
var sublen = arr.length;
for (var j = 0; j < sublen; j++) {
var innermost = [];
// map empty arguments ("" in URL) to empty arrays
// (innermost remains [])
if (arr[j].length) {
var arrsplit = arr[j].split('~');
var subsublen = arrsplit.length;
for (var k = 0; k < subsublen; k++) {
if(arrsplit[k].match(isDigitsRE)) {
// convert digits into ints ...
innermost.push(parseInt(arrsplit[k], 10));
}
else {
// ... anything else remains a string.
innermost.push(arrsplit[k]);
}
}
}
val.push(innermost);
}
result[parts[1]] = val;
}
return result;
};
var paramArray = function(val) {
val = val || [];
var len = val.length;
var arr = [];
for (var i = 0; i < len; i++) {
if ($.isArray(val[i])) {
arr.push(val[i].join('~'));
} else {
// non-array argument; this is an error from the caller
console.error('param: Error: received non-array-in-array argument [', i, ']', ':', val[i], '(fix caller)');
}
}
return arr;
};
var param = function(args) {
if (!args) return '';
var vals = [];
for (var key in args) {
if (args.hasOwnProperty(key)) {
var val = args[key];
if (val == undefined) {
console.error('Error: received argument', key, 'with value', val);
continue;
}
// values normally expected to be arrays, but some callers screw
// up, so check
if ($.isArray(val)) {
var arr = paramArray(val);
vals.push(key + '=' + arr.join(','));
} else {
// non-array argument; this is an error from the caller
console.error('param: Error: received non-array argument', key, ':', val, '(fix caller)');
}
}
}
return vals.join('&');
};
var profiles = {};
var profileStarts = {};
var profileOn = false;
var profileEnable = function(on) {
if (on === undefined) on = true;
profileOn = on;
}; // profileEnable
var profileClear = function() {
if (!profileOn) return;
profiles = {};
profileStarts = {};
}; // profileClear
var profileStart = function(label) {
if (!profileOn) return;
profileStarts[label] = new Date();
}; // profileStart
var profileEnd = function(label) {
if (!profileOn) return;
var profileElapsed = new Date() - profileStarts[label]
if (!profiles[label]) profiles[label] = 0;
profiles[label] += profileElapsed;
}; // profileEnd
var profileReport = function() {
if (!profileOn) return;
if (window.console) {
$.each(profiles, function(label, time) {
console.log("profile " + label, time);
});
console.log("-------");
}
}; // profileReport
var fontsLoaded = false;
var fontNotifyList = false;
var proceedWithFonts = function() {
if (fontsLoaded) return;
fontsLoaded = true;
$.each(fontNotifyList, function(dispatcherNo, dispatcher) {
dispatcher.post('triggerRender');
});
fontNotifyList = null;
};
var loadFonts = function(webFontURLs, dispatcher) {
if (fontsLoaded) {
dispatcher.post('triggerRender');
return;
}
if (fontNotifyList) {
fontNotifyList.push(dispatcher);
return;
}
fontNotifyList = [dispatcher];
var families = [];
$.each(webFontURLs, function(urlNo, url) {
if (/Astloch/i.test(url)) families.push('Astloch');
else if (/PT.*Sans.*Caption/i.test(url)) families.push('PT Sans Caption');
else if (/Liberation.*Sans/i.test(url)) families.push('Liberation Sans');
});
webFontURLs = {
families: families,
urls: webFontURLs
}
var webFontConfig = {
custom: webFontURLs,
active: proceedWithFonts,
inactive: proceedWithFonts,
fontactive: function(fontFamily, fontDescription) {
// Note: Enable for font debugging
// console.log("font active: ", fontFamily, fontDescription);
},
fontloading: function(fontFamily, fontDescription) {
// Note: Enable for font debugging
// console.log("font loading:", fontFamily, fontDescription);
},
};
WebFont.load(webFontConfig);
setTimeout(function() {
if (!fontsLoaded) {
console.error('Timeout in loading fonts');
proceedWithFonts();
}
}, fontLoadTimeout);
};
var areFontsLoaded = function() {
return fontsLoaded;
};
return {
profileEnable: profileEnable,
profileClear: profileClear,
profileStart: profileStart,
profileEnd: profileEnd,
profileReport: profileReport,
formatTimeAgo: formatTimeAgo,
realBBox: realBBox,
getSpanLabels: getSpanLabels,
spanDisplayForm: spanDisplayForm,
getArcLabels: getArcLabels,
arcDisplayForm: arcDisplayForm,
escapeQuotes: escapeQuotes,
escapeHTML: escapeHTML,
escapeHTMLandQuotes: escapeHTMLandQuotes,
escapeHTMLwithNewlines: escapeHTMLwithNewlines,
cmp: cmp,
rgbToHsl: rgbToHsl,
hslToRgb: hslToRgb,
adjustColorLightness: adjustColorLightness,
objectToUrlStr: objectToUrlStr,
isEqual: isEqual,
paramArray: paramArray,
param: param,
deparam: deparam,
isMac: isMac,
loadFonts: loadFonts,
areFontsLoaded: areFontsLoaded,
};
})(window);
module.exports = Util; | Edilmo/brat-widget | js/src/util.js | JavaScript | mit | 21,591 |