code
stringlengths
2
1.05M
import React from 'react'; import AutoField from 'uniforms-semantic/AutoField'; import SubmitField from 'uniforms-semantic/SubmitField'; import ErrorsField from 'uniforms-semantic/ErrorsField'; import AutoForm from 'uniforms-semantic/AutoForm'; import FormMaskedInput from '../../lib/FormMaskedInput'; const FormBank = formProps => ( <AutoForm showInlineError {...formProps} > <AutoField name="name" /> <AutoField name="internationalAccountNumber" component={FormMaskedInput} mask={'CH99 9999 9999 9999 9999 9'} maskChar={'_'} alwaysShowMask /> <ErrorsField /> <SubmitField value="Speichern" className="primary" /> </AutoForm> ); export default FormBank;
class system_runtime_remoting_contexts_synchronizationattribute { constructor() { // bool IsReEntrant {get;} this.IsReEntrant = undefined; // bool Locked {get;set;} this.Locked = undefined; // string Name {get;} this.Name = undefined; // System.Object TypeId {get;} this.TypeId = undefined; } // bool Equals(System.Object o) Equals() { } // void Freeze(System.Runtime.Remoting.Contexts.Context newContext), void IContex... Freeze() { } // System.Runtime.Remoting.Messaging.IMessageSink GetClientContextSink(System.Run... GetClientContextSink() { } // int GetHashCode() GetHashCode() { } // void _Attribute.GetIDsOfNames([ref] guid riid, System.IntPtr rgszNames, uint32... GetIDsOfNames() { } // void GetPropertiesForNewContext(System.Runtime.Remoting.Activation.IConstructi... GetPropertiesForNewContext() { } // System.Runtime.Remoting.Messaging.IMessageSink GetServerContextSink(System.Run... GetServerContextSink() { } // type GetType() GetType() { } // void _Attribute.GetTypeInfo(uint32 iTInfo, uint32 lcid, System.IntPtr ppTInfo) GetTypeInfo() { } // void _Attribute.GetTypeInfoCount([ref] uint32 pcTInfo) GetTypeInfoCount() { } // void _Attribute.Invoke(uint32 dispIdMember, [ref] guid riid, uint32 lcid, int1... Invoke() { } // bool IsContextOK(System.Runtime.Remoting.Contexts.Context ctx, System.Runtime.... IsContextOK() { } // bool IsDefaultAttribute() IsDefaultAttribute() { } // bool IsNewContextOK(System.Runtime.Remoting.Contexts.Context newCtx), bool ICo... IsNewContextOK() { } // bool Match(System.Object obj) Match() { } // string ToString() ToString() { } } module.exports = system_runtime_remoting_contexts_synchronizationattribute;
/* * Kendo UI v2014.2.716 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["de-CH"] = { name: "de-CH", numberFormat: { pattern: ["-n"], decimals: 2, ",": "'", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": "'", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": "'", ".": ".", groupSize: [3], symbol: "Fr." } }, calendars: { standard: { days: { names: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"], namesAbbr: ["So","Mo","Di","Mi","Do","Fr","Sa"], namesShort: ["So","Mo","Di","Mi","Do","Fr","Sa"] }, months: { names: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember",""], namesAbbr: ["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez",""] }, AM: [""], PM: [""], patterns: { d: "dd.MM.yyyy", D: "dddd, d. MMMM yyyy", F: "dddd, d. MMMM yyyy HH:mm:ss", g: "dd.MM.yyyy HH:mm", G: "dd.MM.yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
var {Helper, Type} = require("@kaoscript/runtime"); module.exports = function() { function foobar() { if(arguments.length === 1 && Type.isString(arguments[0])) { let __ks_i = -1; let x = arguments[++__ks_i]; if(x === void 0 || x === null) { throw new TypeError("'x' is not nullable"); } else if(!Type.isString(x)) { throw new TypeError("'x' is not of type 'String'"); } return x; } else if(arguments.length === 1) { let __ks_i = -1; let x = arguments[++__ks_i]; if(x === void 0) { x = null; } } else { throw new SyntaxError("Wrong number of arguments"); } }; console.log(foobar("foo")); console.log(Helper.toString(foobar(null))); };
var url = require('url'); /** * * @param options * mustLogin 必须登陆的路径 * mustNotLogin 必须没登陆的路径 * @returns {Function} */ module.exports = function(options){ if(!options) options = {}; return function(req,res,next){ var pathname = url.parse(req.url).pathname; if(pathname != "/"){ if(options.mustLogin && new RegExp(pathname,'i').test(options.mustLogin)){ if(!req.session.user){ req.flash('error','你尚未登陆,请登陆'); return res.redirect('/users/login'); } } if(options.mustNotLogin && new RegExp(pathname,'i').test(options.mustNotLogin)){ if(req.session.user){ req.flash('error','你已经登陆,不能执行此操作'); return res.redirect('back'); } } } next(); } }
var clipper = require('../'); Promise.promisifyAll(clipper); function wrap(args) { return function() { clipper.orientation.apply(null, args); }; } describe('clipper.orientation()', function() { it('should throw an error if no arguments are provided', function() { expect(wrap([])).to.throw(TypeError, 'Wrong type for argument 1: expected array'); }); it('should throw an error if the first argument is the wrong type', function() { var args1 = [true]; var args2 = [0]; var args3 = ['str']; var args4 = [null]; var args5 = [{ prop: 'one' }]; expect(wrap(args1)).to.throw(TypeError, 'Wrong type for argument 1: expected array'); expect(wrap(args2)).to.throw(TypeError, 'Wrong type for argument 1: expected array'); expect(wrap(args3)).to.throw(TypeError, 'Wrong type for argument 1: expected array'); expect(wrap(args4)).to.throw(TypeError, 'Wrong type for argument 1: expected array'); expect(wrap(args5)).to.throw(TypeError, 'Wrong type for argument 1: expected array'); }); it('should return true if the polygon is an outer polygon', function() { var path = [0, 10, 10, 0, 20, 10, 10, 20]; expect(clipper.orientation(path)).to.be.true; }); it('should return false if the polygon is a hole polygon', function() { var path = [15, 10, 5, 10, 10, 20]; expect(clipper.orientation(path)).to.be.false; }); it('should accept a factor as an argument', function() { var path = [0, 0.10, 0.10, 0, 0.20, 0.10, 0.10, 0.20]; expect(clipper.orientation(path, 100)).to.be.true; }); it('should correctly get the orientation boolean in a callback', function(done) { var path = [0, 10, 10, 0, 20, 10, 10, 20]; clipper.orientation(path, function(err, value) { expect(value).to.be.true; done(); }); }); it('should correctly get the orientation boolean using promises', function() { var path = [0, 10, 10, 0, 20, 10, 10, 20]; return clipper.orientationAsync(path).then(function(value) { expect(value).to.be.true; }); }); });
var MySql = require('../../../../src/dialect/my-sql'); describe("MySql Dialect", function() { beforeEach(function() { this.dialect = new MySql(); }); describe(".field()", function() { it("formats a column with `varchar` by default", function() { var field = this.dialect.field({ name: 'title' }); expect(field).toEqual({ name: 'title', use: 'varchar', length: 255, type: null, precision: null, serial: false, null: null, default: null }); }); it("ignores invalid types when the `'use'` options is set", function() { field = this.dialect.field({ type: 'invalid', name: 'title', use: 'text' }); expect(field).toEqual({ type: 'invalid', name: 'title', use: 'text', length: null, precision: null, serial: false, null: null, default: null }); }); }); describe(".conditions()", function() { it("manages set operators", function() { var select1 = this.dialect.statement('select').from('table1'); var select2 = this.dialect.statement('select').from('table2'); var part = this.dialect.conditions({ ':union': [ select1, select2 ] }); expect(part).toBe('SELECT * FROM `table1` UNION SELECT * FROM `table2`'); }); }); describe(".meta()", function() { context("with table", function() { it("generates charset meta", function() { var result = this.dialect.meta('table', { charset: 'utf8' }); expect(result).toBe('DEFAULT CHARSET utf8'); }); it("generates collate meta", function() { var result = this.dialect.meta('table', { collate: 'utf8_unicode_ci' }); expect(result).toBe('COLLATE utf8_unicode_ci'); }); it("generates ENGINE meta", function() { var result = this.dialect.meta('table', { engine: 'InnoDB' }); expect(result).toBe('ENGINE InnoDB'); }); it("generates TABLESPACE meta", function() { var result = this.dialect.meta('table', { tablespace: 'myspace' }); expect(result).toBe('TABLESPACE myspace'); }); }); context("with column", function() { it("generates charset meta", function() { var result = this.dialect.meta('column', { charset: 'utf8' }); expect(result).toBe('CHARACTER SET utf8'); }); it("generates collate meta", function() { var result = this.dialect.meta('column', { collate: 'utf8_unicode_ci' }); expect(result).toBe('COLLATE utf8_unicode_ci'); }); it("generates comment meta", function() { var result = this.dialect.meta('column', { comment: 'comment value' }); expect(result).toBe('COMMENT \'comment value\''); }); }); }); describe(".constraint()", function() { context("with `'primary'`", function() { it("generates a PRIMARY KEY constraint", function() { var data = { column: ['id'] }; var result = this.dialect.constraint('primary', data); expect(result).toBe('PRIMARY KEY (`id`)'); }); it("generates a multiple PRIMARY KEY constraint", function() { var data = { column: ['id', 'name'] }; var result = this.dialect.constraint('primary', data); expect(result).toBe('PRIMARY KEY (`id`, `name`)'); }); }); context("with `'unique'`", function() { it("generates an UNIQUE KEY constraint", function() { var data = { column: ['id'] }; var result = this.dialect.constraint('unique', data); expect(result).toBe('UNIQUE `id` (`id`)'); }); it("generates a multiple UNIQUE KEY constraint", function() { var data = { column: ['id', 'name'] }; var result = this.dialect.constraint('unique', data); expect(result).toBe('UNIQUE `id_name` (`id`, `name`)'); }); it("generates a multiple UNIQUE KEY constraint", function() { var data = { column: ['id', 'name'], index: true }; var result = this.dialect.constraint('unique', data); expect(result).toBe('UNIQUE INDEX `id_name` (`id`, `name`)'); }); it("generates an UNIQUE KEY constraint when both index & key are required", function() { var data = { column: ['id', 'name'], key: true }; var result = this.dialect.constraint('unique', data); expect(result).toBe('UNIQUE KEY `id_name` (`id`, `name`)'); }); }); context("with `'check'`", function() { it("generates a CHECK constraint", function() { var data = { expr: [ { population: { '>': 20 } }, { name: 'Los Angeles' } ] }; var result = this.dialect.constraint('check', data); expect(result).toBe('CHECK (`population` > 20 AND `name` = \'Los Angeles\')'); }); }); context("with `'foreign_key'`", function() { it("generates a FOREIGN KEY constraint", function() { var data = { foreignKey: 'table_id', to: 'table', primaryKey: 'id', on: 'DELETE CASCADE' }; var result = this.dialect.constraint('foreign key', data); expect(result).toBe('FOREIGN KEY (`table_id`) REFERENCES `table` (`id`) ON DELETE CASCADE'); }); }); }); describe(".column()", function() { context("with a integer column", function() { it("generates an interger column", function() { var data = { name: 'fieldname', type: 'integer' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` int'); }); it("generates an interger column with the correct length", function() { var data = { name: 'fieldname', type: 'integer', length: 11 }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` int(11)'); }); }); context("with a string column", function() { it("generates a varchar column", function() { var data = { name: 'fieldname', type: 'string', length: 32, null: true, comment: 'test' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` varchar(32) NULL COMMENT \'test\''); }); it("generates a varchar column with a default value", function() { var data = { name: 'fieldname', type: 'string', length: 32, 'default': 'default value' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` varchar(32) DEFAULT \'default value\''); data['null'] = false; result = this.dialect.column(data); expect(result).toBe('`fieldname` varchar(32) NOT NULL DEFAULT \'default value\''); }); it("generates a varchar column with charset & collate", function() { var data = { name: 'fieldname', type: 'string', length: 32, null: false, charset: 'utf8', collate: 'utf8_unicode_ci' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL'); }); }); context("with a float column", function() { it("generates a float column", function() { var data = { name: 'fieldname', type: 'float', length: 10 }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` float(10)'); }); it("generates a decimal column", function() { var data = { name: 'fieldname', type: 'float', length: 10, precision: 2 }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` decimal(10,2)'); }); }); context("with a default value", function() { it("generates a default value", function() { var data = { name: 'fieldname', type: 'string', default: 'value' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` varchar(255) DEFAULT \'value\''); }); it("overrides default value for numeric type when equal to an empty string", function() { var data = { name: 'fieldname', type: 'float', length: 10, default: '' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` float(10) NULL'); }); it("ignores default for BLOB/TEXT", function() { var data = { name: 'fieldname', use: 'longtext', default: 'value' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` longtext'); var data = { name: 'fieldname', use: 'mediumtext', default: 'value' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` mediumtext'); var data = { name: 'fieldname', use: 'text', default: 'value' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` text'); data = { name: 'fieldname', use: 'blob', default: 'value' }; result = this.dialect.column(data); expect(result).toBe('`fieldname` blob'); data = { name: 'fieldname', use: 'geometry', default: 'value' }; result = this.dialect.column(data); expect(result).toBe('`fieldname` geometry'); data = { name: 'fieldname', use: 'json', default: 'value' }; result = this.dialect.column(data); expect(result).toBe('`fieldname` json'); }); }); context("with a datetime column", function() { it("generates a datetime column", function() { var data = { name: 'modified', type: 'datetime' }; var result = this.dialect.column(data); expect(result).toBe('`modified` datetime'); }); it("generates a datetime column with a default value", function() { var data = { name: 'created', type: 'datetime', 'default': { ':plain': 'CURRENT_TIMESTAMP' } }; var result = this.dialect.column(data); expect(result).toBe('`created` datetime DEFAULT CURRENT_TIMESTAMP'); }); }); context("with a date column", function() { it("generates a date column", function() { var data = { name: 'created', type: 'date' }; var result = this.dialect.column(data); expect(result).toBe('`created` date'); }); }); context("with a time column", function() { it("generates a time column", function() { var data = { name: 'created', type: 'time' }; var result = this.dialect.column(data); expect(result).toBe('`created` time'); }); }); context("with a boolean column", function() { it("generates a boolean column", function() { var data = { name: 'active', type: 'boolean' }; var result = this.dialect.column(data); expect(result).toBe('`active` boolean'); }); it("generates a boolean column where default is `true`", function() { var data = { name: 'active', type: 'boolean', 'default': true }; var result = this.dialect.column(data); expect(result).toBe('`active` boolean DEFAULT TRUE'); }); it("generates a boolean column where default is `false`", function() { var data = { name: 'active', type: 'boolean', 'default': false }; var result = this.dialect.column(data); expect(result).toBe('`active` boolean DEFAULT FALSE'); }); }); context("with a binary column", function() { it("generates a binary column", function() { var data = { name: 'raw', type: 'binary' }; var result = this.dialect.column(data); expect(result).toBe('`raw` blob'); }); }); context("with a bad type column", function() { it("generates throws an execption", function() { var closure = function() { var data = { name: 'fieldname', type: 'invalid' }; this.dialect.column(data); }.bind(this); expect(closure).toThrow(new Error("Column type `'invalid'` does not exist.")); }); }); context("with a use option", function() { it("overrides the default type", function() { var data = { name: 'fieldname', type: 'string', use: 'decimal', length: 11, precision: 2 }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` decimal(11,2)'); }); }); context("with a default column value", function() { it("sets up the default value", function() { var data = { name: 'fieldname', type: 'integer', 'default': 1 }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` int DEFAULT 1'); }); context("with a casting handler defined", function() { beforeEach(function() { var dialect = this.dialect; dialect.caster(function(value, states) { if (!states || !states.field || !states.field.type) { return value; } switch (states.field.type) { case 'integer': return Number.parseInt(value); break; default: return String(dialect.quote(value)); break; } }); }); it("casts the default value to an integer", function() { var data = { name: 'fieldname', type: 'integer', 'default': '1' }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` int DEFAULT 1'); }); it("casts the default value to an string", function() { var data = { name: 'fieldname', type: 'string', length: 64, 'default': 1 }; var result = this.dialect.column(data); expect(result).toBe('`fieldname` varchar(64) DEFAULT \'1\''); }); }); }); }); });
console.log('Hello!'); var thermostat = new Thermostat(); $(document).ready(function() { $('#temperature_display').text(thermostat.temperature); $('#temperature_display').css('color', thermostat.colour); $('#increase_button').on('click', function() { thermostat.increaseTemp(); $('#temperature_display').text(thermostat.temperature); $('#temperature_display').css('color', thermostat.colour); }); $('#decrease_button').on('click', function() { thermostat.decreaseTemp(); $('#temperature_display').text(thermostat.temperature); $('#temperature_display').css('color', thermostat.colour); }); $('#reset_button').on('click', function() { thermostat.reset(); $('#temperature_display').text(thermostat.temperature); $('#temperature_display').css('color', thermostat.colour); }); $('#power_saving_mode').on('change', function() { if (this.checked) { thermostat.powerSavingOn(); } else { thermostat.powerSavingOff(); } $('#temperature_display').text(thermostat.temperature); $('#temperature_display').css('color', thermostat.colour); }); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-5-b-133 description: > Object.defineProperties - 'descObj' is the JSON object which implements its own [[Get]] method to get 'value' property (8.10.5 step 5.a) includes: [runTestCase.js] ---*/ function testcase() { var obj = {}; try { JSON.value = "JSON"; Object.defineProperties(obj, { property: JSON }); return obj.property === "JSON"; } finally { delete JSON.value; } } runTestCase(testcase);
System.config({ "baseURL": "/", "transpiler": "babel", "paths": { "*": "*.js", "github:*": "jspm_packages/github/*.js", "npm:*": "jspm_packages/npm/*.js" } }); System.config({ "map": { "FezVrasta/bootstrap-material-design": "github:FezVrasta/bootstrap-material-design@0.2.2", "angular": "github:angular/bower-angular@1.3.14", "angular-resource": "npm:angular-resource@1.3.14", "angular-ui-router": "github:angular-ui/ui-router@0.2.13", "bootstrap": "github:twbs/bootstrap@3.3.2", "css": "github:systemjs/plugin-css@0.1.6", "image": "github:systemjs/plugin-image@0.1.0", "jquery": "github:components/jquery@2.1.3", "twbs/bootstrap": "github:twbs/bootstrap@3.3.2", "github:angular-ui/ui-router@0.2.13": { "angular": "github:angular/bower-angular@1.3.14" }, "github:jspm/nodelibs-assert@0.1.0": { "assert": "npm:assert@1.3.0" }, "github:jspm/nodelibs-buffer@0.1.0": { "buffer": "npm:buffer@3.0.3" }, "github:jspm/nodelibs-events@0.1.0": { "events-browserify": "npm:events-browserify@0.0.1" }, "github:jspm/nodelibs-http@1.7.0": { "Base64": "npm:Base64@0.2.1", "events": "github:jspm/nodelibs-events@0.1.0", "inherits": "npm:inherits@2.0.1", "stream": "github:jspm/nodelibs-stream@0.1.0", "url": "github:jspm/nodelibs-url@0.1.0", "util": "github:jspm/nodelibs-util@0.1.0" }, "github:jspm/nodelibs-https@0.1.0": { "https-browserify": "npm:https-browserify@0.0.0" }, "github:jspm/nodelibs-os@0.1.0": { "os-browserify": "npm:os-browserify@0.1.2" }, "github:jspm/nodelibs-path@0.1.0": { "path-browserify": "npm:path-browserify@0.0.0" }, "github:jspm/nodelibs-process@0.1.1": { "process": "npm:process@0.10.0" }, "github:jspm/nodelibs-querystring@0.1.0": { "querystring": "npm:querystring@0.2.0" }, "github:jspm/nodelibs-stream@0.1.0": { "stream-browserify": "npm:stream-browserify@1.0.0" }, "github:jspm/nodelibs-url@0.1.0": { "url": "npm:url@0.10.3" }, "github:jspm/nodelibs-util@0.1.0": { "util": "npm:util@0.10.3" }, "github:systemjs/plugin-css@0.1.6": { "clean-css": "npm:clean-css@3.0.10", "fs": "github:jspm/nodelibs-fs@0.1.1", "path": "github:jspm/nodelibs-path@0.1.0" }, "github:twbs/bootstrap@3.3.2": { "css": "github:systemjs/plugin-css@0.1.6", "jquery": "github:components/jquery@2.1.3" }, "npm:amdefine@0.1.0": { "fs": "github:jspm/nodelibs-fs@0.1.1", "module": "github:jspm/nodelibs-module@0.1.0", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.1" }, "npm:assert@1.3.0": { "util": "npm:util@0.10.3" }, "npm:buffer@3.0.3": { "base64-js": "npm:base64-js@0.0.8", "ieee754": "npm:ieee754@1.1.4", "is-array": "npm:is-array@1.0.1" }, "npm:clean-css@3.0.10": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "commander": "npm:commander@2.5.1", "fs": "github:jspm/nodelibs-fs@0.1.1", "http": "github:jspm/nodelibs-http@1.7.0", "https": "github:jspm/nodelibs-https@0.1.0", "os": "github:jspm/nodelibs-os@0.1.0", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.1", "source-map": "npm:source-map@0.1.43", "url": "github:jspm/nodelibs-url@0.1.0", "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:commander@2.5.1": { "child_process": "github:jspm/nodelibs-child_process@0.1.0", "events": "github:jspm/nodelibs-events@0.1.0", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.1" }, "npm:core-util-is@1.0.1": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:events-browserify@0.0.1": { "process": "github:jspm/nodelibs-process@0.1.1" }, "npm:https-browserify@0.0.0": { "http": "github:jspm/nodelibs-http@1.7.0" }, "npm:inherits@2.0.1": { "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:os-browserify@0.1.2": { "os": "github:jspm/nodelibs-os@0.1.0" }, "npm:path-browserify@0.0.0": { "process": "github:jspm/nodelibs-process@0.1.1" }, "npm:punycode@1.3.2": { "process": "github:jspm/nodelibs-process@0.1.1" }, "npm:readable-stream@1.1.13": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "core-util-is": "npm:core-util-is@1.0.1", "events": "github:jspm/nodelibs-events@0.1.0", "inherits": "npm:inherits@2.0.1", "isarray": "npm:isarray@0.0.1", "process": "github:jspm/nodelibs-process@0.1.1", "stream": "npm:stream-browserify@1.0.0", "string_decoder": "npm:string_decoder@0.10.31", "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:source-map@0.1.43": { "amdefine": "npm:amdefine@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.1", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.1" }, "npm:stream-browserify@1.0.0": { "events": "github:jspm/nodelibs-events@0.1.0", "inherits": "npm:inherits@2.0.1", "readable-stream": "npm:readable-stream@1.1.13" }, "npm:string_decoder@0.10.31": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:url@0.10.2": { "assert": "github:jspm/nodelibs-assert@0.1.0", "punycode": "npm:punycode@1.3.2", "querystring": "github:jspm/nodelibs-querystring@0.1.0", "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:url@0.10.3": { "assert": "github:jspm/nodelibs-assert@0.1.0", "punycode": "npm:punycode@1.3.2", "querystring": "npm:querystring@0.2.0", "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:util@0.10.3": { "inherits": "npm:inherits@2.0.1", "process": "github:jspm/nodelibs-process@0.1.1" } } });
/** @fileoverview File watcher for Grunt.js Copyright (c) 2013 Daniel Steigerwald */ module.exports = function(grunt) { var fs = require('fs'); var path = require('path'); var tinylr = require('tiny-lr'); var semver = require('semver'); var RESTART_WATCHERS_DEBOUNCE = 10; var WAIT_FOR_UNLOCK_INTERVAL = 10; var WAIT_FOR_UNLOCK_TRY_LIMIT = 50; var changedFilesForLiveReload = []; var done; var esteWatchTaskIsRunning = false; var filesChangedWithinWatchTask = []; var firstRun = true; var lrServer; var options; var watchers = []; var watchTaskStart; var unlockTimer = null; if(semver.lt(process.versions.node, '0.9.2')) { grunt.fail.warn("Use node 0.9.2+, due to buggy fs.watch"); } grunt.registerTask('esteWatch', 'Este files watcher.', function() { options = this.options({ dirs: [ 'bower_components/closure-library/**/', 'bower_components/este-library/**/', '!bower_components/este-library/node_modules/**/', 'client/**/{js,css}/**/' ], ignoredFiles: [], livereload: { enabled: true, port: 35729, extensions: ['js', 'css'] }, // friendly beep on error beep: false }); done = this.async(); esteWatchTaskIsRunning = false; watchTaskStart = Date.now(); grunt.log.ok('Waiting...'); if (firstRun) { firstRun = false; restartWatchers(); if (options.livereload.enabled) runLiveReloadServer(); keepThisTaskRunForeverViaHideousHack(); } dispatchWaitingChanges(); }); grunt.registerTask('esteWatchLiveReload', function() { if (!options.livereload.enabled) return; if (changedFilesForLiveReload.length) { changedFilesForLiveReload = grunt.util._.uniq(changedFilesForLiveReload); notifyLiveReloadServer(changedFilesForLiveReload); changedFilesForLiveReload = []; } }); // TODO: handle hypothetic situation, when task create dir var restartWatchers = function() { var start = Date.now(); closeWatchers(); var allDirs = grunt.file.expand(options.dirs); grunt.verbose.writeln('Watched dirs: ' + allDirs); watchDirs(allDirs); var duration = Date.now() - start; grunt.log.writeln(( allDirs.length + ' dirs watched within ' + duration + ' ms.').cyan); }; var notifyLiveReloadServer = function(filepaths) { grunt.verbose.ok('notifyLiveReloadServer: ' + filepaths); filepaths = filepaths.filter(function(filepath) { var ext = path.extname(filepath).slice(1); return options.livereload.extensions.indexOf(ext) != -1; }); if (!filepaths.length) { grunt.log.writeln('Nothing to live reload.'); return; } lrServer.changed({ body: { files: filepaths } }); }; // It's safer to wait in case of bulk changes. var restartDirsWatchersDebounced = grunt.util._.debounce( restartWatchers, RESTART_WATCHERS_DEBOUNCE); var runLiveReloadServer = function() { lrServer = tinylr(); lrServer.server.removeAllListeners('error'); lrServer.server.on('error', function(err) { if (err.code === 'EADDRINUSE') { grunt.fatal('Port ' + options.port + ' is already in use by another process.'); grunt.fatal('Open OS process manager and kill all node\'s processes.'); } else { grunt.fatal(err); } process.exit(1); }); lrServer.listen(options.livereload.port, function(err) { if (err) { grunt.fatal(err); return; } grunt.log.writeln( 'LiveReload server started on port: ' + options.livereload.port); }); }; // TODO: fork&fix Grunt var keepThisTaskRunForeverViaHideousHack = function() { var createLog = function(isWarning) { return function(e) { var message = typeof e == 'string' ? e : e.message; var line = options.beep ? '\x07' : ''; if (isWarning) { line += ('Warning: ' + message).yellow; if (grunt.option('force')) return; } else { line += ('Fatal error: ' + message).red; } grunt.log.writeln(line); rerun(); }; }; grunt.warn = grunt.fail.warn = createLog(true); grunt.fatal = grunt.fail.fatal = createLog(false); }; var rerun = function() { grunt.task.clearQueue(); grunt.task.run('esteWatch'); }; var dispatchWaitingChanges = function() { var waitingFiles = grunt.util._.uniq(filesChangedWithinWatchTask); grunt.verbose.ok('Files changed within watch task:'); grunt.verbose.ok(waitingFiles); var ignoredFiles = filesChangedWithinWatchTask.dispatcher; filesChangedWithinWatchTask = []; waitingFiles.forEach(function(filepath) { if (filepath == ignoredFiles) return; onFileChange(filepath); }); }; var closeWatchers = function() { watchers.forEach(function(watcher) { watcher.close(); }); watchers = []; }; var watchDirs = function(dirs) { dirs.forEach(function(dir) { var watcher = fs.watch(dir, function(event, filename) { onDirChange(event, filename, dir); }); watchers.push(watcher); }); }; var onDirChange = function(event, filename, dir) { var filepath = path.join(dir || '', filename || ''); // Normalize \\ paths to / paths. Yet another Windows fix. filepath = filepath.replace(/\\/g, '/'); // fs.statSync fails on deleted symlink dir with "Abort trap: 6" exception // https://github.com/bevry/watchr/issues/42 // https://github.com/joyent/node/issues/4261 var fileExists = fs.existsSync(filepath); if (!fileExists) return; if (fs.statSync(filepath).isDirectory()) { grunt.log.ok('Dir changed: ' + filepath); restartDirsWatchersDebounced(); return; } onFileChange(filepath); }; var onFileChange = function(filepath) { if (options.ignoredFiles.indexOf(filepath) != -1) return; if (options.livereload.enabled) changedFilesForLiveReload.push(filepath); // postpone changes occured during tasks execution if (esteWatchTaskIsRunning) { grunt.verbose.writeln('filesChangedWithinWatchTask.push ' + filepath); filesChangedWithinWatchTask.push(filepath); return; } if (grunt.task.current.name == 'esteWatch') { esteWatchTaskIsRunning = true; // We have to track file which dispatched watch task, because on Windows // file change dispatches two or more events, which is actually ok, but // we have to ignore these changes later. // https://github.com/joyent/node/issues/2126 filesChangedWithinWatchTask.dispatcher = filepath; } // detect user's 'unit of work' var userAction = (Date.now() - watchTaskStart) > 500; if (userAction) { grunt.log.ok('User action.'.yellow); } // run tasks for changed file grunt.log.ok('File changed: ' + filepath); var tasks = getFilepathTasks(filepath); if (options.livereload.enabled) tasks.push('esteWatchLiveReload'); tasks.push('esteWatch'); var waitTryCount = 0; var waitForFileUnlock = function() { var isLocked = false; waitTryCount++; try { fs.readFileSync(filepath); } catch (e) { // File is locked isLocked = true; } if(!isLocked || waitTryCount > WAIT_FOR_UNLOCK_TRY_LIMIT) { done(); grunt.task.run(tasks); } else { grunt.verbose.writeln('Waiting for file to unlock (' + waitTryCount + '): ' + filepath); clearTimeout(unlockTimer); unlockTimer = setTimeout(waitForFileUnlock, WAIT_FOR_UNLOCK_INTERVAL); } }; waitForFileUnlock(); }; var getFilepathTasks = function(filepath) { var ext = path.extname(filepath).slice(1); var config = grunt.config.get(['esteWatch', ext]); if (!config) config = grunt.config.get(['esteWatch', '*']); if (!config) return []; var tasks = config(filepath) || []; if (!Array.isArray(tasks)) tasks = [tasks]; return tasks; }; };
(function(window) { 'use strict'; var utils = utils || {}; utils.byId=function(selector){ return document.getElementById(selector); } utils.selector=function(selector){ return document.selector(); } utils.selectorAll=function(selector){ return document.selectorAll(); } utils.addEvent = function(el, type, fn, capture) { el.addEventListener(type, fn, !!capture); }; utils.removeEevent = function(el, type, fn, capture) { el.removeEventListener(type, fn, !!capture); }; utils.changeTip = function(el, attr, message) { var res = document.getElementById("it-" + attr); res.innerHTML = message; } utils.addTargetId = function(target, el) { var re; eval('re = /(<[^>]+for=["\\\']' + target.id + '["\\\'][^>]*)(>)([^>]*?)(<\\/[^>]+>)/;'); el.innerHTML = el.innerHTML.replace(re, "$1 id = 'it-" + target.id + "'$2$3$4"); } var reg = { require: { reg: /[\w\W]+/, message: "内容不能为空" }, digit: { reg: /\d*/, message: "请输入数字" }, phone: { reg: /\d{11}/, message: "请输入正确手机号码" }, mail: { reg: /[a-zA-Z0-9_]+@[a-zA-Z0-9]+\.[a-zA-Z]+/, message: "请输入正确的邮箱地址" } }; function FormEmt(emt,rule) { this.emt = emt; this.value = emt.value; this.rule = rule.split(','); } FormEmt.prototype = { verification: function() { var val = this.value; return this.rule.every(function(item, index) { var reg_express = reg[item].reg, pat = new RegExp(reg_express), message = reg[item].message; console.log(pat); console.log(val); console.log(pat.test(val)); return pat.test(val); }, true) }, createTip: function() { } } var formElementReg = /select|input|textarea/i; var ivalidate = function(selector, params) { return new ivalidate.fn.init(selector,params); }; ivalidate.prototype = ivalidate.fn = { init: function(name,cb) { this.eles = []; name=name ||""; this.target = document.forms[name]; if(this.target){ var eles=this.target.elements; for(var i=0;i<eles.length;i++){ var item=eles[i],iv=item.getAttribute("iv"); console.log(item); if(item.name!=="" && iv){ var fe=new FormEmt(item,iv); this.eles.push(fe); } } } this._onSubmit(cb); }, _setRegulare: function() { //todo 设置验证规则 }, _onSubmit: function(cb) { var that=this; console.log(cb); utils.addEvent(this.target, "submit", function(event) { var res=that._validate(); if(cb && cb["submit"]){ cb["submit"].call(that,res); event.preventDefault(); }else{ if(!res.result){ alert("fail"); event.preventDefault(); } } }) }, _validate: function() { var res=this.eles.every(function(emt, ix) { return emt.verification(); }) return {result:res}; } } ivalidate.fn.init.prototype = ivalidate.prototype; window.iv = ivalidate; })(window);
module.exports = { "google": { search: "mail.google.com", title: "Gmail - Free Storage and Email from Google" } };
'use strict'; import Base from './ArticleBase'; import Render from './ArticleRender'; export default class Article extends Base { constructor (props) { super(props); } render () { return Render.call(this, this.props, this.state); } }
function test(fun,expected){/*若干项测试用例能否保障 执行一段代码 expected的值*/ } /*测试一定需要构造测试用例,怎么样才能判断测试通过还是失败,*/ module.exports=mix(x,{ test:test });
var _ = require('underscore'); module.exports = function(app, nox) { var json = function(res, json) { res.writeHead(200, { 'content-type': 'text/json' }); res.write(JSON.stringify(json)); res.end('\n'); }; app.get('/', function(req, res){ res.render('index', { title: "Nox", requests: nox.currentRequests(), sounds: (req.query.sounds == 'false') ? false : true }); }); app.all('/request', function(req, res) { nox.addRequest(req, res); }); app.get('/kill-all', function(req, res) { nox.killAll(); res.redirect('/'); }); app.delete('/kill/:id', function(req, res) { var request = nox.findRequest(req.params.id); nox.killRequest(request); json(res, { ok: true }); }); app.post('/response/:id', function(req, res) { var request = nox.findRequest(req.params.id); nox.respondToRequest(request, { statusCode: req.body.statusCode, contentType: req.body.contentType, body: req.body.response }); json(res, { ok: true }); }); app.get('/perform/:id', function(req, res) { var request = nox.findRequest(req.params.id); nox.performRequest(request, function(response, error) { if(error) json(res, { ok: false, error: error }); else json(res, _.extend({ ok: true }, response)); }); }); }
/*! * JSHint, by JSHint Community. * * Licensed under the same slightly modified MIT license that JSLint is. * It stops evil-doers everywhere. * * JSHint is a derivative work of JSLint: * * Copyright (c) 2002 Douglas Crockford (www.JSLint.com) * * 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 shall be used for Good, not Evil. * * 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. * * JSHint was forked from 2010-12-16 edition of JSLint. * */ /* JSHINT is a global function. It takes two parameters. var myResult = JSHINT(source, option); The first parameter is either a string or an array of strings. If it is a string, it will be split on '\n' or '\r'. If it is an array of strings, it is assumed that each string represents one line. The source can be a JavaScript text or a JSON text. The second parameter is an optional object of options which control the operation of JSHINT. Most of the options are booleans: They are all optional and have a default value of false. One of the options, predef, can be an array of names, which will be used to declare global variables, or an object whose keys are used as global names, with a boolean value that determines if they are assignable. If it checks out, JSHINT returns true. Otherwise, it returns false. If false, you can inspect JSHINT.errors to find out the problems. JSHINT.errors is an array of objects containing these members: { line : The line (relative to 0) at which the lint was found character : The character (relative to 0) at which the lint was found reason : The problem evidence : The text line in which the problem occurred raw : The raw message before the details were inserted a : The first detail b : The second detail c : The third detail d : The fourth detail } If a fatal error was found, a null will be the last element of the JSHINT.errors array. You can request a Function Report, which shows all of the functions and the parameters and vars that they use. This can be used to find implied global variables and other problems. The report is in HTML and can be inserted in an HTML <body>. var myReport = JSHINT.report(limited); If limited is true, then the report will be limited to only errors. You can request a data structure which contains JSHint's results. var myData = JSHINT.data(); It returns a structure with this form: { errors: [ { line: NUMBER, character: NUMBER, reason: STRING, evidence: STRING } ], functions: [ name: STRING, line: NUMBER, last: NUMBER, param: [ STRING ], closure: [ STRING ], var: [ STRING ], exception: [ STRING ], outer: [ STRING ], unused: [ STRING ], global: [ STRING ], label: [ STRING ] ], globals: [ STRING ], member: { STRING: NUMBER }, unused: [ { name: STRING, line: NUMBER } ], implieds: [ { name: STRING, line: NUMBER } ], urls: [ STRING ], json: BOOLEAN } Empty arrays will not be included. */ /*jshint evil: true, nomen: false, onevar: false, regexp: false, strict: true, boss: true, undef: true, maxlen: 100, indent:4 */ /*members "\b", "\t", "\n", "\f", "\r", "!=", "!==", "\"", "%", "(begin)", "(breakage)", "(context)", "(error)", "(global)", "(identifier)", "(last)", "(line)", "(loopage)", "(name)", "(onevar)", "(params)", "(scope)", "(statement)", "(verb)", "*", "+", "++", "-", "--", "\/", "<", "<=", "==", "===", ">", ">=", $, $$, $A, $F, $H, $R, $break, $continue, $w, Abstract, Ajax, __filename, __dirname, ActiveXObject, Array, ArrayBuffer, ArrayBufferView, Audio, Autocompleter, Assets, Boolean, Builder, Buffer, Browser, COM, CScript, Canvas, CustomAnimation, Class, Control, Chain, Color, Cookie, Core, DataView, Date, Debug, Draggable, Draggables, Droppables, Document, DomReady, DOMReady, Drag, E, Enumerator, Enumerable, Element, Elements, Error, Effect, EvalError, Event, Events, FadeAnimation, Field, Flash, Float32Array, Float64Array, Form, FormField, Frame, FormData, Function, Fx, GetObject, Group, Hash, HotKey, HTMLElement, HTMLAnchorElement, HTMLBaseElement, HTMLBlockquoteElement, HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLCanvasElement, HTMLDirectoryElement, HTMLDivElement, HTMLDListElement, HTMLFieldSetElement, HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, HTMLLabelElement, HTMLLayerElement, HTMLLegendElement, HTMLLIElement, HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, HtmlTable, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement, HTMLVideoElement, Iframe, IframeShim, Image, Int16Array, Int32Array, Int8Array, Insertion, InputValidator, JSON, Keyboard, Locale, LN10, LN2, LOG10E, LOG2E, MAX_VALUE, MIN_VALUE, Mask, Math, MenuItem, MoveAnimation, MooTools, Native, NEGATIVE_INFINITY, Number, Object, ObjectRange, Option, Options, OverText, PI, POSITIVE_INFINITY, PeriodicalExecuter, Point, Position, Prototype, RangeError, Rectangle, ReferenceError, RegExp, ResizeAnimation, Request, RotateAnimation, SQRT1_2, SQRT2, ScrollBar, ScriptEngine, ScriptEngineBuildVersion, ScriptEngineMajorVersion, ScriptEngineMinorVersion, Scriptaculous, Scroller, Slick, Slider, Selector, SharedWorker, String, Style, SyntaxError, Sortable, Sortables, SortableObserver, Sound, Spinner, System, Swiff, Text, TextArea, Template, Timer, Tips, Type, TypeError, Toggle, Try, "use strict", unescape, URI, URIError, URL, VBArray, WSH, WScript, XDomainRequest, Web, Window, XMLDOM, XMLHttpRequest, XPathEvaluator, XPathException, XPathExpression, XPathNamespace, XPathNSResolver, XPathResult, "\\", a, addEventListener, address, alert, apply, applicationCache, arguments, arity, asi, b, basic, basicToken, bitwise, block, blur, boolOptions, boss, browser, c, call, callee, caller, cases, charAt, charCodeAt, character, clearInterval, clearTimeout, close, closed, closure, comment, condition, confirm, console, constructor, content, couch, create, css, curly, d, data, datalist, dd, debug, decodeURI, decodeURIComponent, defaultStatus, defineClass, deserialize, devel, document, dojo, dijit, dojox, define, else, emit, encodeURI, encodeURIComponent, entityify, eqeqeq, eqnull, errors, es5, escape, esnext, eval, event, evidence, evil, ex, exception, exec, exps, expr, exports, FileReader, first, floor, focus, forin, fragment, frames, from, fromCharCode, fud, funcscope, funct, function, functions, g, gc, getComputedStyle, getRow, getter, getterToken, GLOBAL, global, globals, globalstrict, hasOwnProperty, help, history, i, id, identifier, immed, implieds, importPackage, include, indent, indexOf, init, ins, instanceOf, isAlpha, isApplicationRunning, isArray, isDigit, isFinite, isNaN, iterator, java, join, jshint, JSHINT, json, jquery, jQuery, keys, label, labelled, last, lastsemic, laxbreak, latedef, lbp, led, left, length, line, load, loadClass, localStorage, location, log, loopfunc, m, match, maxerr, maxlen, member,message, meta, module, moveBy, moveTo, mootools, multistr, name, navigator, new, newcap, noarg, node, noempty, nomen, nonew, nonstandard, nud, onbeforeunload, onblur, onerror, onevar, onecase, onfocus, onload, onresize, onunload, open, openDatabase, openURL, opener, opera, options, outer, param, parent, parseFloat, parseInt, passfail, plusplus, predef, print, process, prompt, proto, prototype, prototypejs, provides, push, quit, range, raw, reach, reason, regexp, readFile, readUrl, regexdash, removeEventListener, replace, report, require, reserved, resizeBy, resizeTo, resolvePath, resumeUpdates, respond, rhino, right, runCommand, scroll, screen, scripturl, scrollBy, scrollTo, scrollbar, search, seal, send, serialize, sessionStorage, setInterval, setTimeout, setter, setterToken, shift, slice, smarttabs, sort, spawn, split, stack, status, start, strict, sub, substr, supernew, shadow, supplant, sum, sync, test, toLowerCase, toString, toUpperCase, toint32, token, top, trailing, type, typeOf, Uint16Array, Uint32Array, Uint8Array, undef, undefs, unused, urls, validthis, value, valueOf, var, version, WebSocket, white, window, Worker, wsh*/ /*global exports: false */ // We build the application inside a function so that we produce only a single // global variable. That function will be invoked immediately, and its return // value is the JSHINT function itself. var JSHINT = (function () { "use strict"; var anonname, // The guessed name for anonymous functions. // These are operators that should not be used with the ! operator. bang = { '<' : true, '<=' : true, '==' : true, '===': true, '!==': true, '!=' : true, '>' : true, '>=' : true, '+' : true, '-' : true, '*' : true, '/' : true, '%' : true }, // These are the JSHint boolean options. boolOptions = { asi : true, // if automatic semicolon insertion should be tolerated bitwise : true, // if bitwise operators should not be allowed boss : true, // if advanced usage of assignments should be allowed browser : true, // if the standard browser globals should be predefined couch : true, // if CouchDB globals should be predefined curly : true, // if curly braces around all blocks should be required debug : true, // if debugger statements should be allowed devel : true, // if logging globals should be predefined (console, // alert, etc.) dojo : true, // if Dojo Toolkit globals should be predefined eqeqeq : true, // if === should be required eqnull : true, // if == null comparisons should be tolerated es5 : true, // if ES5 syntax should be allowed esnext : true, // if es.next specific syntax should be allowed evil : true, // if eval should be allowed expr : true, // if ExpressionStatement should be allowed as Programs forin : true, // if for in statements must filter funcscope : true, // if only function scope should be used for scope tests globalstrict: true, // if global "use strict"; should be allowed (also // enables 'strict') immed : true, // if immediate invocations must be wrapped in parens iterator : true, // if the `__iterator__` property should be allowed jquery : true, // if jQuery globals should be predefined lastsemic : true, // if semicolons may be ommitted for the trailing // statements inside of a one-line blocks. latedef : true, // if the use before definition should not be tolerated laxbreak : true, // if line breaks should not be checked loopfunc : true, // if functions should be allowed to be defined within // loops mootools : true, // if MooTools globals should be predefined multistr : true, // allow multiline strings newcap : true, // if constructor names must be capitalized noarg : true, // if arguments.caller and arguments.callee should be // disallowed node : true, // if the Node.js environment globals should be // predefined noempty : true, // if empty blocks should be disallowed nonew : true, // if using `new` for side-effects should be disallowed nonstandard : true, // if non-standard (but widely adopted) globals should // be predefined nomen : true, // if names should be checked onevar : true, // if only one var statement per function should be // allowed onecase : true, // if one case switch statements should be allowed passfail : true, // if the scan should stop on first error plusplus : true, // if increment/decrement should not be allowed proto : true, // if the `__proto__` property should be allowed prototypejs : true, // if Prototype and Scriptaculous globals should be // predefined regexdash : true, // if unescaped first/last dash (-) inside brackets // should be tolerated regexp : true, // if the . should not be allowed in regexp literals rhino : true, // if the Rhino environment globals should be predefined undef : true, // if variables should be declared before used scripturl : true, // if script-targeted URLs should be tolerated shadow : true, // if variable shadowing should be tolerated smarttabs : true, // if smarttabs should be tolerated // (http://www.emacswiki.org/emacs/SmartTabs) strict : true, // require the "use strict"; pragma sub : true, // if all forms of subscript notation are tolerated supernew : true, // if `new function () { ... };` and `new Object;` // should be tolerated trailing : true, // if trailing whitespace rules apply validthis : true, // if 'this' inside a non-constructor function is valid. // This is a function scoped option only. white : true, // if strict whitespace rules apply wsh : true // if the Windows Scripting Host environment globals // should be predefined }, // browser contains a set of global names which are commonly provided by a // web browser environment. browser = { ArrayBuffer : false, ArrayBufferView : false, Audio : false, addEventListener : false, applicationCache : false, blur : false, clearInterval : false, clearTimeout : false, close : false, closed : false, DataView : false, defaultStatus : false, document : false, event : false, FileReader : false, Float32Array : false, Float64Array : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement : false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement : false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement : false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Int16Array : false, Int32Array : false, Int8Array : false, Image : false, length : false, localStorage : false, location : false, moveBy : false, moveTo : false, name : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, print : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, top : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, WebSocket : false, window : false, Worker : false, XMLHttpRequest : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }, couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }, devel = { alert : false, confirm : false, console : false, Debug : false, opera : false, prompt : false }, dojo = { dojo : false, dijit : false, dojox : false, define : false, "require" : false }, escapes = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '/' : '\\/', '\\': '\\\\' }, funct, // The current function functionicity = [ 'closure', 'exception', 'global', 'label', 'outer', 'unused', 'var' ], functions, // All of the functions global, // The global scope implied, // Implied globals inblock, indent, jsonmode, jquery = { '$' : false, jQuery : false }, lines, lookahead, member, membersOnly, mootools = { '$' : false, '$$' : false, Assets : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, Iframe : false, IframeShim : false, InputValidator : false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }, nexttoken, node = { __filename : false, __dirname : false, Buffer : false, console : false, exports : false, GLOBAL : false, global : false, module : false, process : false, require : false, setTimeout : false, clearTimeout : false, setInterval : false, clearInterval : false }, noreach, option, predefined, // Global variables defined by option prereg, prevtoken, prototypejs = { '$' : false, '$$' : false, '$A' : false, '$F' : false, '$H' : false, '$R' : false, '$break' : false, '$continue' : false, '$w' : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }, rhino = { defineClass : false, deserialize : false, gc : false, help : false, importPackage: false, "java" : false, load : false, loadClass : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }, scope, // The current scope stack, // standard contains the global names that are provided by the // ECMAScript standard. standard = { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, 'eval' : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, JSON : false, Math : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, String : false, SyntaxError : false, TypeError : false, URIError : false }, // widely adopted global names that are not part of ECMAScript standard nonstandard = { escape : false, unescape : false }, standard_member = { E : true, LN2 : true, LN10 : true, LOG2E : true, LOG10E : true, MAX_VALUE : true, MIN_VALUE : true, NEGATIVE_INFINITY : true, PI : true, POSITIVE_INFINITY : true, SQRT1_2 : true, SQRT2 : true }, directive, syntax = {}, tab, token, urls, useESNextSyntax, warnings, wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; // Regular expressions. Some of these are stupidly long. var ax, cx, tx, nx, nxg, lx, ix, jx, ft; (function () { /*jshint maxlen:300 */ // unsafe comment or string ax = /@cc|<\/?|script|\]\s*\]|<\s*!|&lt/i; // unsafe characters that are silently deleted by one or more browsers cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; // token tx = /^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/(\*(jshint|jslint|members?|global)?|=|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/; // characters in strings that need escapement nx = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; nxg = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // star slash lx = /\*\/|\/\*/; // identifier ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; // javascript url jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i; // catches /* falls through */ comments ft = /^\s*\/\*\s*falls\sthrough\s*\*\/\s*$/; }()); function F() {} // Used by Object.create function is_own(object, name) { // The object.hasOwnProperty method fails when the property under consideration // is named 'hasOwnProperty'. So we have to use this more convoluted form. return Object.prototype.hasOwnProperty.call(object, name); } // Provide critical ES5 functions to ES3. if (typeof Array.isArray !== 'function') { Array.isArray = function (o) { return Object.prototype.toString.apply(o) === '[object Array]'; }; } if (typeof Object.create !== 'function') { Object.create = function (o) { F.prototype = o; return new F(); }; } if (typeof Object.keys !== 'function') { Object.keys = function (o) { var a = [], k; for (k in o) { if (is_own(o, k)) { a.push(k); } } return a; }; } // Non standard methods if (typeof String.prototype.entityify !== 'function') { String.prototype.entityify = function () { return this .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }; } if (typeof String.prototype.isAlpha !== 'function') { String.prototype.isAlpha = function () { return (this >= 'a' && this <= 'z\uffff') || (this >= 'A' && this <= 'Z\uffff'); }; } if (typeof String.prototype.isDigit !== 'function') { String.prototype.isDigit = function () { return (this >= '0' && this <= '9'); }; } if (typeof String.prototype.supplant !== 'function') { String.prototype.supplant = function (o) { return this.replace(/\{([^{}]*)\}/g, function (a, b) { var r = o[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); }; } if (typeof String.prototype.name !== 'function') { String.prototype.name = function () { // If the string looks like an identifier, then we can return it as is. // If the string contains no control characters, no quote characters, and no // backslash characters, then we can simply slap some quotes around it. // Otherwise we must also replace the offending characters with safe // sequences. if (ix.test(this)) { return this; } if (nx.test(this)) { return '"' + this.replace(nxg, function (a) { var c = escapes[a]; if (c) { return c; } return '\\u' + ('0000' + a.charCodeAt().toString(16)).slice(-4); }) + '"'; } return '"' + this + '"'; }; } function combine(t, o) { var n; for (n in o) { if (is_own(o, n)) { t[n] = o[n]; } } } function assume() { if (option.couch) { combine(predefined, couch); } if (option.rhino) { combine(predefined, rhino); } if (option.prototypejs) { combine(predefined, prototypejs); } if (option.node) { combine(predefined, node); } if (option.devel) { combine(predefined, devel); } if (option.dojo) { combine(predefined, dojo); } if (option.browser) { combine(predefined, browser); } if (option.nonstandard) { combine(predefined, nonstandard); } if (option.jquery) { combine(predefined, jquery); } if (option.mootools) { combine(predefined, mootools); } if (option.wsh) { combine(predefined, wsh); } if (option.esnext) { useESNextSyntax(); } if (option.globalstrict && option.strict !== false) { option.strict = true; } } // Produce an error warning. function quit(message, line, chr) { var percentage = Math.floor((line / lines.length) * 100); throw { name: 'JSHintError', line: line, character: chr, message: message + " (" + percentage + "% scanned).", raw: message }; } function isundef(scope, m, t, a) { return JSHINT.undefs.push([scope, m, t, a]); } function warning(m, t, a, b, c, d) { var ch, l, w; t = t || nexttoken; if (t.id === '(end)') { // `~ t = token; } l = t.line || 0; ch = t.from || 0; w = { id: '(error)', raw: m, evidence: lines[l - 1] || '', line: l, character: ch, a: a, b: b, c: c, d: d }; w.reason = m.supplant(w); JSHINT.errors.push(w); if (option.passfail) { quit('Stopping. ', l, ch); } warnings += 1; if (warnings >= option.maxerr) { quit("Too many errors.", l, ch); } return w; } function warningAt(m, l, ch, a, b, c, d) { return warning(m, { line: l, from: ch }, a, b, c, d); } function error(m, t, a, b, c, d) { var w = warning(m, t, a, b, c, d); } function errorAt(m, l, ch, a, b, c, d) { return error(m, { line: l, from: ch }, a, b, c, d); } // lexical analysis and token construction var lex = (function lex() { var character, from, line, s; // Private lex methods function nextLine() { var at, tw; // trailing whitespace check if (line >= lines.length) return false; character = 1; s = lines[line]; line += 1; // If smarttabs option is used check for spaces followed by tabs only. // Otherwise check for any occurence of mixed tabs and spaces. if (option.smarttabs) at = s.search(/ \t/); else at = s.search(/ \t|\t /); if (at >= 0) warningAt("Mixed spaces and tabs.", line, at + 1); s = s.replace(/\t/g, tab); at = s.search(cx); if (at >= 0) warningAt("Unsafe character.", line, at); if (option.maxlen && option.maxlen < s.length) warningAt("Line too long.", line, s.length); // Check for trailing whitespaces tw = /\s+$/.test(s); if (option.trailing && tw && !/^\s+$/.test(s)) { warningAt("Trailing whitespace.", line, tw); } return true; } // Produce a token object. The token inherits from a syntax symbol. function it(type, value) { var i, t; if (type === '(color)' || type === '(range)') { t = {type: type}; } else if (type === '(punctuator)' || (type === '(identifier)' && is_own(syntax, value))) { t = syntax[value] || syntax['(error)']; } else { t = syntax[type]; } t = Object.create(t); if (type === '(string)' || type === '(range)') { if (!option.scripturl && jx.test(value)) { warningAt("Script URL.", line, from); } } if (type === '(identifier)') { t.identifier = true; if (value === '__proto__' && !option.proto) { warningAt("The '{a}' property is deprecated.", line, from, value); } else if (value === '__iterator__' && !option.iterator) { warningAt("'{a}' is only available in JavaScript 1.7.", line, from, value); } else if (option.nomen && (value.charAt(0) === '_' || value.charAt(value.length - 1) === '_')) { if (!option.node || token.id === '.' || (value !== '__dirname' && value !== '__filename')) { warningAt("Unexpected {a} in '{b}'.", line, from, "dangling '_'", value); } } } t.value = value; t.line = line; t.character = character; t.from = from; i = t.id; if (i !== '(endline)') { prereg = i && (('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) || i === 'return' || i === 'case'); } return t; } // Public lex methods return { init: function (source) { if (typeof source === 'string') { lines = source .replace(/\r\n/g, '\n') .replace(/\r/g, '\n') .split('\n'); } else { lines = source; } // If the first line is a shebang (#!), make it a blank and move on. // Shebangs are used by Node scripts. if (lines[0] && lines[0].substr(0, 2) === '#!') lines[0] = ''; line = 0; nextLine(); from = 1; }, range: function (begin, end) { var c, value = ''; from = character; if (s.charAt(0) !== begin) { errorAt("Expected '{a}' and instead saw '{b}'.", line, character, begin, s.charAt(0)); } for (;;) { s = s.slice(1); character += 1; c = s.charAt(0); switch (c) { case '': errorAt("Missing '{a}'.", line, character, c); break; case end: s = s.slice(1); character += 1; return it('(range)', value); case '\\': warningAt("Unexpected '{a}'.", line, character, c); } value += c; } }, // token -- this is called by advance to get the next token token: function () { var b, c, captures, d, depth, high, i, l, low, q, t, isLiteral, isInRange; function match(x) { var r = x.exec(s), r1; if (r) { l = r[0].length; r1 = r[1]; c = r1.charAt(0); s = s.substr(l); from = character + l - r1.length; character += l; return r1; } } function string(x) { var c, j, r = '', allowNewLine = false; if (jsonmode && x !== '"') { warningAt("Strings must use doublequote.", line, character); } function esc(n) { var i = parseInt(s.substr(j + 1, n), 16); j += n; if (i >= 32 && i <= 126 && i !== 34 && i !== 92 && i !== 39) { warningAt("Unnecessary escapement.", line, character); } character += n; c = String.fromCharCode(i); } j = 0; unclosedString: for (;;) { while (j >= s.length) { j = 0; var cl = line, cf = from; if (!nextLine()) { errorAt("Unclosed string.", cl, cf); break unclosedString; } if (allowNewLine) { allowNewLine = false; } else { warningAt("Unclosed string.", cl, cf); } } c = s.charAt(j); if (c === x) { character += 1; s = s.substr(j + 1); return it('(string)', r, x); } if (c < ' ') { if (c === '\n' || c === '\r') { break; } warningAt("Control character in string: {a}.", line, character + j, s.slice(0, j)); } else if (c === '\\') { j += 1; character += 1; c = s.charAt(j); switch (c) { case '\\': case '"': case '/': break; case '\'': if (jsonmode) { warningAt("Avoid \\'.", line, character); } break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'u': esc(4); break; case 'v': if (jsonmode) { warningAt("Avoid \\v.", line, character); } c = '\v'; break; case 'x': if (jsonmode) { warningAt("Avoid \\x-.", line, character); } esc(2); break; case '': // last character is escape character // always allow new line if escaped, but show // warning if option is not set allowNewLine = true; if (option.multistr) { if (jsonmode) { warningAt("Avoid EOL escapement.", line, character); } c = ''; character -= 1; break; } warningAt("Bad escapement of EOL. Use option multistr if needed.", line, character); break; default: warningAt("Bad escapement.", line, character); } } r += c; character += 1; j += 1; } } for (;;) { if (!s) { return it(nextLine() ? '(endline)' : '(end)', ''); } t = match(tx); if (!t) { t = ''; c = ''; while (s && s < '!') { s = s.substr(1); } if (s) { errorAt("Unexpected '{a}'.", line, character, s.substr(0, 1)); s = ''; } } else { // identifier if (c.isAlpha() || c === '_' || c === '$') { return it('(identifier)', t); } // number if (c.isDigit()) { if (!isFinite(Number(t))) { warningAt("Bad number '{a}'.", line, character, t); } if (s.substr(0, 1).isAlpha()) { warningAt("Missing space after '{a}'.", line, character, t); } if (c === '0') { d = t.substr(1, 1); if (d.isDigit()) { if (token.id !== '.') { warningAt("Don't use extra leading zeros '{a}'.", line, character, t); } } else if (jsonmode && (d === 'x' || d === 'X')) { warningAt("Avoid 0x-. '{a}'.", line, character, t); } } if (t.substr(t.length - 1) === '.') { warningAt( "A trailing decimal point can be confused with a dot '{a}'.", line, character, t); } return it('(number)', t); } switch (t) { // string case '"': case "'": return string(t); // // comment case '//': s = ''; token.comment = true; break; // /* comment case '/*': for (;;) { i = s.search(lx); if (i >= 0) { break; } if (!nextLine()) { errorAt("Unclosed comment.", line, character); } } character += i + 2; if (s.substr(i, 1) === '/') { errorAt("Nested comment.", line, character); } s = s.substr(i + 2); token.comment = true; break; // /*members /*jshint /*global case '/*members': case '/*member': case '/*jshint': case '/*jslint': case '/*global': case '*/': return { value: t, type: 'special', line: line, character: character, from: from }; case '': break; // / case '/': if (token.id === '/=') { errorAt("A regular expression literal can be confused with '/='.", line, from); } if (prereg) { depth = 0; captures = 0; l = 0; for (;;) { b = true; c = s.charAt(l); l += 1; switch (c) { case '': errorAt("Unclosed regular expression.", line, from); return quit('Stopping.', line, from); case '/': if (depth > 0) { warningAt("{a} unterminated regular expression " + "group(s).", line, from + l, depth); } c = s.substr(0, l - 1); q = { g: true, i: true, m: true }; while (q[s.charAt(l)] === true) { q[s.charAt(l)] = false; l += 1; } character += l; s = s.substr(l); q = s.charAt(0); if (q === '/' || q === '*') { errorAt("Confusing regular expression.", line, from); } return it('(regexp)', c); case '\\': c = s.charAt(l); if (c < ' ') { warningAt( "Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt( "Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; break; case '(': depth += 1; b = false; if (s.charAt(l) === '?') { l += 1; switch (s.charAt(l)) { case ':': case '=': case '!': l += 1; break; default: warningAt( "Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l)); } } else { captures += 1; } break; case '|': b = false; break; case ')': if (depth === 0) { warningAt("Unescaped '{a}'.", line, from + l, ')'); } else { depth -= 1; } break; case ' ': q = 1; while (s.charAt(l) === ' ') { l += 1; q += 1; } if (q > 1) { warningAt( "Spaces are hard to count. Use {{a}}.", line, from + l, q); } break; case '[': c = s.charAt(l); if (c === '^') { l += 1; if (option.regexp) { warningAt("Insecure '{a}'.", line, from + l, c); } else if (s.charAt(l) === ']') { errorAt("Unescaped '{a}'.", line, from + l, '^'); } } if (c === ']') { warningAt("Empty class.", line, from + l - 1); } isLiteral = false; isInRange = false; klass: do { c = s.charAt(l); l += 1; switch (c) { case '[': case '^': warningAt("Unescaped '{a}'.", line, from + l, c); if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '-': if (isLiteral && !isInRange) { isLiteral = false; isInRange = true; } else if (isInRange) { isInRange = false; } else if (s.charAt(l) === ']') { isInRange = true; } else { if (option.regexdash !== (l === 2 || (l === 3 && s.charAt(1) === '^'))) { warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); } isLiteral = true; } break; case ']': if (isInRange && !option.regexdash) { warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); } break klass; case '\\': c = s.charAt(l); if (c < ' ') { warningAt( "Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt( "Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; // \w, \s and \d are never part of a character range if (/[wsd]/i.test(c)) { if (isInRange) { warningAt("Unescaped '{a}'.", line, from + l, '-'); isInRange = false; } isLiteral = false; } else if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '/': warningAt("Unescaped '{a}'.", line, from + l - 1, '/'); if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '<': if (isInRange) { isInRange = false; } else { isLiteral = true; } break; default: if (isInRange) { isInRange = false; } else { isLiteral = true; } } } while (c); break; case '.': if (option.regexp) { warningAt("Insecure '{a}'.", line, from + l, c); } break; case ']': case '?': case '{': case '}': case '+': case '*': warningAt("Unescaped '{a}'.", line, from + l, c); } if (b) { switch (s.charAt(l)) { case '?': case '+': case '*': l += 1; if (s.charAt(l) === '?') { l += 1; } break; case '{': l += 1; c = s.charAt(l); if (c < '0' || c > '9') { warningAt( "Expected a number and instead saw '{a}'.", line, from + l, c); } l += 1; low = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; low = +c + (low * 10); } high = low; if (c === ',') { l += 1; high = Infinity; c = s.charAt(l); if (c >= '0' && c <= '9') { l += 1; high = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; high = +c + (high * 10); } } } if (s.charAt(l) !== '}') { warningAt( "Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c); } else { l += 1; } if (s.charAt(l) === '?') { l += 1; } if (low > high) { warningAt( "'{a}' should not be greater than '{b}'.", line, from + l, low, high); } } } } c = s.substr(0, l - 1); character += l; s = s.substr(l); return it('(regexp)', c); } return it('(punctuator)', t); // punctuator case '#': return it('(punctuator)', t); default: return it('(punctuator)', t); } } } } }; }()); function addlabel(t, type) { if (t === 'hasOwnProperty') { warning("'hasOwnProperty' is a really bad name."); } // Define t in the current function in the current scope. if (is_own(funct, t) && !funct['(global)']) { if (funct[t] === true) { if (option.latedef) warning("'{a}' was used before it was defined.", nexttoken, t); } else { if (!option.shadow && type !== "exception") warning("'{a}' is already defined.", nexttoken, t); } } funct[t] = type; if (funct['(global)']) { global[t] = funct; if (is_own(implied, t)) { if (option.latedef) warning("'{a}' was used before it was defined.", nexttoken, t); delete implied[t]; } } else { scope[t] = funct; } } function doOption() { var b, obj, filter, o = nexttoken.value, t, v; switch (o) { case '*/': error("Unbegun comment."); break; case '/*members': case '/*member': o = '/*members'; if (!membersOnly) { membersOnly = {}; } obj = membersOnly; break; case '/*jshint': case '/*jslint': obj = option; filter = boolOptions; break; case '/*global': obj = predefined; break; default: error("What?"); } t = lex.token(); loop: for (;;) { for (;;) { if (t.type === 'special' && t.value === '*/') { break loop; } if (t.id !== '(endline)' && t.id !== ',') { break; } t = lex.token(); } if (t.type !== '(string)' && t.type !== '(identifier)' && o !== '/*members') { error("Bad option.", t); } v = lex.token(); if (v.id === ':') { v = lex.token(); if (obj === membersOnly) { error("Expected '{a}' and instead saw '{b}'.", t, '*/', ':'); } if (t.value === 'indent' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.white = true; obj.indent = b; } else if (t.value === 'maxerr' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.maxerr = b; } else if (t.value === 'maxlen' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.maxlen = b; } else if (t.value === 'validthis') { if (funct['(global)']) { error("Option 'validthis' can't be used in a global scope."); } else { if (v.value === 'true' || v.value === 'false') obj[t.value] = v.value === 'true'; else error("Bad option value.", v); } } else if (v.value === 'true') { obj[t.value] = true; } else if (v.value === 'false') { obj[t.value] = false; } else { error("Bad option value.", v); } t = lex.token(); } else { if (o === '/*jshint' || o === '/*jslint') { error("Missing option value.", t); } obj[t.value] = false; t = v; } } if (filter) { assume(); } } // We need a peek function. If it has an argument, it peeks that much farther // ahead. It is used to distinguish // for ( var i in ... // from // for ( var i = ... function peek(p) { var i = p || 0, j = 0, t; while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } return t; } // Produce the next token. It looks for programming errors. function advance(id, t) { switch (token.id) { case '(number)': if (nexttoken.id === '.') { warning("A dot following a number can be confused with a decimal point.", token); } break; case '-': if (nexttoken.id === '-' || nexttoken.id === '--') { warning("Confusing minusses."); } break; case '+': if (nexttoken.id === '+' || nexttoken.id === '++') { warning("Confusing plusses."); } break; } if (token.type === '(string)' || token.identifier) { anonname = token.value; } if (id && nexttoken.id !== id) { if (t) { if (nexttoken.id === '(end)') { warning("Unmatched '{a}'.", t, t.id); } else { warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", nexttoken, id, t.id, t.line, nexttoken.value); } } else if (nexttoken.type !== '(identifier)' || nexttoken.value !== id) { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, id, nexttoken.value); } } prevtoken = token; token = nexttoken; for (;;) { nexttoken = lookahead.shift() || lex.token(); if (nexttoken.id === '(end)' || nexttoken.id === '(error)') { return; } if (nexttoken.type === 'special') { doOption(); } else { if (nexttoken.id !== '(endline)') { break; } } } } // This is the heart of JSHINT, the Pratt parser. In addition to parsing, it // is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is // like .nud except that it is only used on the first token of a statement. // Having .fud makes it much easier to define statement-oriented languages like // JavaScript. I retained Pratt's nomenclature. // .nud Null denotation // .fud First null denotation // .led Left denotation // lbp Left binding power // rbp Right binding power // They are elements of the parsing method called Top Down Operator Precedence. function expression(rbp, initial) { var left, isArray = false; if (nexttoken.id === '(end)') error("Unexpected early end of program.", token); advance(); if (initial) { anonname = 'anonymous'; funct['(verb)'] = token.value; } if (initial === true && token.fud) { left = token.fud(); } else { if (token.nud) { left = token.nud(); } else { if (nexttoken.type === '(number)' && token.id === '.') { warning("A leading decimal point can be confused with a dot: '.{a}'.", token, nexttoken.value); advance(); return token; } else { error("Expected an identifier and instead saw '{a}'.", token, token.id); } } while (rbp < nexttoken.lbp) { isArray = token.value === 'Array'; advance(); if (isArray && token.id === '(' && nexttoken.id === ')') warning("Use the array literal notation [].", token); if (token.led) { left = token.led(left); } else { error("Expected an operator and instead saw '{a}'.", token, token.id); } } } return left; } // Functions for conformance of style. function adjacent(left, right) { left = left || token; right = right || nexttoken; if (option.white) { if (left.character !== right.from && left.line === right.line) { left.from += (left.character - left.from); warning("Unexpected space after '{a}'.", left, left.value); } } } function nobreak(left, right) { left = left || token; right = right || nexttoken; if (option.white && (left.character !== right.from || left.line !== right.line)) { warning("Unexpected space before '{a}'.", right, right.value); } } function nospace(left, right) { left = left || token; right = right || nexttoken; if (option.white && !left.comment) { if (left.line === right.line) { adjacent(left, right); } } } function nonadjacent(left, right) { if (option.white) { left = left || token; right = right || nexttoken; if (left.line === right.line && left.character === right.from) { left.from += (left.character - left.from); warning("Missing space after '{a}'.", left, left.value); } } } function nobreaknonadjacent(left, right) { left = left || token; right = right || nexttoken; if (!option.laxbreak && left.line !== right.line) { warning("Bad line breaking before '{a}'.", right, right.id); } else if (option.white) { left = left || token; right = right || nexttoken; if (left.character === right.from) { left.from += (left.character - left.from); warning("Missing space after '{a}'.", left, left.value); } } } function indentation(bias) { var i; if (option.white && nexttoken.id !== '(end)') { i = indent + (bias || 0); if (nexttoken.from !== i) { warning( "Expected '{a}' to have an indentation at {b} instead at {c}.", nexttoken, nexttoken.value, i, nexttoken.from); } } } function nolinebreak(t) { t = t || token; if (t.line !== nexttoken.line) { warning("Line breaking error '{a}'.", t, t.value); } } function comma() { if (token.line !== nexttoken.line) { if (!option.laxbreak) { warning("Bad line breaking before '{a}'.", token, nexttoken.id); } } else if (!token.comment && token.character !== nexttoken.from && option.white) { token.from += (token.character - token.from); warning("Unexpected space after '{a}'.", token, token.value); } advance(','); nonadjacent(token, nexttoken); } // Functional constructors for making the symbols that will be inherited by // tokens. function symbol(s, p) { var x = syntax[s]; if (!x || typeof x !== 'object') { syntax[s] = x = { id: s, lbp: p, value: s }; } return x; } function delim(s) { return symbol(s, 0); } function stmt(s, f) { var x = delim(s); x.identifier = x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; } function reserveName(x) { var c = x.id.charAt(0); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { x.identifier = x.reserved = true; } return x; } function prefix(s, f) { var x = symbol(s, 150); reserveName(x); x.nud = (typeof f === 'function') ? f : function () { this.right = expression(150); this.arity = 'unary'; if (this.id === '++' || this.id === '--') { if (option.plusplus) { warning("Unexpected use of '{a}'.", this, this.id); } else if ((!this.right.identifier || this.right.reserved) && this.right.id !== '.' && this.right.id !== '[') { warning("Bad operand.", this); } } return this; }; return x; } function type(s, f) { var x = delim(s); x.type = s; x.nud = f; return x; } function reserve(s, f) { var x = type(s, f); x.identifier = x.reserved = true; return x; } function reservevar(s, v) { return reserve(s, function () { if (typeof v === 'function') { v(this); } return this; }); } function infix(s, f, p, w) { var x = symbol(s, p); reserveName(x); x.led = function (left) { if (!w) { nobreaknonadjacent(prevtoken, token); nonadjacent(token, nexttoken); } if (s === "in" && left.id === "!") { warning("Confusing use of '{a}'.", left, '!'); } if (typeof f === 'function') { return f(left, this); } else { this.left = left; this.right = expression(p); return this; } }; return x; } function relation(s, f) { var x = symbol(s, 100); x.led = function (left) { nobreaknonadjacent(prevtoken, token); nonadjacent(token, nexttoken); var right = expression(100); if ((left && left.id === 'NaN') || (right && right.id === 'NaN')) { warning("Use the isNaN function to compare with NaN.", this); } else if (f) { f.apply(this, [left, right]); } if (left.id === '!') { warning("Confusing use of '{a}'.", left, '!'); } if (right.id === '!') { warning("Confusing use of '{a}'.", right, '!'); } this.left = left; this.right = right; return this; }; return x; } function isPoorRelation(node) { return node && ((node.type === '(number)' && +node.value === 0) || (node.type === '(string)' && node.value === '') || (node.type === 'null' && !option.eqnull) || node.type === 'true' || node.type === 'false' || node.type === 'undefined'); } function assignop(s, f) { symbol(s, 20).exps = true; return infix(s, function (left, that) { var l; that.left = left; if (predefined[left.value] === false && scope[left.value]['(global)'] === true) { warning("Read only.", left); } else if (left['function']) { warning("'{a}' is a function.", left, left.value); } if (left) { if (option.esnext && funct[left.value] === 'const') { warning("Attempting to override '{a}' which is a constant", left, left.value); } if (left.id === '.' || left.id === '[') { if (!left.left || left.left.value === 'arguments') { warning('Bad assignment.', that); } that.right = expression(19); return that; } else if (left.identifier && !left.reserved) { if (funct[left.value] === 'exception') { warning("Do not assign to the exception parameter.", left); } that.right = expression(19); return that; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment and instead saw a function invocation.", token); } } error("Bad assignment.", that); }, 20); } function bitwise(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === 'function') ? f : function (left) { if (option.bitwise) { warning("Unexpected use of '{a}'.", this, this.id); } this.left = left; this.right = expression(p); return this; }; return x; } function bitwiseassignop(s) { symbol(s, 20).exps = true; return infix(s, function (left, that) { if (option.bitwise) { warning("Unexpected use of '{a}'.", that, that.id); } nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); if (left) { if (left.id === '.' || left.id === '[' || (left.identifier && !left.reserved)) { expression(19); return that; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment, and instead saw a function invocation.", token); } return that; } error("Bad assignment.", that); }, 20); } function suffix(s, f) { var x = symbol(s, 150); x.led = function (left) { if (option.plusplus) { warning("Unexpected use of '{a}'.", this, this.id); } else if ((!left.identifier || left.reserved) && left.id !== '.' && left.id !== '[') { warning("Bad operand.", this); } this.left = left; return this; }; return x; } // fnparam means that this identifier is being defined as a function // argument (see identifier()) function optionalidentifier(fnparam) { if (nexttoken.identifier) { advance(); if (token.reserved && !option.es5) { // `undefined` as a function param is a common pattern to protect // against the case when somebody does `undefined = true` and // help with minification. More info: https://gist.github.com/315916 if (!fnparam || token.value !== 'undefined') { warning("Expected an identifier and instead saw '{a}' (a reserved word).", token, token.id); } } return token.value; } } // fnparam means that this identifier is being defined as a function // argument function identifier(fnparam) { var i = optionalidentifier(fnparam); if (i) { return i; } if (token.id === 'function' && nexttoken.id === '(') { warning("Missing name in function declaration."); } else { error("Expected an identifier and instead saw '{a}'.", nexttoken, nexttoken.value); } } function reachable(s) { var i = 0, t; if (nexttoken.id !== ';' || noreach) { return; } for (;;) { t = peek(i); if (t.reach) { return; } if (t.id !== '(endline)') { if (t.id === 'function') { if (!option.latedef) { break; } warning( "Inner functions should be listed at the top of the outer function.", t); break; } warning("Unreachable '{a}' after '{b}'.", t, t.value, s); break; } i += 1; } } function statement(noindent) { var i = indent, r, s = scope, t = nexttoken; if (t.id === ";") { advance(";"); return; } // Is this a labelled statement? if (t.identifier && !t.reserved && peek().id === ':') { advance(); advance(':'); scope = Object.create(s); addlabel(t.value, 'label'); if (!nexttoken.labelled) { warning("Label '{a}' on {b} statement.", nexttoken, t.value, nexttoken.value); } if (jx.test(t.value + ':')) { warning("Label '{a}' looks like a javascript url.", t, t.value); } nexttoken.label = t.value; t = nexttoken; } // Parse the statement. if (!noindent) { indentation(); } r = expression(0, true); // Look for the final semicolon. if (!t.block) { if (!option.expr && (!r || !r.exps)) { warning("Expected an assignment or function call and instead saw an expression.", token); } else if (option.nonew && r.id === '(' && r.left.id === 'new') { warning("Do not use 'new' for side effects."); } if (nexttoken.id !== ';') { if (!option.asi) { // If this is the last statement in a block that ends on // the same line *and* option lastsemic is on, ignore the warning. // Otherwise, complain about missing semicolon. if (!option.lastsemic || nexttoken.id !== '}' || nexttoken.line !== token.line) { warningAt("Missing semicolon.", token.line, token.character); } } } else { adjacent(token, nexttoken); advance(';'); nonadjacent(token, nexttoken); } } // Restore the indentation. indent = i; scope = s; return r; } function statements(startLine) { var a = [], f, p; while (!nexttoken.reach && nexttoken.id !== '(end)') { if (nexttoken.id === ';') { p = peek(); if (!p || p.id !== "(") { warning("Unnecessary semicolon."); } advance(';'); } else { a.push(statement(startLine === nexttoken.line)); } } return a; } /* * read all directives * recognizes a simple form of asi, but always * warns, if it is used */ function directives() { var i, p, pn; for (;;) { if (nexttoken.id === "(string)") { p = peek(0); if (p.id === "(endline)") { i = 1; do { pn = peek(i); i = i + 1; } while (pn.id === "(endline)"); if (pn.id !== ";") { if (pn.id !== "(string)" && pn.id !== "(number)" && pn.id !== "(regexp)" && pn.identifier !== true && pn.id !== "}") { break; } warning("Missing semicolon.", nexttoken); } else { p = pn; } } else if (p.id === "}") { // directive with no other statements, warn about missing semicolon warning("Missing semicolon.", p); } else if (p.id !== ";") { break; } indentation(); advance(); if (directive[token.value]) { warning("Unnecessary directive \"{a}\".", token, token.value); } if (token.value === "use strict") { option.newcap = true; option.undef = true; } // there's no directive negation, so always set to true directive[token.value] = true; if (p.id === ";") { advance(";"); } continue; } break; } } /* * Parses a single block. A block is a sequence of statements wrapped in * braces. * * ordinary - true for everything but function bodies and try blocks. * stmt - true if block can be a single statement (e.g. in if/for/while). * isfunc - true if block is a function body */ function block(ordinary, stmt, isfunc) { var a, b = inblock, old_indent = indent, m, s = scope, t, line, d; inblock = ordinary; if (!ordinary || !option.funcscope) scope = Object.create(scope); nonadjacent(token, nexttoken); t = nexttoken; if (nexttoken.id === '{') { advance('{'); line = token.line; if (nexttoken.id !== '}') { indent += option.indent; while (!ordinary && nexttoken.from > indent) { indent += option.indent; } if (isfunc) { m = {}; for (d in directive) { if (is_own(directive, d)) { m[d] = directive[d]; } } directives(); if (option.strict && funct['(context)']['(global)']) { if (!m["use strict"] && !directive["use strict"]) { warning("Missing \"use strict\" statement."); } } } a = statements(line); if (isfunc) { directive = m; } indent -= option.indent; if (line !== nexttoken.line) { indentation(); } } else if (line !== nexttoken.line) { indentation(); } advance('}', t); indent = old_indent; } else if (!ordinary) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, '{', nexttoken.value); } else { if (!stmt || option.curly) warning("Expected '{a}' and instead saw '{b}'.", nexttoken, '{', nexttoken.value); noreach = true; indent += option.indent; // test indentation only if statement is in new line a = [statement(nexttoken.line === token.line)]; indent -= option.indent; noreach = false; } funct['(verb)'] = null; if (!ordinary || !option.funcscope) scope = s; inblock = b; if (ordinary && option.noempty && (!a || a.length === 0)) { warning("Empty block."); } return a; } function countMember(m) { if (membersOnly && typeof membersOnly[m] !== 'boolean') { warning("Unexpected /*member '{a}'.", token, m); } if (typeof member[m] === 'number') { member[m] += 1; } else { member[m] = 1; } } function note_implied(token) { var name = token.value, line = token.line, a = implied[name]; if (typeof a === 'function') { a = false; } if (!a) { a = [line]; implied[name] = a; } else if (a[a.length - 1] !== line) { a.push(line); } } // Build the syntax table by declaring the syntactic elements of the language. type('(number)', function () { return this; }); type('(string)', function () { return this; }); syntax['(identifier)'] = { type: '(identifier)', lbp: 0, identifier: true, nud: function () { var v = this.value, s = scope[v], f; if (typeof s === 'function') { // Protection against accidental inheritance. s = undefined; } else if (typeof s === 'boolean') { f = funct; funct = functions[0]; addlabel(v, 'var'); s = funct; funct = f; } // The name is in scope and defined in the current function. if (funct === s) { // Change 'unused' to 'var', and reject labels. switch (funct[v]) { case 'unused': funct[v] = 'var'; break; case 'unction': funct[v] = 'function'; this['function'] = true; break; case 'function': this['function'] = true; break; case 'label': warning("'{a}' is a statement label.", token, v); break; } } else if (funct['(global)']) { // The name is not defined in the function. If we are in the global // scope, then we have an undefined variable. // // Operators typeof and delete do not raise runtime errors even if // the base object of a reference is null so no need to display warning // if we're inside of typeof or delete. if (option.undef && typeof predefined[v] !== 'boolean') { // Attempting to subscript a null reference will throw an // error, even within the typeof and delete operators if (!(anonname === 'typeof' || anonname === 'delete') || (nexttoken && (nexttoken.value === '.' || nexttoken.value === '['))) { isundef(funct, "'{a}' is not defined.", token, v); } } note_implied(token); } else { // If the name is already defined in the current // function, but not as outer, then there is a scope error. switch (funct[v]) { case 'closure': case 'function': case 'var': case 'unused': warning("'{a}' used out of scope.", token, v); break; case 'label': warning("'{a}' is a statement label.", token, v); break; case 'outer': case 'global': break; default: // If the name is defined in an outer function, make an outer entry, // and if it was unused, make it var. if (s === true) { funct[v] = true; } else if (s === null) { warning("'{a}' is not allowed.", token, v); note_implied(token); } else if (typeof s !== 'object') { // Operators typeof and delete do not raise runtime errors even // if the base object of a reference is null so no need to // display warning if we're inside of typeof or delete. if (option.undef) { // Attempting to subscript a null reference will throw an // error, even within the typeof and delete operators if (!(anonname === 'typeof' || anonname === 'delete') || (nexttoken && (nexttoken.value === '.' || nexttoken.value === '['))) { isundef(funct, "'{a}' is not defined.", token, v); } } funct[v] = true; note_implied(token); } else { switch (s[v]) { case 'function': case 'unction': this['function'] = true; s[v] = 'closure'; funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'var': case 'unused': s[v] = 'closure'; funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'closure': case 'parameter': funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'label': warning("'{a}' is a statement label.", token, v); } } } } return this; }, led: function () { error("Expected an operator and instead saw '{a}'.", nexttoken, nexttoken.value); } }; type('(regexp)', function () { return this; }); // ECMAScript parser delim('(endline)'); delim('(begin)'); delim('(end)').reach = true; delim('</').reach = true; delim('<!'); delim('<!--'); delim('-->'); delim('(error)').reach = true; delim('}').reach = true; delim(')'); delim(']'); delim('"').reach = true; delim("'").reach = true; delim(';'); delim(':').reach = true; delim(','); delim('#'); delim('@'); reserve('else'); reserve('case').reach = true; reserve('catch'); reserve('default').reach = true; reserve('finally'); reservevar('arguments', function (x) { if (directive['use strict'] && funct['(global)']) { warning("Strict violation.", x); } }); reservevar('eval'); reservevar('false'); reservevar('Infinity'); reservevar('NaN'); reservevar('null'); reservevar('this', function (x) { if (directive['use strict'] && !option.validthis && ((funct['(statement)'] && funct['(name)'].charAt(0) > 'Z') || funct['(global)'])) { warning("Possible strict violation.", x); } }); reservevar('true'); reservevar('undefined'); assignop('=', 'assign', 20); assignop('+=', 'assignadd', 20); assignop('-=', 'assignsub', 20); assignop('*=', 'assignmult', 20); assignop('/=', 'assigndiv', 20).nud = function () { error("A regular expression literal can be confused with '/='."); }; assignop('%=', 'assignmod', 20); bitwiseassignop('&=', 'assignbitand', 20); bitwiseassignop('|=', 'assignbitor', 20); bitwiseassignop('^=', 'assignbitxor', 20); bitwiseassignop('<<=', 'assignshiftleft', 20); bitwiseassignop('>>=', 'assignshiftright', 20); bitwiseassignop('>>>=', 'assignshiftrightunsigned', 20); infix('?', function (left, that) { that.left = left; that.right = expression(10); advance(':'); that['else'] = expression(10); return that; }, 30); infix('||', 'or', 40); infix('&&', 'and', 50); bitwise('|', 'bitor', 70); bitwise('^', 'bitxor', 80); bitwise('&', 'bitand', 90); relation('==', function (left, right) { var eqnull = option.eqnull && (left.value === 'null' || right.value === 'null'); if (!eqnull && option.eqeqeq) warning("Expected '{a}' and instead saw '{b}'.", this, '===', '=='); else if (isPoorRelation(left)) warning("Use '{a}' to compare with '{b}'.", this, '===', left.value); else if (isPoorRelation(right)) warning("Use '{a}' to compare with '{b}'.", this, '===', right.value); return this; }); relation('==='); relation('!=', function (left, right) { var eqnull = option.eqnull && (left.value === 'null' || right.value === 'null'); if (!eqnull && option.eqeqeq) { warning("Expected '{a}' and instead saw '{b}'.", this, '!==', '!='); } else if (isPoorRelation(left)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', left.value); } else if (isPoorRelation(right)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', right.value); } return this; }); relation('!=='); relation('<'); relation('>'); relation('<='); relation('>='); bitwise('<<', 'shiftleft', 120); bitwise('>>', 'shiftright', 120); bitwise('>>>', 'shiftrightunsigned', 120); infix('in', 'in', 120); infix('instanceof', 'instanceof', 120); infix('+', function (left, that) { var right = expression(130); if (left && right && left.id === '(string)' && right.id === '(string)') { left.value += right.value; left.character = right.character; if (!option.scripturl && jx.test(left.value)) { warning("JavaScript URL.", left); } return left; } that.left = left; that.right = right; return that; }, 130); prefix('+', 'num'); prefix('+++', function () { warning("Confusing pluses."); this.right = expression(150); this.arity = 'unary'; return this; }); infix('+++', function (left) { warning("Confusing pluses."); this.left = left; this.right = expression(130); return this; }, 130); infix('-', 'sub', 130); prefix('-', 'neg'); prefix('---', function () { warning("Confusing minuses."); this.right = expression(150); this.arity = 'unary'; return this; }); infix('---', function (left) { warning("Confusing minuses."); this.left = left; this.right = expression(130); return this; }, 130); infix('*', 'mult', 140); infix('/', 'div', 140); infix('%', 'mod', 140); suffix('++', 'postinc'); prefix('++', 'preinc'); syntax['++'].exps = true; suffix('--', 'postdec'); prefix('--', 'predec'); syntax['--'].exps = true; prefix('delete', function () { var p = expression(0); if (!p || (p.id !== '.' && p.id !== '[')) { warning("Variables should not be deleted."); } this.first = p; return this; }).exps = true; prefix('~', function () { if (option.bitwise) { warning("Unexpected '{a}'.", this, '~'); } expression(150); return this; }); prefix('!', function () { this.right = expression(150); this.arity = 'unary'; if (bang[this.right.id] === true) { warning("Confusing use of '{a}'.", this, '!'); } return this; }); prefix('typeof', 'typeof'); prefix('new', function () { var c = expression(155), i; if (c && c.id !== 'function') { if (c.identifier) { c['new'] = true; switch (c.value) { case 'Object': warning("Use the object literal notation {}.", token); break; case 'Number': case 'String': case 'Boolean': case 'Math': case 'JSON': warning("Do not use {a} as a constructor.", token, c.value); break; case 'Function': if (!option.evil) { warning("The Function constructor is eval."); } break; case 'Date': case 'RegExp': break; default: if (c.id !== 'function') { i = c.value.substr(0, 1); if (option.newcap && (i < 'A' || i > 'Z')) { warning("A constructor name should start with an uppercase letter.", token); } } } } else { if (c.id !== '.' && c.id !== '[' && c.id !== '(') { warning("Bad constructor.", token); } } } else { if (!option.supernew) warning("Weird construction. Delete 'new'.", this); } adjacent(token, nexttoken); if (nexttoken.id !== '(' && !option.supernew) { warning("Missing '()' invoking a constructor."); } this.first = c; return this; }); syntax['new'].exps = true; prefix('void').exps = true; infix('.', function (left, that) { adjacent(prevtoken, token); nobreak(); var m = identifier(); if (typeof m === 'string') { countMember(m); } that.left = left; that.right = m; if (left && left.value === 'arguments' && (m === 'callee' || m === 'caller')) { if (option.noarg) warning("Avoid arguments.{a}.", left, m); else if (directive['use strict']) error('Strict violation.'); } else if (!option.evil && left && left.value === 'document' && (m === 'write' || m === 'writeln')) { warning("document.write can be a form of eval.", left); } if (!option.evil && (m === 'eval' || m === 'execScript')) { warning('eval is evil.'); } return that; }, 160, true); infix('(', function (left, that) { if (prevtoken.id !== '}' && prevtoken.id !== ')') { nobreak(prevtoken, token); } nospace(); if (option.immed && !left.immed && left.id === 'function') { warning("Wrap an immediate function invocation in parentheses " + "to assist the reader in understanding that the expression " + "is the result of a function, and not the function itself."); } var n = 0, p = []; if (left) { if (left.type === '(identifier)') { if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if (left.value !== 'Number' && left.value !== 'String' && left.value !== 'Boolean' && left.value !== 'Date') { if (left.value === 'Math') { warning("Math is not a function.", left); } else if (option.newcap) { warning( "Missing 'new' prefix when invoking a constructor.", left); } } } } } if (nexttoken.id !== ')') { for (;;) { p[p.length] = expression(10); n += 1; if (nexttoken.id !== ',') { break; } comma(); } } advance(')'); nospace(prevtoken, token); if (typeof left === 'object') { if (left.value === 'parseInt' && n === 1) { warning("Missing radix parameter.", left); } if (!option.evil) { if (left.value === 'eval' || left.value === 'Function' || left.value === 'execScript') { warning("eval is evil.", left); } else if (p[0] && p[0].id === '(string)' && (left.value === 'setTimeout' || left.value === 'setInterval')) { warning( "Implied eval is evil. Pass a function instead of a string.", left); } } if (!left.identifier && left.id !== '.' && left.id !== '[' && left.id !== '(' && left.id !== '&&' && left.id !== '||' && left.id !== '?') { warning("Bad invocation.", left); } } that.left = left; return that; }, 155, true).exps = true; prefix('(', function () { nospace(); if (nexttoken.id === 'function') { nexttoken.immed = true; } var v = expression(0); advance(')', this); nospace(prevtoken, token); if (option.immed && v.id === 'function') { if (nexttoken.id === '(') { warning( "Move the invocation into the parens that contain the function.", nexttoken); } else { warning( "Do not wrap function literals in parens unless they are to be immediately invoked.", this); } } return v; }); infix('[', function (left, that) { nobreak(prevtoken, token); nospace(); var e = expression(0), s; if (e && e.type === '(string)') { if (!option.evil && (e.value === 'eval' || e.value === 'execScript')) { warning("eval is evil.", that); } countMember(e.value); if (!option.sub && ix.test(e.value)) { s = syntax[e.value]; if (!s || !s.reserved) { warning("['{a}'] is better written in dot notation.", e, e.value); } } } advance(']', that); nospace(prevtoken, token); that.left = left; that.right = e; return that; }, 160, true); prefix('[', function () { var b = token.line !== nexttoken.line; this.first = []; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } while (nexttoken.id !== '(end)') { while (nexttoken.id === ',') { warning("Extra comma."); advance(','); } if (nexttoken.id === ']') { break; } if (b && token.line !== nexttoken.line) { indentation(); } this.first.push(expression(10)); if (nexttoken.id === ',') { comma(); if (nexttoken.id === ']' && !option.es5) { warning("Extra comma.", token); break; } } else { break; } } if (b) { indent -= option.indent; indentation(); } advance(']', this); return this; }, 160); function property_name() { var id = optionalidentifier(true); if (!id) { if (nexttoken.id === '(string)') { id = nexttoken.value; advance(); } else if (nexttoken.id === '(number)') { id = nexttoken.value.toString(); advance(); } } return id; } function functionparams() { var i, t = nexttoken, p = []; advance('('); nospace(); if (nexttoken.id === ')') { advance(')'); return; } for (;;) { i = identifier(true); p.push(i); addlabel(i, 'parameter'); if (nexttoken.id === ',') { comma(); } else { advance(')', t); nospace(prevtoken, token); return p; } } } function doFunction(i, statement) { var f, oldOption = option, oldScope = scope; option = Object.create(option); scope = Object.create(scope); funct = { '(name)' : i || '"' + anonname + '"', '(line)' : nexttoken.line, '(context)' : funct, '(breakage)' : 0, '(loopage)' : 0, '(scope)' : scope, '(statement)': statement }; f = funct; token.funct = funct; functions.push(funct); if (i) { addlabel(i, 'function'); } funct['(params)'] = functionparams(); block(false, false, true); scope = oldScope; option = oldOption; funct['(last)'] = token.line; funct = funct['(context)']; return f; } (function (x) { x.nud = function () { var b, f, i, j, p, t; var props = {}; // All properties, including accessors function saveProperty(name, token) { if (props[name] && is_own(props, name)) warning("Duplicate member '{a}'.", nexttoken, i); else props[name] = {}; props[name].basic = true; props[name].basicToken = token; } function saveSetter(name, token) { if (props[name] && is_own(props, name)) { if (props[name].basic || props[name].setter) warning("Duplicate member '{a}'.", nexttoken, i); } else { props[name] = {}; } props[name].setter = true; props[name].setterToken = token; } function saveGetter(name) { if (props[name] && is_own(props, name)) { if (props[name].basic || props[name].getter) warning("Duplicate member '{a}'.", nexttoken, i); } else { props[name] = {}; } props[name].getter = true; props[name].getterToken = token; } b = token.line !== nexttoken.line; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } for (;;) { if (nexttoken.id === '}') { break; } if (b) { indentation(); } if (nexttoken.value === 'get' && peek().id !== ':') { advance('get'); if (!option.es5) { error("get/set are ES5 features."); } i = property_name(); if (!i) { error("Missing property name."); } saveGetter(i); t = nexttoken; adjacent(token, nexttoken); f = doFunction(); p = f['(params)']; if (p) { warning("Unexpected parameter '{a}' in get {b} function.", t, p[0], i); } adjacent(token, nexttoken); } else if (nexttoken.value === 'set' && peek().id !== ':') { advance('set'); if (!option.es5) { error("get/set are ES5 features."); } i = property_name(); if (!i) { error("Missing property name."); } saveSetter(i, nexttoken); t = nexttoken; adjacent(token, nexttoken); f = doFunction(); p = f['(params)']; if (!p || p.length !== 1) { warning("Expected a single parameter in set {a} function.", t, i); } } else { i = property_name(); saveProperty(i, nexttoken); if (typeof i !== 'string') { break; } advance(':'); nonadjacent(token, nexttoken); expression(10); } countMember(i); if (nexttoken.id === ',') { comma(); if (nexttoken.id === ',') { warning("Extra comma.", token); } else if (nexttoken.id === '}' && !option.es5) { warning("Extra comma.", token); } } else { break; } } if (b) { indent -= option.indent; indentation(); } advance('}', this); // Check for lonely setters if in the ES5 mode. if (option.es5) { for (var name in props) { if (is_own(props, name) && props[name].setter && !props[name].getter) { warning("Setter is defined without getter.", props[name].setterToken); } } } return this; }; x.fud = function () { error("Expected to see a statement and instead saw a block.", token); }; }(delim('{'))); // This Function is called when esnext option is set to true // it adds the `const` statement to JSHINT useESNextSyntax = function () { var conststatement = stmt('const', function (prefix) { var id, name, value; this.first = []; for (;;) { nonadjacent(token, nexttoken); id = identifier(); if (funct[id] === "const") { warning("const '" + id + "' has already been declared"); } if (funct['(global)'] && predefined[id] === false) { warning("Redefinition of '{a}'.", token, id); } addlabel(id, 'const'); if (prefix) { break; } name = token; this.first.push(token); if (nexttoken.id !== "=") { warning("const " + "'{a}' is initialized to 'undefined'.", token, id); } if (nexttoken.id === '=') { nonadjacent(token, nexttoken); advance('='); nonadjacent(token, nexttoken); if (nexttoken.id === 'undefined') { warning("It is not necessary to initialize " + "'{a}' to 'undefined'.", token, id); } if (peek(0).id === '=' && nexttoken.identifier) { error("Constant {a} was not declared correctly.", nexttoken, nexttoken.value); } value = expression(0); name.first = value; } if (nexttoken.id !== ',') { break; } comma(); } return this; }); conststatement.exps = true; }; var varstatement = stmt('var', function (prefix) { // JavaScript does not have block scope. It only has function scope. So, // declaring a variable in a block can have unexpected consequences. var id, name, value; if (funct['(onevar)'] && option.onevar) { warning("Too many var statements."); } else if (!funct['(global)']) { funct['(onevar)'] = true; } this.first = []; for (;;) { nonadjacent(token, nexttoken); id = identifier(); if (option.esnext && funct[id] === "const") { warning("const '" + id + "' has already been declared"); } if (funct['(global)'] && predefined[id] === false) { warning("Redefinition of '{a}'.", token, id); } addlabel(id, 'unused'); if (prefix) { break; } name = token; this.first.push(token); if (nexttoken.id === '=') { nonadjacent(token, nexttoken); advance('='); nonadjacent(token, nexttoken); if (nexttoken.id === 'undefined') { warning("It is not necessary to initialize '{a}' to 'undefined'.", token, id); } if (peek(0).id === '=' && nexttoken.identifier) { error("Variable {a} was not declared correctly.", nexttoken, nexttoken.value); } value = expression(0); name.first = value; } if (nexttoken.id !== ',') { break; } comma(); } return this; }); varstatement.exps = true; blockstmt('function', function () { if (inblock) { warning("Function declarations should not be placed in blocks. " + "Use a function expression or move the statement to the top of " + "the outer function.", token); } var i = identifier(); if (option.esnext && funct[i] === "const") { warning("const '" + i + "' has already been declared"); } adjacent(token, nexttoken); addlabel(i, 'unction'); doFunction(i, true); if (nexttoken.id === '(' && nexttoken.line === token.line) { error( "Function declarations are not invocable. Wrap the whole function invocation in parens."); } return this; }); prefix('function', function () { var i = optionalidentifier(); if (i) { adjacent(token, nexttoken); } else { nonadjacent(token, nexttoken); } doFunction(i); if (!option.loopfunc && funct['(loopage)']) { warning("Don't make functions within a loop."); } return this; }); blockstmt('if', function () { var t = nexttoken; advance('('); nonadjacent(this, t); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); block(true, true); if (nexttoken.id === 'else') { nonadjacent(token, nexttoken); advance('else'); if (nexttoken.id === 'if' || nexttoken.id === 'switch') { statement(true); } else { block(true, true); } } return this; }); blockstmt('try', function () { var b, e, s; block(false); if (nexttoken.id === 'catch') { advance('catch'); nonadjacent(token, nexttoken); advance('('); s = scope; scope = Object.create(s); e = nexttoken.value; if (nexttoken.type !== '(identifier)') { warning("Expected an identifier and instead saw '{a}'.", nexttoken, e); } else { addlabel(e, 'exception'); } advance(); advance(')'); block(false); b = true; scope = s; } if (nexttoken.id === 'finally') { advance('finally'); block(false); return; } else if (!b) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'catch', nexttoken.value); } return this; }); blockstmt('while', function () { var t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); block(true, true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; }).labelled = true; reserve('with'); blockstmt('switch', function () { var t = nexttoken, g = false; funct['(breakage)'] += 1; advance('('); nonadjacent(this, t); nospace(); this.condition = expression(20); advance(')', t); nospace(prevtoken, token); nonadjacent(token, nexttoken); t = nexttoken; advance('{'); nonadjacent(token, nexttoken); indent += option.indent; this.cases = []; for (;;) { switch (nexttoken.id) { case 'case': switch (funct['(verb)']) { case 'break': case 'case': case 'continue': case 'return': case 'switch': case 'throw': break; default: // You can tell JSHint that you don't use break intentionally by // adding a comment /* falls through */ on a line just before // the next `case`. if (!ft.test(lines[nexttoken.line - 2])) { warning( "Expected a 'break' statement before 'case'.", token); } } indentation(-option.indent); advance('case'); this.cases.push(expression(20)); g = true; advance(':'); funct['(verb)'] = 'case'; break; case 'default': switch (funct['(verb)']) { case 'break': case 'continue': case 'return': case 'throw': break; default: if (!ft.test(lines[nexttoken.line - 2])) { warning( "Expected a 'break' statement before 'default'.", token); } } indentation(-option.indent); advance('default'); g = true; advance(':'); break; case '}': indent -= option.indent; indentation(); advance('}', t); if (this.cases.length === 1 || this.condition.id === 'true' || this.condition.id === 'false') { if (!option.onecase) warning("This 'switch' should be an 'if'.", this); } funct['(breakage)'] -= 1; funct['(verb)'] = undefined; return; case '(end)': error("Missing '{a}'.", nexttoken, '}'); return; default: if (g) { switch (token.id) { case ',': error("Each value should have its own case label."); return; case ':': g = false; statements(); break; default: error("Missing ':' on a case clause.", token); return; } } else { if (token.id === ':') { advance(':'); error("Unexpected '{a}'.", token, ':'); statements(); } else { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'case', nexttoken.value); return; } } } } }).labelled = true; stmt('debugger', function () { if (!option.debug) { warning("All 'debugger' statements should be removed."); } return this; }).exps = true; (function () { var x = stmt('do', function () { funct['(breakage)'] += 1; funct['(loopage)'] += 1; this.first = block(true); advance('while'); var t = nexttoken; nonadjacent(token, t); advance('('); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; }); x.labelled = true; x.exps = true; }()); blockstmt('for', function () { var s, t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); if (peek(nexttoken.id === 'var' ? 1 : 0).id === 'in') { if (nexttoken.id === 'var') { advance('var'); varstatement.fud.call(varstatement, true); } else { switch (funct[nexttoken.value]) { case 'unused': funct[nexttoken.value] = 'var'; break; case 'var': break; default: warning("Bad for in variable '{a}'.", nexttoken, nexttoken.value); } advance(); } advance('in'); expression(20); advance(')', t); s = block(true, true); if (option.forin && s && (s.length > 1 || typeof s[0] !== 'object' || s[0].value !== 'if')) { warning("The body of a for in should be wrapped in an if statement to filter " + "unwanted properties from the prototype.", this); } funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; } else { if (nexttoken.id !== ';') { if (nexttoken.id === 'var') { advance('var'); varstatement.fud.call(varstatement); } else { for (;;) { expression(0, 'for'); if (nexttoken.id !== ',') { break; } comma(); } } } nolinebreak(token); advance(';'); if (nexttoken.id !== ';') { expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } } nolinebreak(token); advance(';'); if (nexttoken.id === ';') { error("Expected '{a}' and instead saw '{b}'.", nexttoken, ')', ';'); } if (nexttoken.id !== ')') { for (;;) { expression(0, 'for'); if (nexttoken.id !== ',') { break; } comma(); } } advance(')', t); nospace(prevtoken, token); block(true, true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; } }).labelled = true; stmt('break', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) warning("Unexpected '{a}'.", nexttoken, this.value); if (!option.asi) nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } this.first = nexttoken; advance(); } } reachable('break'); return this; }).exps = true; stmt('continue', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) warning("Unexpected '{a}'.", nexttoken, this.value); if (!option.asi) nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } this.first = nexttoken; advance(); } } else if (!funct['(loopage)']) { warning("Unexpected '{a}'.", nexttoken, this.value); } reachable('continue'); return this; }).exps = true; stmt('return', function () { if (this.line === nexttoken.line) { if (nexttoken.id === '(regexp)') warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator."); if (nexttoken.id !== ';' && !nexttoken.reach) { nonadjacent(token, nexttoken); if (peek().value === "=" && !option.boss) { warningAt("Did you mean to return a conditional instead of an assignment?", token.line, token.character + 1); } this.first = expression(0); } } else if (!option.asi) { nolinebreak(this); // always warn (Line breaking error) } reachable('return'); return this; }).exps = true; stmt('throw', function () { nolinebreak(this); nonadjacent(token, nexttoken); this.first = expression(20); reachable('throw'); return this; }).exps = true; // Superfluous reserved words reserve('class'); reserve('const'); reserve('enum'); reserve('export'); reserve('extends'); reserve('import'); reserve('super'); reserve('let'); reserve('yield'); reserve('implements'); reserve('interface'); reserve('package'); reserve('private'); reserve('protected'); reserve('public'); reserve('static'); // Parse JSON function jsonValue() { function jsonObject() { var o = {}, t = nexttoken; advance('{'); if (nexttoken.id !== '}') { for (;;) { if (nexttoken.id === '(end)') { error("Missing '}' to match '{' from line {a}.", nexttoken, t.line); } else if (nexttoken.id === '}') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } else if (nexttoken.id !== '(string)') { warning("Expected a string and instead saw {a}.", nexttoken, nexttoken.value); } if (o[nexttoken.value] === true) { warning("Duplicate key '{a}'.", nexttoken, nexttoken.value); } else if ((nexttoken.value === '__proto__' && !option.proto) || (nexttoken.value === '__iterator__' && !option.iterator)) { warning("The '{a}' key may produce unexpected results.", nexttoken, nexttoken.value); } else { o[nexttoken.value] = true; } advance(); advance(':'); jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance('}'); } function jsonArray() { var t = nexttoken; advance('['); if (nexttoken.id !== ']') { for (;;) { if (nexttoken.id === '(end)') { error("Missing ']' to match '[' from line {a}.", nexttoken, t.line); } else if (nexttoken.id === ']') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance(']'); } switch (nexttoken.id) { case '{': jsonObject(); break; case '[': jsonArray(); break; case 'true': case 'false': case 'null': case '(number)': case '(string)': advance(); break; case '-': advance('-'); if (token.character !== nexttoken.from) { warning("Unexpected space after '-'.", token); } adjacent(token, nexttoken); advance('(number)'); break; default: error("Expected a JSON value.", nexttoken); } } // The actual JSHINT function itself. var itself = function (s, o, g) { var a, i, k; JSHINT.errors = []; JSHINT.undefs = []; predefined = Object.create(standard); combine(predefined, g || {}); if (o) { a = o.predef; if (a) { if (Array.isArray(a)) { for (i = 0; i < a.length; i += 1) { predefined[a[i]] = true; } } else if (typeof a === 'object') { k = Object.keys(a); for (i = 0; i < k.length; i += 1) { predefined[k[i]] = !!a[k[i]]; } } } option = o; } else { option = {}; } option.indent = option.indent || 4; option.maxerr = option.maxerr || 50; tab = ''; for (i = 0; i < option.indent; i += 1) { tab += ' '; } indent = 1; global = Object.create(predefined); scope = global; funct = { '(global)': true, '(name)': '(global)', '(scope)': scope, '(breakage)': 0, '(loopage)': 0 }; functions = [funct]; urls = []; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; jsonmode = false; warnings = 0; lex.init(s); prereg = true; directive = {}; prevtoken = token = nexttoken = syntax['(begin)']; assume(); // combine the passed globals after we've assumed all our options combine(predefined, g || {}); try { advance(); switch (nexttoken.id) { case '{': case '[': option.laxbreak = true; jsonmode = true; jsonValue(); break; default: directives(); if (directive["use strict"] && !option.globalstrict) { warning("Use the function form of \"use strict\".", prevtoken); } statements(); } advance('(end)'); // Check queued 'x is not defined' instances to see if they're still undefined. for (i = 0; i < JSHINT.undefs.length; i += 1) { k = JSHINT.undefs[i].slice(0); scope = k.shift(); a = k[2]; if (typeof scope[a] !== 'string' && typeof funct[a] !== 'string') { warning.apply(warning, k); } } } catch (e) { if (e) { var nt = nexttoken || {}; JSHINT.errors.push({ raw : e.raw, reason : e.message, line : e.line || nt.line, character : e.character || nt.from }, null); } } return JSHINT.errors.length === 0; }; // Data summary. itself.data = function () { var data = { functions: [], options: option }, fu, globals, implieds = [], f, i, j, members = [], n, unused = [], v; if (itself.errors.length) { data.errors = itself.errors; } if (jsonmode) { data.json = true; } for (n in implied) { if (is_own(implied, n)) { implieds.push({ name: n, line: implied[n] }); } } if (implieds.length > 0) { data.implieds = implieds; } if (urls.length > 0) { data.urls = urls; } globals = Object.keys(scope); if (globals.length > 0) { data.globals = globals; } for (i = 1; i < functions.length; i += 1) { f = functions[i]; fu = {}; for (j = 0; j < functionicity.length; j += 1) { fu[functionicity[j]] = []; } for (n in f) { if (is_own(f, n) && n.charAt(0) !== '(') { v = f[n]; if (v === 'unction') { v = 'unused'; } if (Array.isArray(fu[v])) { fu[v].push(n); if (v === 'unused') { unused.push({ name: n, line: f['(line)'], 'function': f['(name)'] }); } } } } for (j = 0; j < functionicity.length; j += 1) { if (fu[functionicity[j]].length === 0) { delete fu[functionicity[j]]; } } fu.name = f['(name)']; fu.param = f['(params)']; fu.line = f['(line)']; fu.last = f['(last)']; data.functions.push(fu); } if (unused.length > 0) { data.unused = unused; } members = []; for (n in member) { if (typeof member[n] === 'number') { data.member = member; break; } } return data; }; itself.report = function (option) { var data = itself.data(); var a = [], c, e, err, f, i, k, l, m = '', n, o = [], s; function detail(h, array) { var b, i, singularity; if (array) { o.push('<div><i>' + h + '</i> '); array = array.sort(); for (i = 0; i < array.length; i += 1) { if (array[i] !== singularity) { singularity = array[i]; o.push((b ? ', ' : '') + singularity); b = true; } } o.push('</div>'); } } if (data.errors || data.implieds || data.unused) { err = true; o.push('<div id=errors><i>Error:</i>'); if (data.errors) { for (i = 0; i < data.errors.length; i += 1) { c = data.errors[i]; if (c) { e = c.evidence || ''; o.push('<p>Problem' + (isFinite(c.line) ? ' at line ' + c.line + ' character ' + c.character : '') + ': ' + c.reason.entityify() + '</p><p class=evidence>' + (e && (e.length > 80 ? e.slice(0, 77) + '...' : e).entityify()) + '</p>'); } } } if (data.implieds) { s = []; for (i = 0; i < data.implieds.length; i += 1) { s[i] = '<code>' + data.implieds[i].name + '</code>&nbsp;<i>' + data.implieds[i].line + '</i>'; } o.push('<p><i>Implied global:</i> ' + s.join(', ') + '</p>'); } if (data.unused) { s = []; for (i = 0; i < data.unused.length; i += 1) { s[i] = '<code><u>' + data.unused[i].name + '</u></code>&nbsp;<i>' + data.unused[i].line + '</i> <code>' + data.unused[i]['function'] + '</code>'; } o.push('<p><i>Unused variable:</i> ' + s.join(', ') + '</p>'); } if (data.json) { o.push('<p>JSON: bad.</p>'); } o.push('</div>'); } if (!option) { o.push('<br><div id=functions>'); if (data.urls) { detail("URLs<br>", data.urls, '<br>'); } if (data.json && !err) { o.push('<p>JSON: good.</p>'); } else if (data.globals) { o.push('<div><i>Global</i> ' + data.globals.sort().join(', ') + '</div>'); } else { o.push('<div><i>No new global variables introduced.</i></div>'); } for (i = 0; i < data.functions.length; i += 1) { f = data.functions[i]; o.push('<br><div class=function><i>' + f.line + '-' + f.last + '</i> ' + (f.name || '') + '(' + (f.param ? f.param.join(', ') : '') + ')</div>'); detail('<big><b>Unused</b></big>', f.unused); detail('Closure', f.closure); detail('Variable', f['var']); detail('Exception', f.exception); detail('Outer', f.outer); detail('Global', f.global); detail('Label', f.label); } if (data.member) { a = Object.keys(data.member); if (a.length) { a = a.sort(); m = '<br><pre id=members>/*members '; l = 10; for (i = 0; i < a.length; i += 1) { k = a[i]; n = k.name(); if (l + n.length > 72) { o.push(m + '<br>'); m = ' '; l = 1; } l += n.length + 2; if (data.member[k] === 1) { n = '<i>' + n + '</i>'; } if (i < a.length - 1) { n += ', '; } m += n; } o.push(m + '<br>*/</pre>'); } o.push('</div>'); } } return o.join(''); }; itself.jshint = itself; return itself; }()); // Make JSHINT a Node module, if possible. if (typeof exports === 'object' && exports) exports.JSHINT = JSHINT;
describe('Test Parser: ', function () { // TODO: Fix files to load in karma.conf.js // beforeEach( function() { // module('textAngular'); // module('pdfDelegate'); // module('LatexEditor'); // inject(function($controller) { // buttonController = $controller('EditorButtonController'); // }); // }); it('Proof of concept.', function() { expect(true).toBeTruthy(); }); xit('Controller should be defined.', function() { expect(buttonController).toBeDefined(); }); xit('Parsing an empty string should return an empty string.',function() { expect(buttonController.tokenize('')).toEqual(''); }); xit('Tokenizing an h1 tag should return the right LaTeX command.',function() { expect(buttonController.tokenize('<h1></h1>')).toEqual('\\section*{\\raggedright{}}'); }); });
import Configuration from "../data/Configuration"; import MessageService from "../services/MessageService"; import PageScriptService from "../services/PageScriptService"; /* global chrome */ class ContentScriptService { static init(config: Configuration) { PageScriptService.run(` window.BeyondHelp = { id : "${chrome.runtime.id}", config: ${JSON.stringify(config)} } `); } } export default ContentScriptService;
import { setData } from '@progress/kendo-angular-intl'; setData({ name: "en-MT", likelySubtags: { en: "en-Latn-US" }, identity: { language: "en", territory: "MT" }, territory: "MT", numbers: { symbols: { decimal: ".", group: ",", list: ";", percentSign: "%", plusSign: "+", minusSign: "-", exponential: "E", superscriptingExponent: "×", perMille: "‰", infinity: "∞", nan: "NaN", timeSeparator: ":" }, decimal: { patterns: [ "n" ], groupSize: [ 3 ] }, scientific: { patterns: [ "nEn" ], groupSize: [] }, percent: { patterns: [ "n%" ], groupSize: [ 3 ] }, currency: { patterns: [ "$n" ], groupSize: [ 3 ], "unitPattern-count-one": "n $", "unitPattern-count-other": "n $" }, accounting: { patterns: [ "$n", "($n)" ], groupSize: [ 3 ] } } });
(function(window) { function Ball() { this.initialize(); } //p est un raccourci var p = Ball.prototype = new createjs.Container(); // public properties: p.BallBody; p.vX; p.vY; p.bounds; p.hit; p.largeurDeplacement; p.hauteurDeplacement; // constructor: p.Container_initialize = p.initialize; //unique to avoid overiding base class p.initialize = function() { this.Container_initialize(); this.BallBody = new createjs.Shape(); this.addChild(this.BallBody); this.makeShape(); this.vX = 4; this.vY = 4; } // public methods: p.makeShape = function() { //Cercle var g = this.BallBody.graphics; g.clear(); g.setStrokeStyle(1); g.beginStroke(createjs.Graphics.getRGB(0,255,0)); g.beginFill(createjs.Graphics.getRGB(255,0,0)); g.drawCircle(0,0,10); //radius pour savoir si on touche ou pas this.bounds = 10; this.hit = this.bounds; } // faire un rebond vertical p.verticalBounce = function(){ this.vX = this.vX * (-1) } // idem horizontal p.horizontalBounce = function(){ this.vY = this.vY * (-1) } p.hitRadius = function(tX, tY, tHit) { // savoir si il est en dehors de la zone hauteur largeur if(tX - tHit > this.x + this.hit) { return 'not'; } if(tX + tHit < this.x - this.hit) { return 'not'; } if(tY - tHit > this.y + this.hit) { return 'not'; } if(tY + tHit < this.y - this.hit) { return 'not'; } //verifier les bords arrondiees return this.hit + tHit > Math.sqrt(Math.pow(Math.abs(this.x - tX),2) + Math.pow(Math.abs(this.y - tY),2)); }, //limitter le déplacement de a balle sur une hauteur et une taille donné p.constrainBall = function(largeur,hauteur){ this.largeurDeplacement = largeur; this.hauteurDeplacement = hauteur; }, p.tick = function(player) { // deplacer this.x += this.vX; this.y += this.vY; //verifier si bounce if (this.y <= 0 || this.y >= this.hauteurDeplacement) { if(this.y <= 0 ){ this.y = 0; }else{ this.y = this.hauteurDeplacement; } this.horizontalBounce(); } // si la balle touche le mur vertical else if( this.x <= 0 || this.x >= this.largeurDeplacement) { if(this.x <= 0 ){ this.x = 0; }else{ this.x = this.largeurDeplacement; } this.verticalBounce(); } } window.Ball = Ball; }(window));
this.NesDb = this.NesDb || {}; NesDb[ 'D32CCAFB8B336BFCB0666DBD60B1364CF226C3FC' ] = { "$": { "name": "Nigel Mansell's World Championship Racing", "class": "Licensed", "catalog": "NES-NC-USA", "publisher": "GameTek", "developer": "Gremlin", "region": "USA", "players": "2", "date": "1993-10" }, "cartridge": [ { "$": { "system": "NES-NTSC", "crc": "4751A751", "sha1": "D32CCAFB8B336BFCB0666DBD60B1364CF226C3FC", "dump": "ok", "dumper": "bootgod", "datedumped": "2006-02-19" }, "board": [ { "$": { "type": "NES-SLROM", "pcb": "NES-SLROM-06", "mapper": "1" }, "prg": [ { "$": { "name": "NES-NC-0 PRG", "size": "128k", "crc": "F91BAC83", "sha1": "270CD6A7629B75F70590AD96B6D664EAA47DB726" } } ], "chr": [ { "$": { "name": "NES-NC-0 CHR", "size": "128k", "crc": "307157F3", "sha1": "7B98464C8A4C8B2E0F9CB93D6BA6252E2F091018" } } ], "chip": [ { "$": { "type": "MMC1B2" } } ], "cic": [ { "$": { "type": "6113B1" } } ] } ] } ], "gameGenieCodes": [ { "name": "No extra time in the pits", "codes": [ [ "GZSULOVV" ] ] }, { "name": "Only need 3 laps in South Africa instead of 6", "codes": [ [ "GANKXZYA" ] ] }, { "name": "Only need 3 laps in Mexico instead of 6", "codes": [ [ "GANKUZYA" ] ] }, { "name": "Only need 3 laps in Brazil instead of 5", "codes": [ [ "GANKKZTA" ] ] }, { "name": "Only need 3 laps in Spain instead of 4", "codes": [ [ "GANKSZIA" ] ] }, { "name": "Only need 3 laps in San Marino instead of 6", "codes": [ [ "GANKVZYA" ] ] }, { "name": "Only need 3 laps in Monaco instead of 5", "codes": [ [ "GANKNZTA" ] ] }, { "name": "Only need 3 laps in Canada instead of 6", "codes": [ [ "GEEGEZYA" ] ] }, { "name": "Only need 3 laps in France instead of 4", "codes": [ [ "GEEGOZIA" ] ] }, { "name": "Only need 3 laps in Great Britian instead of 5", "codes": [ [ "GEEGXZTA" ] ] }, { "name": "Only need 3 laps in Germany instead of 5", "codes": [ [ "GEEGUZTA" ] ] }, { "name": "Only need 3 laps in Hungary instead of 5", "codes": [ [ "GEEGKZTA" ] ] }, { "name": "Only need 3 laps in Belgium instead of 5", "codes": [ [ "GEEGSZTA" ] ] }, { "name": "Only need 3 laps in Italy instead of 6", "codes": [ [ "GEEGVZYA" ] ] }, { "name": "Only need 3 laps in Portugal instead of 4", "codes": [ [ "GEEGNZIA" ] ] }, { "name": "Only need 3 laps in Japan instead of 5", "codes": [ [ "GEEKEZTA" ] ] }, { "name": "Only need 3 laps in Australia instead of 5", "codes": [ [ "GEEKOZTA" ] ] }, { "name": "Start with 1/2 normal tire tread", "codes": [ [ "AEEKXAAO" ] ] }, { "name": "Less tire wear", "codes": [ [ "SZSTLEVK" ] ] }, { "name": "Full season ends after South Africa", "codes": [ [ "PEOXOZAP" ] ] }, { "name": "Full season ends after Mexico", "codes": [ [ "ZEOXOZAP" ] ] }, { "name": "Full season ends after Brazil", "codes": [ [ "LEOXOZAP" ] ] }, { "name": "Full season ends after Spain", "codes": [ [ "GEOXOZAP" ] ] }, { "name": "Full season ends after San Marino", "codes": [ [ "IEOXOZAP" ] ] }, { "name": "Full season ends after Monaco", "codes": [ [ "TEOXOZAP" ] ] }, { "name": "Full season ends after Canada", "codes": [ [ "YEOXOZAP" ] ] }, { "name": "Full season ends after France", "codes": [ [ "AEOXOZAO" ] ] }, { "name": "Full season ends after Great Britian", "codes": [ [ "PEOXOZAO" ] ] }, { "name": "Full season ends after Germany", "codes": [ [ "ZEOXOZAO" ] ] }, { "name": "Full season ends after Hungary", "codes": [ [ "LEOXOZAO" ] ] }, { "name": "Full season ends after Belgium", "codes": [ [ "GEOXOZAO" ] ] }, { "name": "Full season ends after Italy", "codes": [ [ "IEOXOZAO" ] ] }, { "name": "Full season ends after Portugal", "codes": [ [ "TEOXOZAO" ] ] }, { "name": "Full season ends after Japan", "codes": [ [ "YEOXOZAO" ] ] }, { "name": "Accelerate faster", "codes": [ [ "IVSNIOIN" ] ] }, { "name": "Accelerate a lot faster", "codes": [ [ "IVSNIOIN", "AAKNALGE" ] ] }, { "name": "Only need 1 lap on all tracks", "codes": [ [ "ZANKXZYA", "SXNKSESU" ] ] }, { "name": "Almost no tire wear", "codes": [ [ "SZSTLEVK", "SZNNXEVK" ] ] } ] };
import F from 'funcunit'; import QUnit from 'steal-qunit'; import 'pitbull-client/models/test'; import 'pitbull-client/login/login-test'; import 'pitbull-client/components/login-page/login-page-test'; import 'pitbull-client/components/nav-bar/nav-bar-test'; import 'pitbull-client/components/pitbull-footer/pitbull-footer-test'; import 'pitbull-client/conponents/pitbull-content/pitbull-content-test'; import 'pitbull-client/components/pitbull-cameras/pitbull-cameras-test'; F.attach(QUnit); QUnit.module('pitbull-client functional smoke test', { beforeEach() { F.open('./development.html'); } }); QUnit.test('pitbull-client main page shows up', function() { F('title').text('pitbull-client', 'Title is set'); });
define(['angular'], function (angular) { 'use strict'; return angular.module('directives', []); });
function report(str) { console.log(str); } r = require('rethinkdb'); function createTable(conn, tableName) { r.db('test').tableCreate(tableName).run(conn, function(err, res) { if(err) { //throw err; report("err: "+err); report("Cannot create table "+tableName); } else { console.log(res); report("Created table "+tableName); } }); } r.connect({ host: 'localhost', port: 28015 }, function(err, conn) { if(err) throw err; createTable(conn, "chat"); createTable(conn, "notes"); createTable(conn, "periscope"); });
import createDebug from 'debug' const debug = createDebug('sa:debug') export default debug
var className = /******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 3); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__lib_authenticationManager__ = __webpack_require__(1); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. const config = { clientId: "<clientId of your app>", tenant: "<tenantId of your app>", popUp: false, cacheLocation: "localStorage", redirectUri: "http://localhost:8080/login.html" }; const authManager = new __WEBPACK_IMPORTED_MODULE_0__lib_authenticationManager__["a" /* AuthenticationManager */](config); /* harmony export (immutable) */ __webpack_exports__["a"] = authManager; /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. const adal = __webpack_require__(2); class AuthenticationManager { constructor(config) { this.authContext = new adal(config); } /** * Provides the authentication context supported by adal-js. */ getAuthenticationContext() { return this.authContext; } /** * Gets the token for the specified resource provided the user is already logged in. * @param resource This is the resource uri or token audience for which the token is needed. * For example it can be: * - resourcemanagement endpoint "https://management.azure.com/" (default). * - management endpoint "https://management.core.windows.net/" * - graph endpoint "https://graph.windows.net/", * - sqlManagement endpoint "https://management.core.windows.net:8443/" * - keyvault endpoint "https://<keyvault-account-name>.vault.azure.net/" * - datalakestore endpoint "https://<datalakestore-account>.azuredatalakestore.net/" * - datalakeanalytics endpoint "https://<datalakeanalytics-account>.azuredatalakeanalytics.net/" */ getToken(resource = "https://management.azure.com/") { // Get Cached user needs to be called to ensure that the "this._user" property in adal-js is populated from the token cache. this.authContext.getCachedUser(); return new Promise((resolve, reject) => { // adal has inbuilt smarts to acquire token from the cache if not expired. Otherwise sends request to AAD to obtain a new token this.authContext.acquireToken(resource, (error, token) => { if (error || !token) { return reject(error); } return resolve(token); }); }); } /** * A simple wrapper around adal-js' handleWindowCallback() method * Handles redirection after login operation. Gets access token from url and saves token to the (local/session) storage * or saves error in case unsuccessful login. */ handleWindowCallback() { this.authContext.handleWindowCallback(); const user = this.authContext.getCachedUser(); if (user && user.userName) { document.write("login successful"); } else { document.write("Could not find the user. Either this method was called before login or login was not successful."); } } } /* harmony export (immutable) */ __webpack_exports__["a"] = AuthenticationManager; /***/ }), /* 2 */ /***/ (function(module, exports) { //---------------------------------------------------------------------- // AdalJS v1.0.15 // @preserve Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 //id // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //---------------------------------------------------------------------- var AuthenticationContext = (function () { 'use strict'; /** * Configuration options for Authentication Context. * @class config * @property {string} tenant - Your target tenant. * @property {string} clientID - Client ID assigned to your app by Azure Active Directory. * @property {string} redirectUri - Endpoint at which you expect to receive tokens.Defaults to `window.location.href`. * @property {string} instance - Azure Active Directory Instance.Defaults to `https://login.microsoftonline.com/`. * @property {Array} endpoints - Collection of {Endpoint-ResourceId} used for automatically attaching tokens in webApi calls. * @property {Boolean} popUp - Set this to true to enable login in a popup winodow instead of a full redirect.Defaults to `false`. * @property {string} localLoginUrl - Set this to redirect the user to a custom login page. * @property {function} displayCall - User defined function of handling the navigation to Azure AD authorization endpoint in case of login. Defaults to 'null'. * @property {string} postLogoutRedirectUri - Redirects the user to postLogoutRedirectUri after logout. Defaults is 'redirectUri'. * @property {string} cacheLocation - Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to 'sessionStorage'. * @property {Array.<string>} anonymousEndpoints Array of keywords or URI's. Adal will not attach a token to outgoing requests that have these keywords or uri. Defaults to 'null'. * @property {number} expireOffsetSeconds If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 120 seconds. * @property {string} correlationId Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits). */ /** * Creates a new AuthenticationContext object. * @constructor * @param {config} config Configuration options for AuthenticationContext */ AuthenticationContext = function (config) { /** * Enum for request type * @enum {string} */ this.REQUEST_TYPE = { LOGIN: 'LOGIN', RENEW_TOKEN: 'RENEW_TOKEN', UNKNOWN: 'UNKNOWN' }; /** * Enum for storage constants * @enum {string} */ this.CONSTANTS = { ACCESS_TOKEN: 'access_token', EXPIRES_IN: 'expires_in', ID_TOKEN: 'id_token', ERROR_DESCRIPTION: 'error_description', SESSION_STATE: 'session_state', STORAGE: { TOKEN_KEYS: 'adal.token.keys', ACCESS_TOKEN_KEY: 'adal.access.token.key', EXPIRATION_KEY: 'adal.expiration.key', STATE_LOGIN: 'adal.state.login', STATE_RENEW: 'adal.state.renew', NONCE_IDTOKEN: 'adal.nonce.idtoken', SESSION_STATE: 'adal.session.state', USERNAME: 'adal.username', IDTOKEN: 'adal.idtoken', ERROR: 'adal.error', ERROR_DESCRIPTION: 'adal.error.description', LOGIN_REQUEST: 'adal.login.request', LOGIN_ERROR: 'adal.login.error', RENEW_STATUS: 'adal.token.renew.status' }, RESOURCE_DELIMETER: '|', LOADFRAME_TIMEOUT: '6000', TOKEN_RENEW_STATUS_CANCELED: 'Canceled', TOKEN_RENEW_STATUS_COMPLETED: 'Completed', TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress', LOGGING_LEVEL: { ERROR: 0, WARN: 1, INFO: 2, VERBOSE: 3 }, LEVEL_STRING_MAP: { 0: 'ERROR:', 1: 'WARNING:', 2: 'INFO:', 3: 'VERBOSE:' }, POPUP_WIDTH: 483, POPUP_HEIGHT: 600 }; if (AuthenticationContext.prototype._singletonInstance) { return AuthenticationContext.prototype._singletonInstance; } AuthenticationContext.prototype._singletonInstance = this; // public this.instance = 'https://login.microsoftonline.com/'; this.config = {}; this.callback = null; this.popUp = false; this.isAngular = false; // private this._user = null; this._activeRenewals = {}; this._loginInProgress = false; this._acquireTokenInProgress = false; window.renewStates = []; window.callBackMappedToRenewStates = {}; window.callBacksMappedToRenewStates = {}; // validate before constructor assignments if (config.displayCall && typeof config.displayCall !== 'function') { throw new Error('displayCall is not a function'); } if (!config.clientId) { throw new Error('clientId is required'); } this.config = this._cloneConfig(config); if (this.config.navigateToLoginRequestUrl === undefined) this.config.navigateToLoginRequestUrl = true; if (this.config.popUp) this.popUp = true; if (this.config.callback && typeof this.config.callback === 'function') this.callback = this.config.callback; if (this.config.instance) { this.instance = this.config.instance; } // App can request idtoken for itself using clientid as resource if (!this.config.loginResource) { this.config.loginResource = this.config.clientId; } // redirect and logout_redirect are set to current location by default if (!this.config.redirectUri) { // strip off query parameters or hashes from the redirect uri as AAD does not allow those. this.config.redirectUri = window.location.href.split("?")[0].split("#")[0]; } if (!this.config.postLogoutRedirectUri) { // strip off query parameters or hashes from the post logout redirect uri as AAD does not allow those. this.config.postLogoutRedirectUri = window.location.href.split("?")[0].split("#")[0]; } if (!this.config.anonymousEndpoints) { this.config.anonymousEndpoints = []; } if (this.config.isAngular) { this.isAngular = this.config.isAngular; } }; window.Logging = { level: 0, log: function (message) { } }; /** * Initiates the login process by redirecting the user to Azure AD authorization endpoint. */ AuthenticationContext.prototype.login = function (loginStartPage) { // Token is not present and user needs to login if (this._loginInProgress) { this.info("Login in progress"); return; } var expectedState = this._guid(); this.config.state = expectedState; this._idTokenNonce = this._guid(); this.verbose('Expected state: ' + expectedState + ' startPage:' + window.location.href); this._saveItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST, loginStartPage || window.location.href); this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, ''); this._saveItem(this.CONSTANTS.STORAGE.STATE_LOGIN, expectedState); this._saveItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN, this._idTokenNonce); this._saveItem(this.CONSTANTS.STORAGE.ERROR, ''); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, ''); var urlNavigate = this._getNavigateUrl('id_token', null) + '&nonce=' + encodeURIComponent(this._idTokenNonce); this._loginInProgress = true; if (this.config.displayCall) { // User defined way of handling the navigation this.config.displayCall(urlNavigate); } else if (this.popUp) { this._loginPopup(urlNavigate); } else { this.promptUser(urlNavigate); } }; /** * Configures popup window for login. * @ignore */ AuthenticationContext.prototype._openPopup = function (urlNavigate, title, popUpWidth, popUpHeight) { try { /** * adding winLeft and winTop to account for dual monitor * using screenLeft and screenTop for IE8 and earlier */ var winLeft = window.screenLeft ? window.screenLeft : window.screenX; var winTop = window.screenTop ? window.screenTop : window.screenY; /** * window.innerWidth displays browser window's height and width excluding toolbars * using document.documentElement.clientWidth for IE8 and earlier */ var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var left = ((width / 2) - (popUpWidth / 2)) + winLeft; var top = ((height / 2) - (popUpHeight / 2)) + winTop; var popupWindow = window.open(urlNavigate, title, 'width=' + popUpWidth + ', height=' + popUpHeight + ', top=' + top + ', left=' + left); if (popupWindow.focus) { popupWindow.focus(); } return popupWindow; } catch (e) { this.warn('Error opening popup, ' + e.message); this._loginInProgress = false; return null; } } /** * After authorization, the user will be sent to your specified redirect_uri with the user's bearer token * attached to the URI fragment as an id_token field. It closes popup window after redirection. * @ignore */ AuthenticationContext.prototype._loginPopup = function (urlNavigate, resource, callback) { var popupWindow = this._openPopup(urlNavigate, "login", this.CONSTANTS.POPUP_WIDTH, this.CONSTANTS.POPUP_HEIGHT); var loginCallback = callback || this.callback; if (popupWindow == null) { this.warn('Popup Window is null. This can happen if you are using IE'); this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'Error opening popup'); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Popup Window is null. This can happen if you are using IE'); this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'Popup Window is null. This can happen if you are using IE'); if (resource && this._activeRenewals[resource]) { this._activeRenewals[resource] = null; } this._loginInProgress = false; this._acquireTokenInProgress = false; if (loginCallback) loginCallback(this._getItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null, this._getItem(this.CONSTANTS.STORAGE.ERROR)); return; } if (this.config.redirectUri.indexOf('#') != -1) var registeredRedirectUri = this.config.redirectUri.split("#")[0]; else var registeredRedirectUri = this.config.redirectUri; var that = this; var pollTimer = window.setInterval(function () { if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) { that._loginInProgress = false; that._acquireTokenInProgress = false; if (resource && that._activeRenewals[resource]) { that._activeRenewals[resource] = null; } window.clearInterval(pollTimer); } try { if (popupWindow.location.href.indexOf(registeredRedirectUri) != -1) { if (that.isAngular) { that._onPopUpHashChanged(popupWindow.location.hash); } else { that.handleWindowCallback(popupWindow.location.hash); } window.clearInterval(pollTimer); that._loginInProgress = false; that._acquireTokenInProgress = false; that.info("Closing popup window"); popupWindow.close(); } } catch (e) { } }, 1); }; AuthenticationContext.prototype._onPopUpHashChanged = function (hash) { // Custom Event is not supported in IE, below IIFE will polyfill the CustomEvent() constructor functionality in Internet Explorer 9 and higher (function () { if (typeof window.CustomEvent === "function") { return false; } function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; } CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })(); var evt = new CustomEvent('adal:popUpHashChanged', { detail: hash }); window.dispatchEvent(evt); }; AuthenticationContext.prototype.loginInProgress = function () { return this._loginInProgress; }; /** * Checks for the resource in the cache. By default, cache location is Session Storage * @ignore * @returns {Boolean} 'true' if login is in progress, else returns 'false'. */ AuthenticationContext.prototype._hasResource = function (key) { var keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS); return keys && !this._isEmpty(keys) && (keys.indexOf(key + this.CONSTANTS.RESOURCE_DELIMETER) > -1); }; /** * Gets token for the specified resource from the cache. * @param {string} resource A URI that identifies the resource for which the token is requested. * @returns {string} token if if it exists and not expired, otherwise null. */ AuthenticationContext.prototype.getCachedToken = function (resource) { if (!this._hasResource(resource)) { return null; } var token = this._getItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource); var expiry = this._getItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource); // If expiration is within offset, it will force renew var offset = this.config.expireOffsetSeconds || 300; if (expiry && (expiry > this._now() + offset)) { return token; } else { this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, ''); this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, 0); return null; } }; /** * User information from idtoken. * @class User * @property {string} userName - username assigned from upn or email. * @property {object} profile - properties parsed from idtoken. */ /** * If user object exists, returns it. Else creates a new user object by decoding id_token from the cache. * @returns {User} user object */ AuthenticationContext.prototype.getCachedUser = function () { if (this._user) { return this._user; } var idtoken = this._getItem(this.CONSTANTS.STORAGE.IDTOKEN); this._user = this._createUser(idtoken); return this._user; }; /** * Adds the passed callback to the array of callbacks for the specified resource and puts the array on the window object. * @param {string} resource A URI that identifies the resource for which the token is requested. * @param {string} expectedState A unique identifier (guid). * @param {tokenCallback} callback - The callback provided by the caller. It will be called with token or error. */ AuthenticationContext.prototype.registerCallback = function (expectedState, resource, callback) { this._activeRenewals[resource] = expectedState; if (!window.callBacksMappedToRenewStates[expectedState]) { window.callBacksMappedToRenewStates[expectedState] = []; } var self = this; window.callBacksMappedToRenewStates[expectedState].push(callback); if (!window.callBackMappedToRenewStates[expectedState]) { window.callBackMappedToRenewStates[expectedState] = function (errorDesc, token, error) { self._activeRenewals[resource] = null; for (var i = 0; i < window.callBacksMappedToRenewStates[expectedState].length; ++i) { try { window.callBacksMappedToRenewStates[expectedState][i](errorDesc, token, error); } catch (error) { self.warn(error); } } window.callBacksMappedToRenewStates[expectedState] = null; window.callBackMappedToRenewStates[expectedState] = null; }; } }; // var errorResponse = {error:'', error_description:''}; // var token = 'string token'; // callback(errorResponse, token) // with callback /** * Acquires access token with hidden iframe * @ignore */ AuthenticationContext.prototype._renewToken = function (resource, callback) { // use iframe to try refresh token // use given resource to create new authz url this.info('renewToken is called for resource:' + resource); var frameHandle = this._addAdalFrame('adalRenewFrame' + resource); var expectedState = this._guid() + '|' + resource; this.config.state = expectedState; // renew happens in iframe, so it keeps javascript context window.renewStates.push(expectedState); this.verbose('Renew token Expected state: ' + expectedState); var urlNavigate = this._getNavigateUrl('token', resource) + '&prompt=none'; urlNavigate = this._addHintParameters(urlNavigate); this.registerCallback(expectedState, resource, callback); this.verbose('Navigate to:' + urlNavigate); frameHandle.src = 'about:blank'; this._loadFrameTimeout(urlNavigate, 'adalRenewFrame' + resource, resource); }; /** * Renews idtoken for app's own backend when resource is clientId and calls the callback with token/error * @ignore */ AuthenticationContext.prototype._renewIdToken = function (callback) { // use iframe to try refresh token this.info('renewIdToken is called'); var frameHandle = this._addAdalFrame('adalIdTokenFrame'); var expectedState = this._guid() + '|' + this.config.clientId; this._idTokenNonce = this._guid(); this._saveItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN, this._idTokenNonce); this.config.state = expectedState; // renew happens in iframe, so it keeps javascript context window.renewStates.push(expectedState); this.verbose('Renew Idtoken Expected state: ' + expectedState); var urlNavigate = this._getNavigateUrl('id_token', null) + '&prompt=none'; urlNavigate = this._addHintParameters(urlNavigate); urlNavigate += '&nonce=' + encodeURIComponent(this._idTokenNonce); this.registerCallback(expectedState, this.config.clientId, callback); this.idTokenNonce = null; this.verbose('Navigate to:' + urlNavigate); frameHandle.src = 'about:blank'; this._loadFrameTimeout(urlNavigate, 'adalIdTokenFrame', this.config.clientId); }; /** * Checks if the authorization endpoint URL contains query string parameters * @ignore */ AuthenticationContext.prototype._urlContainsQueryStringParameter = function (name, url) { // regex to detect pattern of a ? or & followed by the name parameter and an equals character var regex = new RegExp("[\\?&]" + name + "="); return regex.test(url); } // Calling _loadFrame but with a timeout to signal failure in loadframeStatus. Callbacks are left // registered when network errors occur and subsequent token requests for same resource are registered to the pending request /** * @ignore */ AuthenticationContext.prototype._loadFrameTimeout = function (urlNavigation, frameName, resource) { //set iframe session to pending this.verbose('Set loading state to pending for: ' + resource); this._saveItem(this.CONSTANTS.STORAGE.RENEW_STATUS + resource, this.CONSTANTS.TOKEN_RENEW_STATUS_IN_PROGRESS); this._loadFrame(urlNavigation, frameName); var self = this; setTimeout(function () { if (self._getItem(self.CONSTANTS.STORAGE.RENEW_STATUS + resource) === self.CONSTANTS.TOKEN_RENEW_STATUS_IN_PROGRESS) { // fail the iframe session if it's in pending state self.verbose('Loading frame has timed out after: ' + (self.CONSTANTS.LOADFRAME_TIMEOUT / 1000) + ' seconds for resource ' + resource); var expectedState = self._activeRenewals[resource]; if (expectedState && window.callBackMappedToRenewStates[expectedState]) { window.callBackMappedToRenewStates[expectedState]('Token renewal operation failed due to timeout', null, 'Token Renewal Failed'); } self._saveItem(self.CONSTANTS.STORAGE.RENEW_STATUS + resource, self.CONSTANTS.TOKEN_RENEW_STATUS_CANCELED); } }, self.CONSTANTS.LOADFRAME_TIMEOUT); } /** * Loads iframe with authorization endpoint URL * @ignore */ AuthenticationContext.prototype._loadFrame = function (urlNavigate, frameName) { // This trick overcomes iframe navigation in IE // IE does not load the page consistently in iframe var self = this; self.info('LoadFrame: ' + frameName); var frameCheck = frameName; setTimeout(function () { var frameHandle = self._addAdalFrame(frameCheck); if (frameHandle.src === '' || frameHandle.src === 'about:blank') { frameHandle.src = urlNavigate; self._loadFrame(urlNavigate, frameCheck); } }, 500); }; /** * @callback tokenCallback * @param {string} error_description error description returned from AAD if token request fails. * @param {string} token token returned from AAD if token request is successful. * @param {string} error error message returned from AAD if token request fails. */ /** * Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token. * @param {string} resource ResourceUri identifying the target resource * @param {tokenCallback} callback - The callback provided by the caller. It will be called with token or error. */ AuthenticationContext.prototype.acquireToken = function (resource, callback) { if (this._isEmpty(resource)) { this.warn('resource is required'); callback('resource is required', null, 'resource is required'); return; } var token = this.getCachedToken(resource); if (token) { this.info('Token is already in cache for resource:' + resource); callback(null, token, null); return; } if (!this._user) { this.warn('User login is required'); callback('User login is required', null, 'login required'); return; } // refresh attept with iframe //Already renewing for this resource, callback when we get the token. if (this._activeRenewals[resource]) { //Active renewals contains the state for each renewal. this.registerCallback(this._activeRenewals[resource], resource, callback); } else { if (resource === this.config.clientId) { // App uses idtoken to send to api endpoints // Default resource is tracked as clientid to store this token this.verbose('renewing idtoken'); this._renewIdToken(callback); } else { this._renewToken(resource, callback); } } }; /** * Acquires token (interactive flow using a popUp window) by sending request to AAD to obtain a new token. * @param {string} resource ResourceUri identifying the target resource * @param {string} extraQueryParameters extraQueryParameters to add to the authentication request * @param {tokenCallback} callback - The callback provided by the caller. It will be called with token or error. */ AuthenticationContext.prototype.acquireTokenPopup = function (resource, extraQueryParameters, claims, callback) { if (this._isEmpty(resource)) { this.warn('resource is required'); callback('resource is required', null, 'resource is required'); return; } if (!this._user) { this.warn('User login is required'); callback('User login is required', null, 'login required'); return; } if (this._acquireTokenInProgress) { this.warn("Acquire token interactive is already in progress") callback("Acquire token interactive is already in progress", null, "Acquire token interactive is already in progress"); return; } var expectedState = this._guid() + '|' + resource; this.config.state = expectedState; window.renewStates.push(expectedState); this.verbose('Renew token Expected state: ' + expectedState); var urlNavigate = this._getNavigateUrl('token', resource) + '&prompt=select_account'; if (extraQueryParameters) { urlNavigate += encodeURIComponent(extraQueryParameters); } if (claims && (urlNavigate.indexOf("&claims") === -1)) { urlNavigate += '&claims=' + encodeURIComponent(claims); } else if (claims && (urlNavigate.indexOf("&claims") !== -1)) { throw new Error('Claims cannot be passed as an extraQueryParameter'); } urlNavigate = this._addHintParameters(urlNavigate); this._acquireTokenInProgress = true; this.info('acquireToken interactive is called for the resource ' + resource); this.registerCallback(expectedState, resource, callback); this._loginPopup(urlNavigate, resource, callback); }; /** * Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the Authentication * request constructor will be called. * @param {string} resource ResourceUri identifying the target resource * @param {string} extraQueryParameters extraQueryParameters to add to the authentication request */ AuthenticationContext.prototype.acquireTokenRedirect = function (resource, extraQueryParameters, claims) { if (this._isEmpty(resource)) { this.warn('resource is required'); callback('resource is required', null, 'resource is required'); return; } if (!this._user) { this.warn('User login is required'); callback('User login is required', null, 'login required'); return; } if (this._acquireTokenInProgress) { this.warn("Acquire token interactive is already in progress") callback("Acquire token interactive is already in progress", null, "Acquire token interactive is already in progress"); return; } var expectedState = this._guid() + '|' + resource; this.config.state = expectedState; window.renewStates.push(expectedState); this.verbose('Renew token Expected state: ' + expectedState); var urlNavigate = this._getNavigateUrl('token', resource) + '&prompt=select_account'; if (extraQueryParameters) { urlNavigate += encodeURIComponent(extraQueryParameters); } if (claims && (urlNavigate.indexOf("&claims") === -1)) { urlNavigate += '&claims=' + encodeURIComponent(claims); } else if (claims && (urlNavigate.indexOf("&claims") !== -1)) { throw new Error('Claims cannot be passed as an extraQueryParameter'); } urlNavigate = this._addHintParameters(urlNavigate); this._acquireTokenInProgress = true; this.info('acquireToken interactive is called for the resource ' + resource); this._saveItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST, window.location.href); this._saveItem(this.CONSTANTS.STORAGE.STATE_RENEW, expectedState); this.promptUser(urlNavigate); }; /** * Redirects the browser to Azure AD authorization endpoint. * @param {string} urlNavigate Url of the authorization endpoint. */ AuthenticationContext.prototype.promptUser = function (urlNavigate) { if (urlNavigate) { this.info('Navigate to:' + urlNavigate); window.location.replace(urlNavigate); } else { this.info('Navigate url is empty'); } }; /** * Clears cache items. */ AuthenticationContext.prototype.clearCache = function () { this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY, ''); this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY, 0); this._saveItem(this.CONSTANTS.STORAGE.SESSION_STATE, ''); this._saveItem(this.CONSTANTS.STORAGE.STATE_LOGIN, ''); window.renewStates = []; this._saveItem(this.CONSTANTS.STORAGE.USERNAME, ''); this._saveItem(this.CONSTANTS.STORAGE.IDTOKEN, ''); this._saveItem(this.CONSTANTS.STORAGE.ERROR, ''); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, ''); var keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS); if (!this._isEmpty(keys)) { keys = keys.split(this.CONSTANTS.RESOURCE_DELIMETER); for (var i = 0; i < keys.length; i++) { this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + keys[i], ''); this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + keys[i], 0); } } this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, ''); }; /** * Clears cache items for a given resource. * @param {string} resource a URI that identifies the resource. */ AuthenticationContext.prototype.clearCacheForResource = function (resource) { this._saveItem(this.CONSTANTS.STORAGE.STATE_RENEW, ''); this._saveItem(this.CONSTANTS.STORAGE.ERROR, ''); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, ''); if (this._hasResource(resource)) { this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, ''); this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, 0); } }; /** * Redirects user to logout endpoint. * After logout, it will redirect to postLogoutRedirectUri if added as a property on the config object. */ AuthenticationContext.prototype.logOut = function () { this.clearCache(); this._user = null; var urlNavigate; if (this.config.logOutUri) { urlNavigate = this.config.logOutUri; } else { var tenant = 'common'; var logout = ''; if (this.config.tenant) { tenant = this.config.tenant; } if (this.config.postLogoutRedirectUri) { logout = 'post_logout_redirect_uri=' + encodeURIComponent(this.config.postLogoutRedirectUri); } urlNavigate = this.instance + tenant + '/oauth2/logout?' + logout; } this.info('Logout navigate to: ' + urlNavigate); this.promptUser(urlNavigate); }; AuthenticationContext.prototype._isEmpty = function (str) { return (typeof str === 'undefined' || !str || 0 === str.length); }; /** * @callback userCallback * @param {string} error error message if user info is not available. * @param {User} user user object retrieved from the cache. */ /** * Calls the passed in callback with the user object or error message related to the user. * @param {userCallback} callback - The callback provided by the caller. It will be called with user or error. */ AuthenticationContext.prototype.getUser = function (callback) { // IDToken is first call if (typeof callback !== 'function') { throw new Error('callback is not a function'); } // user in memory if (this._user) { callback(null, this._user); return; } // frame is used to get idtoken var idtoken = this._getItem(this.CONSTANTS.STORAGE.IDTOKEN); if (!this._isEmpty(idtoken)) { this.info('User exists in cache: '); this._user = this._createUser(idtoken); callback(null, this._user); } else { this.warn('User information is not available'); callback('User information is not available', null); } }; /** * Adds login_hint to authorization URL which is used to pre-fill the username field of sign in page for the user if known ahead of time. * domain_hint can be one of users/organisations which when added skips the email based discovery process of the user. * @ignore */ AuthenticationContext.prototype._addHintParameters = function (urlNavigate) { // include hint params only if upn is present if (this._user && this._user.profile && this._user.profile.hasOwnProperty('upn')) { // don't add login_hint twice if user provided it in the extraQueryParameter value if (!this._urlContainsQueryStringParameter("login_hint", urlNavigate)) { // add login_hint urlNavigate += '&login_hint=' + encodeURIComponent(this._user.profile.upn); } // don't add domain_hint twice if user provided it in the extraQueryParameter value if (!this._urlContainsQueryStringParameter("domain_hint", urlNavigate) && this._user.profile.upn.indexOf('@') > -1) { var parts = this._user.profile.upn.split('@'); // local part can include @ in quotes. Sending last part handles that. urlNavigate += '&domain_hint=' + encodeURIComponent(parts[parts.length - 1]); } } return urlNavigate; } /** * Creates a user object by decoding the id_token * @ignore */ AuthenticationContext.prototype._createUser = function (idToken) { var user = null; var parsedJson = this._extractIdToken(idToken); if (parsedJson && parsedJson.hasOwnProperty('aud')) { if (parsedJson.aud.toLowerCase() === this.config.clientId.toLowerCase()) { user = { userName: '', profile: parsedJson }; if (parsedJson.hasOwnProperty('upn')) { user.userName = parsedJson.upn; } else if (parsedJson.hasOwnProperty('email')) { user.userName = parsedJson.email; } } else { this.warn('IdToken has invalid aud field'); } } return user; }; /** * Returns the anchor part(#) of the URL * @ignore */ AuthenticationContext.prototype._getHash = function (hash) { if (hash.indexOf('#/') > -1) { hash = hash.substring(hash.indexOf('#/') + 2); } else if (hash.indexOf('#') > -1) { hash = hash.substring(1); } return hash; }; /** * Checks if the URL fragment contains access token, id token or error_description. * @param {string} hash - Hash passed from redirect page * @returns {Boolean} true if response contains id_token, access_token or error, false otherwise. */ AuthenticationContext.prototype.isCallback = function (hash) { hash = this._getHash(hash); var parameters = this._deserialize(hash); return ( parameters.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION) || parameters.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN) || parameters.hasOwnProperty(this.CONSTANTS.ID_TOKEN) ); }; /** * Gets login error * @returns {string} error message related to login. */ AuthenticationContext.prototype.getLoginError = function () { return this._getItem(this.CONSTANTS.STORAGE.LOGIN_ERROR); }; /** * Request info object created from the response received from AAD. * @class RequestInfo * @property {object} parameters - object comprising of fields such as id_token/error, session_state, state, e.t.c. * @property {REQUEST_TYPE} requestType - either LOGIN, RENEW_TOKEN or UNKNOWN. * @property {boolean} stateMatch - true if state is valid, false otherwise. * @property {string} stateResponse - unique guid used to match the response with the request. * @property {boolean} valid - true if requestType contains id_token, access_token or error, false otherwise. */ /** * Creates a requestInfo object from the URL fragment and returns it. * @returns {RequestInfo} an object created from the redirect response from AAD comprising of the keys - parameters, requestType, stateMatch, stateResponse and valid. */ AuthenticationContext.prototype.getRequestInfo = function (hash) { hash = this._getHash(hash); var parameters = this._deserialize(hash); var requestInfo = { valid: false, parameters: {}, stateMatch: false, stateResponse: '', requestType: this.REQUEST_TYPE.UNKNOWN }; if (parameters) { requestInfo.parameters = parameters; if (parameters.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION) || parameters.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN) || parameters.hasOwnProperty(this.CONSTANTS.ID_TOKEN)) { requestInfo.valid = true; // which call var stateResponse = ''; if (parameters.hasOwnProperty('state')) { this.verbose('State: ' + parameters.state); stateResponse = parameters.state; } else { this.warn('No state returned'); return requestInfo; } requestInfo.stateResponse = stateResponse; // async calls can fire iframe and login request at the same time if developer does not use the API as expected // incoming callback needs to be looked up to find the request type if (stateResponse === this._getItem(this.CONSTANTS.STORAGE.STATE_LOGIN)) { requestInfo.requestType = this.REQUEST_TYPE.LOGIN; requestInfo.stateMatch = true; return requestInfo; } else if (stateResponse === this._getItem(this.CONSTANTS.STORAGE.STATE_RENEW)) { requestInfo.requestType = this.REQUEST_TYPE.RENEW_TOKEN; requestInfo.stateMatch = true; return requestInfo; } // external api requests may have many renewtoken requests for different resource if (!requestInfo.stateMatch && window.parent) { var statesInParentContext = window.parent.renewStates; for (var i = 0; i < statesInParentContext.length; i++) { if (statesInParentContext[i] === requestInfo.stateResponse) { requestInfo.requestType = this.REQUEST_TYPE.RENEW_TOKEN; requestInfo.stateMatch = true; break; } } } } } return requestInfo; }; /** * Extracts resource value from state. * @ignore */ AuthenticationContext.prototype._getResourceFromState = function (state) { if (state) { var splitIndex = state.indexOf('|'); if (splitIndex > -1 && splitIndex + 1 < state.length) { return state.substring(splitIndex + 1); } } return ''; }; /** * Saves token or error received in the response from AAD in the cache. In case of id_token, it also creates the user object. */ AuthenticationContext.prototype.saveTokenFromHash = function (requestInfo) { this.info('State status:' + requestInfo.stateMatch + '; Request type:' + requestInfo.requestType); this._saveItem(this.CONSTANTS.STORAGE.ERROR, ''); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, ''); var resource = this._getResourceFromState(requestInfo.stateResponse); // Record error if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)) { this.info('Error :' + requestInfo.parameters.error + '; Error description:' + requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]); this._saveItem(this.CONSTANTS.STORAGE.ERROR, requestInfo.parameters.error); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]); if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) { this._loginInProgress = false; this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, requestInfo.parameters.error_description); } } else { // It must verify the state from redirect if (requestInfo.stateMatch) { // record tokens to storage if exists this.info('State is right'); if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.SESSION_STATE)) { this._saveItem(this.CONSTANTS.STORAGE.SESSION_STATE, requestInfo.parameters[this.CONSTANTS.SESSION_STATE]); } var keys; if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)) { this.info('Fragment has access token'); if (!this._hasResource(resource)) { keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || ''; this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER); } // save token with related resource this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ACCESS_TOKEN]); this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._expiresIn(requestInfo.parameters[this.CONSTANTS.EXPIRES_IN])); } if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ID_TOKEN)) { this.info('Fragment has id token'); this._loginInProgress = false; this._user = this._createUser(requestInfo.parameters[this.CONSTANTS.ID_TOKEN]); if (this._user && this._user.profile) { if (this._user.profile.nonce !== this._getItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN)) { this._user = null; this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'Nonce is not same as ' + this._idTokenNonce); } else { this._saveItem(this.CONSTANTS.STORAGE.IDTOKEN, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]); // Save idtoken as access token for app itself resource = this.config.loginResource ? this.config.loginResource : this.config.clientId; if (!this._hasResource(resource)) { keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || ''; this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER); } this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]); this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._user.profile.exp); } } else { this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'invalid id_token'); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Invalid id_token. id_token: ' + requestInfo.parameters[this.CONSTANTS.ID_TOKEN]); } } } else { this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'Invalid_state'); this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Invalid_state. state: ' + requestInfo.stateResponse); } } this._saveItem(this.CONSTANTS.STORAGE.RENEW_STATUS + resource, this.CONSTANTS.TOKEN_RENEW_STATUS_COMPLETED); }; /** * Gets resource for given endpoint if mapping is provided with config. * @param {string} endpoint - The URI for which the resource Id is requested. * @returns {string} resource for this API endpoint. */ AuthenticationContext.prototype.getResourceForEndpoint = function (endpoint) { // if user specified list of anonymous endpoints, no need to send token to these endpoints, return null. if (this.config && this.config.anonymousEndpoints) { for (var i = 0; i < this.config.anonymousEndpoints.length; i++) { if (endpoint.indexOf(this.config.anonymousEndpoints[i]) > -1) { return null; } } } if (this.config && this.config.endpoints) { for (var configEndpoint in this.config.endpoints) { // configEndpoint is like /api/Todo requested endpoint can be /api/Todo/1 if (endpoint.indexOf(configEndpoint) > -1) { return this.config.endpoints[configEndpoint]; } } } // default resource will be clientid if nothing specified // App will use idtoken for calls to itself // check if it's staring from http or https, needs to match with app host if (endpoint.indexOf('http://') > -1 || endpoint.indexOf('https://') > -1) { if (this._getHostFromUri(endpoint) === this._getHostFromUri(this.config.redirectUri)) { return this.config.loginResource; } } else { // in angular level, the url for $http interceptor call could be relative url, // if it's relative call, we'll treat it as app backend call. return this.config.loginResource; } // if not the app's own backend or not a domain listed in the endpoints structure return null; }; /** * Strips the protocol part of the URL and returns it. * @ignore */ AuthenticationContext.prototype._getHostFromUri = function (uri) { // remove http:// or https:// from uri var extractedUri = String(uri).replace(/^(https?:)\/\//, ''); extractedUri = extractedUri.split('/')[0]; return extractedUri; }; /** * This method must be called for processing the response received from AAD. It extracts the hash, processes the token or error, saves it in the cache and calls the registered callbacks with the result. * @param {string} [hash=window.location.hash] - Hash fragment of Url. */ AuthenticationContext.prototype.handleWindowCallback = function (hash) { // This is for regular javascript usage for redirect handling // need to make sure this is for callback if (hash == null) hash = window.location.hash; if (this.isCallback(hash)) { var requestInfo = this.getRequestInfo(hash); this.info('Returned from redirect url'); this.saveTokenFromHash(requestInfo); var token = null, callback = null; if ((requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) && window.parent) { // iframe call but same single page this.verbose('Window is in iframe'); callback = window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]; token = requestInfo.parameters[this.CONSTANTS.ACCESS_TOKEN] || requestInfo.parameters[this.CONSTANTS.ID_TOKEN]; } else if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) { callback = this.callback; token = requestInfo.parameters[this.CONSTANTS.ID_TOKEN]; } try { if (callback) callback(this._getItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION), token, this._getItem(this.CONSTANTS.STORAGE.ERROR)); } catch (err) { this.error('Error occurred in user defined callback function', err) } if (!this.popUp) { window.location.hash = ''; if (this.config.navigateToLoginRequestUrl) window.location.href = this._getItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST); } } }; /** * Constructs the authorization endpoint URL and returns it. * @ignore */ AuthenticationContext.prototype._getNavigateUrl = function (responseType, resource) { var tenant = 'common'; if (this.config.tenant) { tenant = this.config.tenant; } var urlNavigate = this.instance + tenant + '/oauth2/authorize' + this._serialize(responseType, this.config, resource) + this._addLibMetadata(); this.info('Navigate url:' + urlNavigate); return urlNavigate; }; /** * Returns the decoded id_token. * @ignore */ AuthenticationContext.prototype._extractIdToken = function (encodedIdToken) { // id token will be decoded to get the username var decodedToken = this._decodeJwt(encodedIdToken); if (!decodedToken) { return null; } try { var base64IdToken = decodedToken.JWSPayload; var base64Decoded = this._base64DecodeStringUrlSafe(base64IdToken); if (!base64Decoded) { this.info('The returned id_token could not be base64 url safe decoded.'); return null; } // ECMA script has JSON built-in support return JSON.parse(base64Decoded); } catch (err) { this.error('The returned id_token could not be decoded', err); } return null; }; /** * Decodes a string of data which has been encoded using base-64 encoding. * @ignore */ AuthenticationContext.prototype._base64DecodeStringUrlSafe = function (base64IdToken) { // html5 should support atob function for decoding base64IdToken = base64IdToken.replace(/-/g, '+').replace(/_/g, '/'); if (window.atob) { return decodeURIComponent(escape(window.atob(base64IdToken))); // jshint ignore:line } else { return decodeURIComponent(escape(this._decode(base64IdToken))); } }; //Take https://cdnjs.cloudflare.com/ajax/libs/Base64/0.3.0/base64.js and https://en.wikipedia.org/wiki/Base64 as reference. AuthenticationContext.prototype._decode = function (base64IdToken) { var codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; base64IdToken = String(base64IdToken).replace(/=+$/, ''); var length = base64IdToken.length; if (length % 4 === 1) { throw new Error('The token to be decoded is not correctly encoded.'); } var h1, h2, h3, h4, bits, c1, c2, c3, decoded = ''; for (var i = 0; i < length; i += 4) { //Every 4 base64 encoded character will be converted to 3 byte string, which is 24 bits // then 6 bits per base64 encoded character h1 = codes.indexOf(base64IdToken.charAt(i)); h2 = codes.indexOf(base64IdToken.charAt(i + 1)); h3 = codes.indexOf(base64IdToken.charAt(i + 2)); h4 = codes.indexOf(base64IdToken.charAt(i + 3)); // For padding, if last two are '=' if (i + 2 === length - 1) { bits = h1 << 18 | h2 << 12 | h3 << 6; c1 = bits >> 16 & 255; c2 = bits >> 8 & 255; decoded += String.fromCharCode(c1, c2); break; } // if last one is '=' else if (i + 1 === length - 1) { bits = h1 << 18 | h2 << 12 c1 = bits >> 16 & 255; decoded += String.fromCharCode(c1); break; } bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; // then convert to 3 byte chars c1 = bits >> 16 & 255; c2 = bits >> 8 & 255; c3 = bits & 255; decoded += String.fromCharCode(c1, c2, c3); } return decoded; }; /** * Decodes an id token into an object with header, payload and signature fields. * @ignore */ // Adal.node js crack function AuthenticationContext.prototype._decodeJwt = function (jwtToken) { if (this._isEmpty(jwtToken)) { return null; }; var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; var matches = idTokenPartsRegex.exec(jwtToken); if (!matches || matches.length < 4) { this.warn('The returned id_token is not parseable.'); return null; } var crackedToken = { header: matches[1], JWSPayload: matches[2], JWSSig: matches[3] }; return crackedToken; }; /** * Converts string to represent binary data in ASCII string format by translating it into a radix-64 representation and returns it * @ignore */ AuthenticationContext.prototype._convertUrlSafeToRegularBase64EncodedString = function (str) { return str.replace('-', '+').replace('_', '/'); }; /** * Serializes the parameters for the authorization endpoint URL and returns the serialized uri string. * @ignore */ AuthenticationContext.prototype._serialize = function (responseType, obj, resource) { var str = []; if (obj !== null) { str.push('?response_type=' + responseType); str.push('client_id=' + encodeURIComponent(obj.clientId)); if (resource) { str.push('resource=' + encodeURIComponent(resource)); } str.push('redirect_uri=' + encodeURIComponent(obj.redirectUri)); str.push('state=' + encodeURIComponent(obj.state)); if (obj.hasOwnProperty('slice')) { str.push('slice=' + encodeURIComponent(obj.slice)); } if (obj.hasOwnProperty('extraQueryParameter')) { str.push(obj.extraQueryParameter); } var correlationId = obj.correlationId ? obj.correlationId : this._guid(); str.push('client-request-id=' + encodeURIComponent(correlationId)); } return str.join('&'); }; /** * Parses the query string parameters into a key-value pair object. * @ignore */ AuthenticationContext.prototype._deserialize = function (query) { var match, pl = /\+/g, // Regex for replacing addition symbol with a space search = /([^&=]+)=([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, ' ')); }, obj = {}; match = search.exec(query); while (match) { obj[decode(match[1])] = decode(match[2]); match = search.exec(query); } return obj; }; /** * Converts decimal value to hex equivalent * @ignore */ AuthenticationContext.prototype._decimalToHex = function (number) { var hex = number.toString(16); while (hex.length < 2) { hex = '0' + hex; } return hex; } /** * Generates RFC4122 version 4 guid (128 bits) * @ignore */ /* jshint ignore:start */ AuthenticationContext.prototype._guid = function () { // RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or // pseudo-random numbers. // The algorithm is as follows: // Set the two most significant bits (bits 6 and 7) of the // clock_seq_hi_and_reserved to zero and one, respectively. // Set the four most significant bits (bits 12 through 15) of the // time_hi_and_version field to the 4-bit version number from // Section 4.1.3. Version4 // Set all the other bits to randomly (or pseudo-randomly) chosen // values. // UUID = time-low "-" time-mid "-"time-high-and-version "-"clock-seq-reserved and low(2hexOctet)"-" node // time-low = 4hexOctet // time-mid = 2hexOctet // time-high-and-version = 2hexOctet // clock-seq-and-reserved = hexOctet: // clock-seq-low = hexOctet // node = 6hexOctet // Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx // y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10 // y values are 8, 9, A, B var cryptoObj = window.crypto || window.msCrypto; // for IE 11 if (cryptoObj && cryptoObj.getRandomValues) { var buffer = new Uint8Array(16); cryptoObj.getRandomValues(buffer); //buffer[6] and buffer[7] represents the time_hi_and_version field. We will set the four most significant bits (4 through 7) of buffer[6] to represent decimal number 4 (UUID version number). buffer[6] |= 0x40; //buffer[6] | 01000000 will set the 6 bit to 1. buffer[6] &= 0x4f; //buffer[6] & 01001111 will set the 4, 5, and 7 bit to 0 such that bits 4-7 == 0100 = "4". //buffer[8] represents the clock_seq_hi_and_reserved field. We will set the two most significant bits (6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively. buffer[8] |= 0x80; //buffer[8] | 10000000 will set the 7 bit to 1. buffer[8] &= 0xbf; //buffer[8] & 10111111 will set the 6 bit to 0. return this._decimalToHex(buffer[0]) + this._decimalToHex(buffer[1]) + this._decimalToHex(buffer[2]) + this._decimalToHex(buffer[3]) + '-' + this._decimalToHex(buffer[4]) + this._decimalToHex(buffer[5]) + '-' + this._decimalToHex(buffer[6]) + this._decimalToHex(buffer[7]) + '-' + this._decimalToHex(buffer[8]) + this._decimalToHex(buffer[9]) + '-' + this._decimalToHex(buffer[10]) + this._decimalToHex(buffer[11]) + this._decimalToHex(buffer[12]) + this._decimalToHex(buffer[13]) + this._decimalToHex(buffer[14]) + this._decimalToHex(buffer[15]); } else { var guidHolder = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; var hex = '0123456789abcdef'; var r = 0; var guidResponse = ""; for (var i = 0; i < 36; i++) { if (guidHolder[i] !== '-' && guidHolder[i] !== '4') { // each x and y needs to be random r = Math.random() * 16 | 0; } if (guidHolder[i] === 'x') { guidResponse += hex[r]; } else if (guidHolder[i] === 'y') { // clock-seq-and-reserved first hex is filtered and remaining hex values are random r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0?? r |= 0x8; // set pos 3 to 1 as 1??? guidResponse += hex[r]; } else { guidResponse += guidHolder[i]; } } return guidResponse; } }; /* jshint ignore:end */ /** * Calculates the expires in value in milliseconds for the acquired token * @ignore */ AuthenticationContext.prototype._expiresIn = function (expires) { // if AAD did not send "expires_in" property, use default expiration of 3599 seconds, for some reason AAD sends 3599 as "expires_in" value instead of 3600 if (!expires) expires = 3599; return this._now() + parseInt(expires, 10); }; /** * Return the number of milliseconds since 1970/01/01 * @ignore */ AuthenticationContext.prototype._now = function () { return Math.round(new Date().getTime() / 1000.0); }; /** * Adds the hidden iframe for silent token renewal * @ignore */ AuthenticationContext.prototype._addAdalFrame = function (iframeId) { if (typeof iframeId === 'undefined') { return; } this.info('Add adal frame to document:' + iframeId); var adalFrame = document.getElementById(iframeId); if (!adalFrame) { if (document.createElement && document.documentElement && (window.opera || window.navigator.userAgent.indexOf('MSIE 5.0') === -1)) { var ifr = document.createElement('iframe'); ifr.setAttribute('id', iframeId); ifr.style.visibility = 'hidden'; ifr.style.position = 'absolute'; ifr.style.width = ifr.style.height = ifr.borderWidth = '0px'; adalFrame = document.getElementsByTagName('body')[0].appendChild(ifr); } else if (document.body && document.body.insertAdjacentHTML) { document.body.insertAdjacentHTML('beforeEnd', '<iframe name="' + iframeId + '" id="' + iframeId + '" style="display:none"></iframe>'); } if (window.frames && window.frames[iframeId]) { adalFrame = window.frames[iframeId]; } } return adalFrame; }; /** * Saves the key-value pair in the cache * @ignore */ AuthenticationContext.prototype._saveItem = function (key, obj) { if (this.config && this.config.cacheLocation && this.config.cacheLocation === 'localStorage') { if (!this._supportsLocalStorage()) { this.info('Local storage is not supported'); return false; } localStorage.setItem(key, obj); return true; } // Default as session storage if (!this._supportsSessionStorage()) { this.info('Session storage is not supported'); return false; } sessionStorage.setItem(key, obj); return true; }; /** * Searches the value for the given key in the cache * @ignore */ AuthenticationContext.prototype._getItem = function (key) { if (this.config && this.config.cacheLocation && this.config.cacheLocation === 'localStorage') { if (!this._supportsLocalStorage()) { this.info('Local storage is not supported'); return null; } return localStorage.getItem(key); } // Default as session storage if (!this._supportsSessionStorage()) { this.info('Session storage is not supported'); return null; } return sessionStorage.getItem(key); }; /** * Returns true if browser supports localStorage, false otherwise. * @ignore */ AuthenticationContext.prototype._supportsLocalStorage = function () { try { if (!window.localStorage) return false; // Test availability window.localStorage.setItem('storageTest', 'A'); // Try write if (window.localStorage.getItem('storageTest') != 'A') return false; // Test read/write window.localStorage.removeItem('storageTest'); // Try delete if (window.localStorage.getItem('storageTest')) return false; // Test delete return true; // Success } catch (e) { return false; } }; /** * Returns true if browser supports sessionStorage, false otherwise. * @ignore */ AuthenticationContext.prototype._supportsSessionStorage = function () { try { if (!window.sessionStorage) return false; // Test availability window.sessionStorage.setItem('storageTest', 'A'); // Try write if (window.sessionStorage.getItem('storageTest') != 'A') return false; // Test read/write window.sessionStorage.removeItem('storageTest'); // Try delete if (window.sessionStorage.getItem('storageTest')) return false; // Test delete return true; // Success } catch (e) { return false; } }; /** * Returns a cloned copy of the passed object. * @ignore */ AuthenticationContext.prototype._cloneConfig = function (obj) { if (null === obj || 'object' !== typeof obj) { return obj; } var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; } } return copy; }; /** * Adds the library version and returns it. * @ignore */ AuthenticationContext.prototype._addLibMetadata = function () { // x-client-SKU // x-client-Ver return '&x-client-SKU=Js&x-client-Ver=' + this._libVersion(); }; /** * Checks the Logging Level, constructs the Log message and logs it. Users need to implement/override this method to turn on Logging. * @param {number} level - Level can be set 0,1,2 and 3 which turns on 'error', 'warning', 'info' or 'verbose' level logging respectively. * @param {string} message - Message to log. * @param {string} error - Error to log. */ AuthenticationContext.prototype.log = function (level, message, error) { if (level <= Logging.level) { var timestamp = new Date().toUTCString(); var formattedMessage = ''; if (this.config.correlationId) formattedMessage = timestamp + ':' + this.config.correlationId + '-' + this._libVersion() + '-' + this.CONSTANTS.LEVEL_STRING_MAP[level] + ' ' + message; else formattedMessage = timestamp + ':' + this._libVersion() + '-' + this.CONSTANTS.LEVEL_STRING_MAP[level] + ' ' + message; if (error) { formattedMessage += '\nstack:\n' + error.stack; } Logging.log(formattedMessage); } }; /** * Logs messages when Logging Level is set to 0. * @param {string} message - Message to log. * @param {string} error - Error to log. */ AuthenticationContext.prototype.error = function (message, error) { this.log(this.CONSTANTS.LOGGING_LEVEL.ERROR, message, error); }; /** * Logs messages when Logging Level is set to 1. * @param {string} message - Message to log. */ AuthenticationContext.prototype.warn = function (message) { this.log(this.CONSTANTS.LOGGING_LEVEL.WARN, message, null); }; /** * Logs messages when Logging Level is set to 2. * @param {string} message - Message to log. */ AuthenticationContext.prototype.info = function (message) { this.log(this.CONSTANTS.LOGGING_LEVEL.INFO, message, null); }; /** * Logs messages when Logging Level is set to 3. * @param {string} message - Message to log. */ AuthenticationContext.prototype.verbose = function (message) { this.log(this.CONSTANTS.LOGGING_LEVEL.VERBOSE, message, null); }; /** * Returns the library version. * @ignore */ AuthenticationContext.prototype._libVersion = function () { return '1.0.15'; }; /** * Returns a reference of Authentication Context as a result of a require call. * @ignore */ if (typeof module !== 'undefined' && module.exports) { module.exports = AuthenticationContext; module.exports.inject = function (conf) { return new AuthenticationContext(conf); }; } return AuthenticationContext; }()); /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__authConstants__ = __webpack_require__(0); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. const subscriptionId = "<your-subscription-id>"; __WEBPACK_IMPORTED_MODULE_0__authConstants__["a" /* authManager */].getToken().then((t) => { let req = { method: "GET", credentials: "include", headers: { "accept-language": "en-US", "x-ms-client-request-id": "9e932adc-7b1c-4d4b-aab6-984f2923bfa5", "Content-Type": "application/json; charset=utf-8", "authorization": `Bearer ${t}` } }; return fetch(`https://management.azure.com/subscriptions/${subscriptionId}/providers/Microsoft.Storage/storageAccounts?api-version=2015-06-15`, req); }).then((res) => { return res.json(); }).then((parsedResponse) => { document.write(JSON.stringify(parsedResponse, null, 2)); console.dir(parsedResponse, { depth: null }); }).catch((err) => { document.write(JSON.stringify(err, null, 2)); console.dir(err, { depth: null }); }); /***/ }) /******/ ]); //# sourceMappingURL=bundle-sample.js.map
App.controller('AdminNodesController', /*@ngInject*/ function ($scope, Nodes, OrderByMixin, lodash) { angular.extend($scope, OrderByMixin); $scope.nodes = {}; $scope.currentId = []; $scope.types = []; $scope.newNode = {}; $scope.orderBy = 'name'; Nodes.getData().then(function(data) { $scope.nodes = lodash.keyBy(data.data.nodes, 'nodeId'); $scope.currentId = data.data.currentId; $scope.types = data.data.types; }); $scope.addNode = function(node) { Nodes.add(node).then(function(newNode) { $scope.nodes[newNode.nodeId] = newNode.data; }); }; $scope.edit = function(node) { Nodes.edit(node).then(function(newNode) { $scope.nodes[newNode.data.nodeId] = newNode.data; $scope.newNode = {}; }); }; $scope.removeOption = function(options, key) { delete options[key]; }; $scope.addOption = function(node) { var key = prompt("Key"); var value = prompt("Value"); if (Array.isArray(node.options)) { node.options = {}; } node.options[key] = value; }; $scope.editOption = function(options, key) { var value = prompt("Value"); options[key] = value; }; $scope.remove = function(node) { Nodes.remove(node).then(function() { delete $scope.nodes[node.nodeId]; }); }; });
(function() { var Ext = window.Ext4 || window.Ext; /** * shows days remaining for timebox */ Ext.define('TimeboxEnd', { extend: 'Gauge', alias:'widget.statsbannertimeboxend', requires: [ 'Rally.util.Timebox', 'Rally.util.Colors' ], tpl: [ '<div class="expanded-widget">', '<div class="stat-title">{type} End</div>', '<div class="stat-metric">', '<div class="metric-chart"></div>', '<div class="metric-chart-text">', '{remaining}', '</div>', '<div class="metric-subtext">days left of {workdays}</div>', '</div>', '</div>', '<div class="collapsed-widget">', '<div class="stat-title">{type} End</div>', '<div class="stat-metric">{remaining}<span class="stat-metric-secondary"> days</span></div>', '</div>' ], config: { data: { type: 'Iteration', remaining: 0, workdays: 0 } }, getChartEl: function() { return this.getEl().down('.metric-chart'); }, _getRenderData: function() { return { type: Ext.String.capitalize(this.getContext().getTimeboxScope().getType()), remaining: this.totalDays - this.day - 1, workdays: this.totalDays }; }, onRender: function () { this.callParent(arguments); var renderData = this._getRenderData(); this.update(renderData); this.refreshChart(this._getChartConfig(renderData)); }, _getChartConfig: function (renderData) { var decimal = renderData.remaining / renderData.workdays, percentLeft = decimal < 1 ? Math.round(decimal * 100) : 0, color = Rally.util.Colors.cyan; if (renderData.total === 0) { color = Rally.util.Colors.grey1; } else if (percentLeft === 0) { color = renderData.accepted === renderData.total ? Rally.util.Colors.lime : Rally.util.Colors.blue; } else if (percentLeft <= 25) { color = Rally.util.Colors.blue; } return { chartData: { series: [{ data: [ { name: 'Days Done', y: 100 - percentLeft, color: color }, { name: 'Days Left', y: percentLeft, color: Rally.util.Colors.grey1 } ] }] } }; } }); })();
;(function(root, factory) { if (typeof exports === "object") { // CommonJS module.exports = factory() } else if (typeof define === "function" && define.amd) { // AMD define([], factory) } else { // Global Variables root.Pjax = factory() } }(this, function() { "use strict"; function newUid() { return (new Date().getTime()) } var Pjax = function(options) { this.firstrun = true this.options = options this.options.elements = this.options.elements || "a[href], form[action]" this.options.selectors = this.options.selectors || ["title", ".js-Pjax"] this.options.switches = this.options.switches || {} this.options.switchesOptions = this.options.switchesOptions || {} this.options.history = this.options.history || true this.options.currentUrlFullReload = this.options.currentUrlFullReload || false this.options.analytics = this.options.analytics || function(options) { // options.backward or options.foward can be true or undefined // by default, we do track back/foward hit // Piwik if(window._paq){ _paq.push(['setDocumentTitle', document.title]); _paq.push(['setCustomUrl', window.location.href]); _paq.push(['trackPageView']); } // https://productforums.google.com/forum/#!topic/analytics/WVwMDjLhXYk if (window._gaq) { _gaq.push(["_trackPageview"]) } if (window.ga) { ga("send", "pageview", {"page": window.location.href, "title": document.title}) } } this.options.scrollTo = this.options.scrollTo || 0 this.options.debug = this.options.debug || false this.maxUid = this.lastUid = newUid() // we can’t replace body.outerHTML or head.outerHTML // it create a bug where new body or new head are created in the dom // if you set head.outerHTML, a new body tag is appended, so the dom get 2 body // & it break the switchFallback which replace head & body if (!this.options.switches.head) { this.options.switches.head = this.switchElementsAlt } if (!this.options.switches.body) { this.options.switches.body = this.switchElementsAlt } this.log("Pjax options", this.options) if (typeof options.analytics !== "function") { options.analytics = function() {} } this.parseDOM(document) Pjax.on(window, "popstate", function(st) { if (st.state) { var opt = Pjax.clone(this.options) opt.url = st.state.url opt.title = st.state.title opt.history = false if (st.state.uid < this.lastUid) { opt.backward = true } else { opt.forward = true } this.lastUid = st.state.uid // @todo implement history cache here, based on uid this.loadUrl(st.state.url, opt) } }.bind(this)) } // make internal methods public Pjax.isSupported = function() { // Borrowed wholesale from https://github.com/defunkt/jquery-pjax return window.history && window.history.pushState && window.history.replaceState && // pushState isn’t reliable on iOS until 5. !navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/) } Pjax.forEachEls = function(els, fn, context) { if (els instanceof HTMLCollection || els instanceof NodeList) { return Array.prototype.forEach.call(els, fn, context) } // assume simple dom element fn.call(context, els) } Pjax.on = function(els, events, listener, useCapture) { events = (typeof events === "string" ? events.split(" ") : events) events.forEach(function(e) { Pjax.forEachEls(els, function(el) { el.addEventListener(e, listener, useCapture) }) }, this) } Pjax.off = function(els, events, listener, useCapture) { events = (typeof events === "string" ? events.split(" ") : events) events.forEach(function(e) { Pjax.forEachEls(els, function(el) { el.removeEventListener(e, listener, useCapture) }) }, this) } Pjax.trigger = function(els, events) { events = (typeof events === "string" ? events.split(" ") : events) events.forEach(function(e) { var event if (document.createEvent) { event = document.createEvent("HTMLEvents") event.initEvent(e, true, true) } else { event = document.createEventObject() event.eventType = e } event.eventName = e if (document.createEvent) { Pjax.forEachEls(els, function(el) { el.dispatchEvent(event) }) } else { Pjax.forEachEls(els, function(el) { el.fireEvent("on" + event.eventType, event) }) } }, this) } Pjax.clone = function(obj) { if (null === obj || "object" != typeof obj) { return obj } var copy = obj.constructor() for (var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr] } } return copy } // Finds and executes scripts (used for newly added elements) // Needed since innerHTML does not run scripts Pjax.executeScripts = function(el) { // console.log("going to execute scripts for ", el) Pjax.forEachEls(el.querySelectorAll("script"), function(script) { if (!script.type || script.type.toLowerCase() === "text/javascript") { if (script.parentNode) { script.parentNode.removeChild(script) } Pjax.evalScript(script) } }) } Pjax.evalScript = function(el) { // console.log("going to execute script", el) var code = (el.text || el.textContent || el.innerHTML || "") , head = document.querySelector("head") || document.documentElement , script = document.createElement("script") if (code.match("document.write")) { if (console && console.log) { console.log("Script contains document.write. Can’t be executed correctly. Code skipped ", el) } return false } script.type = "text/javascript" try { script.appendChild(document.createTextNode(code)) } catch (e) { // old IEs have funky script nodes script.text = code } // execute head.insertBefore(script, head.firstChild) head.removeChild(script) // avoid pollution return true } Pjax.prototype = { log: function() { if (this.options.debug && console) { if (typeof console.log === "function") { console.log.apply(console, arguments); } // ie is weird else if (console.log) { console.log(arguments); } } } , getElements: function(el) { return el.querySelectorAll(this.options.elements) } , parseDOM: function(el) { Pjax.forEachEls(this.getElements(el), function(el) { switch (el.tagName.toLowerCase()) { case "a": this.attachLink(el) break case "form": // todo this.log("Pjax doesnt support <form> yet. TODO :)") break default: throw "Pjax can only be applied on <a> or <form> submit" } }, this) } , attachLink: function(el) { Pjax.on(el, "click", function(event) { //var el = event.currentTarget // Don’t break browser special behavior on links (like page in new window) if (event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { return -1 } // Ignore external links. if (el.protocol !== window.location.protocol || el.host !== window.location.host) { return -2 } // Ignore anchors on the same page if (el.pathname === location.pathname && el.hash.length > 0) { return -3 } // Ignore anchors on the same page if (el.hash && el.href.replace(el.hash, "") === location.href.replace(location.hash, "")) { return -4 } // Ignore empty anchor "foo.html#" if (el.href === location.href + "#") { return -5 } // Ignore target=_blank if(el.target.toLowerCase() === "_blank"){ return -7 } // fire onClick event var clickEvent = new CustomEvent("pjax:click", { "detail": {"event" : event, "element" : el}, "cancelable":true }); document.dispatchEvent(clickEvent); // Click-Event was canceled, so cancle request if(clickEvent.defaultPrevented){ return -8 } event.preventDefault() if (this.options.currentUrlFullReload) { if (el.href === window.location.href) { window.location.reload() return -6 } } this.loadUrl(el.href, Pjax.clone(this.options)) }.bind(this)) Pjax.on(el, "keyup", function(event) { this.log("pjax todo") // todo handle a link hitted by keyboard (enter/space) when focus is on it }.bind(this)) } , forEachSelectors: function(cb, context, DOMcontext) { DOMcontext = DOMcontext || document this.options.selectors.forEach(function(selector) { Pjax.forEachEls(DOMcontext.querySelectorAll(selector), cb, context) }) } , switchSelectors: function(selectors, fromEl, toEl, options) { selectors.forEach(function(selector) { var newEls = fromEl.querySelectorAll(selector) var oldEls = toEl.querySelectorAll(selector) this.log("Pjax switch", selector, newEls, oldEls) if (newEls.length !== oldEls.length) { // Pjax.forEachEls(newEls, function(el) { // this.log("newEl", el, el.outerHTML) // }, this) // Pjax.forEachEls(oldEls, function(el) { // this.log("oldEl", el, el.outerHTML) // }, this) throw "DOM doesn’t look the same on new loaded page: ’" + selector + "’ - new " + newEls.length + ", old " + oldEls.length } Pjax.forEachEls(newEls, function(newEl, i) { var oldEl = oldEls[i] this.log("newEl", newEl, "oldEl", oldEl) if (this.options.switches[selector]) { this.options.switches[selector].bind(this)(oldEl, newEl, options, this.options.switchesOptions[selector]) } else { Pjax.switches.outerHTML.bind(this)(oldEl, newEl, options) } }, this) }, this) } // too much problem with the code below // + it’s too dangerous // , switchFallback: function(fromEl, toEl) { // this.switchSelectors(["head", "body"], fromEl, toEl) // // execute script when DOM is like it should be // Pjax.executeScripts(document.querySelector("head")) // Pjax.executeScripts(document.querySelector("body")) // } , latestChance: function(href) { window.location = href } , onSwitch: function() { Pjax.trigger(window, "resize scroll") } , loadContent: function(html, options) { var tmpEl = document.implementation.createHTMLDocument("") // parse HTML attributes to copy them // since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>) , htmlRegex = /<html[^>]+>/gi , htmlAttribsRegex = /\s?[a-z:]+(?:\=(?:\'|\")[^\'\">]+(?:\'|\"))*/gi , matches = html.match(htmlRegex) if (matches && matches.length) { matches = matches[0].match(htmlAttribsRegex) if (matches.length) { matches.shift() matches.forEach(function(htmlAttrib) { var attr = htmlAttrib.trim().split("=") tmpEl.documentElement.setAttribute(attr[0], attr[1].slice(1, -1)) }) } } tmpEl.documentElement.innerHTML = html this.log("load content", tmpEl.documentElement.attributes, tmpEl.documentElement.innerHTML.length) // try { this.switchSelectors(this.options.selectors, tmpEl, document, options) // FF bug: Won’t autofocus fields that are inserted via JS. // This behavior is incorrect. So if theres no current focus, autofocus // the last field. // // http://www.w3.org/html/wg/drafts/html/master/forms.html var autofocusEl = Array.prototype.slice.call(document.querySelectorAll("[autofocus]")).pop() if (autofocusEl && document.activeElement !== autofocusEl) { autofocusEl.focus(); } // execute scripts when DOM have been completely updated this.options.selectors.forEach(function(selector) { Pjax.forEachEls(document.querySelectorAll(selector), function(el) { Pjax.executeScripts(el) }) }) // } // catch(e) { // if (this.options.debug) { // this.log("Pjax switch fail: ", e) // } // this.switchFallback(tmpEl, document) // } } , doRequest: function(location, callback) { var request = new XMLHttpRequest() request.onreadystatechange = function() { if (request.readyState === 4 && request.status === 200) { callback(request.responseText) } else if (request.readyState === 4 && (request.status === 404 || request.status === 500)){ callback(false) } } request.open("GET", location + (!/[?&]/.test(location) ? "?" : "&") + (new Date().getTime()), true) request.setRequestHeader("X-Requested-With", "XMLHttpRequest") request.send(null) } , loadUrl: function(href, options) { this.log("load href", href, options) Pjax.trigger(document, "pjax:send", options); // Do the request this.doRequest(href, function(html) { // Fail if unable to load HTML via AJAX if (html === false) { Pjax.trigger(document,"pjax:complete pjax:error", options) return } // Clear out any focused controls before inserting new page contents. document.activeElement.blur() try { this.loadContent(html, options) } catch (e) { if (!this.options.debug) { if (console && console.error) { console.error("Pjax switch fail: ", e) } this.latestChance(href) return } else { throw e } } if (options.history) { if (this.firstrun) { this.lastUid = this.maxUid = newUid() this.firstrun = false window.history.replaceState({ "url": window.location.href , "title": document.title , "uid": this.maxUid } , document.title) } // Update browser history this.lastUid = this.maxUid = newUid() window.history.pushState({ "url": href , "title": options.title , "uid": this.maxUid } , options.title , href) } this.forEachSelectors(function(el) { this.parseDOM(el) }, this) // Fire Events Pjax.trigger(document,"pjax:complete pjax:success", options) options.analytics() // Scroll page to top on new page load if (options.scrollTo !== false) { if (options.scrollTo.length > 1) { window.scrollTo(options.scrollTo[0], options.scrollTo[1]) } else { window.scrollTo(0, options.scrollTo) } } }.bind(this)) } } Pjax.switches = { outerHTML: function(oldEl, newEl, options) { oldEl.outerHTML = newEl.outerHTML this.onSwitch() } , innerHTML: function(oldEl, newEl, options) { oldEl.innerHTML = newEl.innerHTML oldEl.className = newEl.className this.onSwitch() } , sideBySide: function(oldEl, newEl, options, switchOptions) { var forEach = Array.prototype.forEach , elsToRemove = [] , elsToAdd = [] , fragToAppend = document.createDocumentFragment() // height transition are shitty on safari // so commented for now (until I found something ?) // , relevantHeight = 0 , animationEventNames = "animationend webkitAnimationEnd MSAnimationEnd oanimationend" , animatedElsNumber = 0 , sexyAnimationEnd = function(e) { if (e.target != e.currentTarget) { // end triggered by an animation on a child return } animatedElsNumber-- if (animatedElsNumber <= 0 && elsToRemove) { elsToRemove.forEach(function(el) { // browsing quickly can make the el // already removed by last page update ? if (el.parentNode) { el.parentNode.removeChild(el) } }) elsToAdd.forEach(function(el) { el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "") el.removeAttribute("data-pjax-classes") // Pjax.off(el, animationEventNames, sexyAnimationEnd, true) }) elsToAdd = null // free memory elsToRemove = null // free memory // assume the height is now useless (avoid bug since there is overflow hidden on the parent) // oldEl.style.height = "auto" // this is to trigger some repaint (example: picturefill) this.onSwitch() //Pjax.trigger(window, "scroll") } }.bind(this) // Force height to be able to trigger css animation // here we get the relevant height // oldEl.parentNode.appendChild(newEl) // relevantHeight = newEl.getBoundingClientRect().height // oldEl.parentNode.removeChild(newEl) // oldEl.style.height = oldEl.getBoundingClientRect().height + "px" switchOptions = switchOptions || {} forEach.call(oldEl.childNodes, function(el) { elsToRemove.push(el) if (el.classList && !el.classList.contains("js-Pjax-remove")) { // for fast switch, clean element that just have been added, & not cleaned yet. if (el.hasAttribute("data-pjax-classes")) { el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "") el.removeAttribute("data-pjax-classes") } el.classList.add("js-Pjax-remove") if (switchOptions.callbacks && switchOptions.callbacks.removeElement) { switchOptions.callbacks.removeElement(el) } if (switchOptions.classNames) { el.className += " " + switchOptions.classNames.remove + " " + (options.backward ? switchOptions.classNames.backward : switchOptions.classNames.forward) } animatedElsNumber++ Pjax.on(el, animationEventNames, sexyAnimationEnd, true) } }) forEach.call(newEl.childNodes, function(el) { if (el.classList) { var addClasses = "" if (switchOptions.classNames) { addClasses = " js-Pjax-add " + switchOptions.classNames.add + " " + (options.backward ? switchOptions.classNames.forward : switchOptions.classNames.backward) } if (switchOptions.callbacks && switchOptions.callbacks.addElement) { switchOptions.callbacks.addElement(el) } el.className += addClasses el.setAttribute("data-pjax-classes", addClasses) elsToAdd.push(el) fragToAppend.appendChild(el) animatedElsNumber++ Pjax.on(el, animationEventNames, sexyAnimationEnd, true) } }) // pass all className of the parent oldEl.className = newEl.className oldEl.appendChild(fragToAppend) // oldEl.style.height = relevantHeight + "px" } } if (Pjax.isSupported()) { return Pjax } // if there isn’t required browser functions, returning stupid api else { var stupidPjax = function() {} for (var key in Pjax.prototype) { if (Pjax.prototype.hasOwnProperty(key) && typeof Pjax.prototype[key] === "function") { stupidPjax[key] = stupidPjax } } return stupidPjax } }));
// corresponding video for the code // https://www.youtube.com/watch?v=BMUiFMZr7vk // functions are values in javascript // they are good for composition // functions allow us to compose // which leads to code reuse // example var triple = function triple(x) { return x * 3 } var waffle = triple // sample array animals var animals = [ {name : "Fluffy", species: "cat"}, {name : "Kutta", species : "dog"}, {name : "Kuttiya", species: "dog"}, {name : "Tota", species: "parrot"}, {name : "Billa", species: "cat"}, {name : "Bhaeriya", species: "wolf"} ] // stuff about functional programming // normal non functional way to filter // using for loop /* var dogs = []; for (var i = 0; i < animals.length; i++) { if (animals[i].species == "dog") { dogs.push(animals[i]); } } Output [ { name: 'Kutta', species: 'dog' }, { name: 'Kuttiya', species: 'dog' } ] */ var isDog = function (animal) { return animal.species == "dog" } // better functional way is to use the filter function var dogs = animals.filter(isDog); console.log(dogs);
import { combineReducers } from 'redux'; import layoutReducer from './layout_reducer'; const rootReducer = combineReducers({ layouts: layoutReducer }); export default rootReducer;
import React, {Component, PropTypes} from 'react'; import keycode from 'keycode'; import {fade, emphasize} from '../utils/colorManipulator'; import EnhancedButton from '../internal/EnhancedButton'; import DeleteIcon from '../svg-icons/navigation/cancel'; function getStyles(props, context, state) { const {chip} = context.muiTheme; const backgroundColor = props.backgroundColor || chip.backgroundColor; const focusColor = emphasize(backgroundColor, 0.08); const pressedColor = emphasize(backgroundColor, 0.12); return { avatar: { marginRight: -4, }, deleteIcon: { color: (state.deleteHovered) ? fade(chip.deleteIconColor, 0.4) : chip.deleteIconColor, cursor: 'pointer', margin: '4px 4px 0px -8px', }, label: { color: props.labelColor || chip.textColor, fontSize: chip.fontSize, fontWeight: chip.fontWeight, lineHeight: '32px', paddingLeft: 12, paddingRight: 12, userSelect: 'none', whiteSpace: 'nowrap', }, root: { backgroundColor: state.clicked ? pressedColor : (state.focused || state.hovered) ? focusColor : backgroundColor, borderRadius: 16, boxShadow: state.clicked ? chip.shadow : null, cursor: props.onTouchTap ? 'pointer' : 'default', display: 'flex', whiteSpace: 'nowrap', width: 'fit-content', }, }; } class Chip extends Component { static propTypes = { /** * Override the background color of the chip. */ backgroundColor: PropTypes.string, /** * Used to render elements inside the Chip. */ children: PropTypes.node, /** * CSS `className` of the root element. */ className: PropTypes.node, /** * Override the label color. */ labelColor: PropTypes.string, /** * Override the inline-styles of the label. */ labelStyle: PropTypes.object, /** @ignore */ onBlur: PropTypes.func, /** @ignore */ onFocus: PropTypes.func, /** @ignore */ onKeyDown: PropTypes.func, /** @ignore */ onKeyboardFocus: PropTypes.func, /** @ignore */ onMouseDown: PropTypes.func, /** @ignore */ onMouseEnter: PropTypes.func, /** @ignore */ onMouseLeave: PropTypes.func, /** @ignore */ onMouseUp: PropTypes.func, /** * Callback function fired when the delete icon is clicked. If set, the delete icon will be shown. * @param {object} event `touchTap` event targeting the element. */ onRequestDelete: PropTypes.func, /** @ignore */ onTouchEnd: PropTypes.func, /** @ignore */ onTouchStart: PropTypes.func, /** * Callback function fired when the `Chip` element is touch-tapped. * * @param {object} event TouchTap event targeting the element. */ onTouchTap: PropTypes.func, /** * Override the inline-styles of the root element. */ style: PropTypes.object, }; static defaultProps = { onBlur: () => {}, onFocus: () => {}, onKeyDown: () => {}, onKeyboardFocus: () => {}, onMouseDown: () => {}, onMouseEnter: () => {}, onMouseLeave: () => {}, onMouseUp: () => {}, onTouchEnd: () => {}, onTouchStart: () => {}, }; static contextTypes = {muiTheme: PropTypes.object.isRequired}; state = { clicked: false, deleteHovered: false, focused: false, hovered: false, }; handleBlur = (event) => { this.setState({clicked: false, focused: false}); this.props.onBlur(event); }; handleFocus = (event) => { if (this.props.onTouchTap || this.props.onRequestDelete) { this.setState({focused: true}); } this.props.onFocus(event); }; handleKeyboardFocus = (event, keyboardFocused) => { if (keyboardFocused) { this.handleFocus(); this.props.onFocus(event); } else { this.handleBlur(); } this.props.onKeyboardFocus(event, keyboardFocused); }; handleKeyDown = (event) => { if (keycode(event) === 'backspace') { event.preventDefault(); if (this.props.onRequestDelete) { this.props.onRequestDelete(event); } } this.props.onKeyDown(event); }; handleMouseDown = (event) => { // Only listen to left clicks if (event.button === 0) { event.stopPropagation(); if (this.props.onTouchTap) { this.setState({clicked: true}); } } this.props.onMouseDown(event); }; handleMouseEnter = (event) => { if (this.props.onTouchTap) { this.setState({hovered: true}); } this.props.onMouseEnter(event); }; handleMouseEnterDeleteIcon = () => { this.setState({deleteHovered: true}); }; handleMouseLeave = (event) => { this.setState({ clicked: false, hovered: false, }); this.props.onMouseLeave(event); }; handleMouseLeaveDeleteIcon = () => { this.setState({deleteHovered: false}); }; handleMouseUp = (event) => { this.setState({clicked: false}); this.props.onMouseUp(event); }; handleTouchTapDeleteIcon = (event) => { // Stop the event from bubbling up to the `Chip` event.stopPropagation(); this.props.onRequestDelete(event); }; handleTouchEnd = (event) => { this.setState({clicked: false}); this.props.onTouchEnd(event); }; handleTouchStart = (event) => { event.stopPropagation(); if (this.props.onTouchTap) { this.setState({clicked: true}); } this.props.onTouchStart(event); }; render() { const buttonEventHandlers = { onBlur: this.handleBlur, onFocus: this.handleFocus, onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave, onMouseUp: this.handleMouseUp, onTouchEnd: this.handleTouchEnd, onTouchStart: this.handleTouchStart, onKeyboardFocus: this.handleKeyboardFocus, }; const {prepareStyles} = this.context.muiTheme; const styles = getStyles(this.props, this.context, this.state); const { children: childrenProp, style, className, labelStyle, labelColor, // eslint-disable-line no-unused-vars,prefer-const backgroundColor, // eslint-disable-line no-unused-vars,prefer-const onRequestDelete, // eslint-disable-line no-unused-vars,prefer-const ...other } = this.props; const deletable = this.props.onRequestDelete; let avatar = null; const deleteIcon = deletable ? <DeleteIcon color={styles.deleteIcon.color} style={styles.deleteIcon} onTouchTap={this.handleTouchTapDeleteIcon} onMouseEnter={this.handleMouseEnterDeleteIcon} onMouseLeave={this.handleMouseLeaveDeleteIcon} /> : null; let children = childrenProp; const childCount = React.Children.count(children); // If the first child is an avatar, extract it and style it if (childCount > 1) { children = React.Children.toArray(children); if (React.isValidElement(children[0]) && children[0].type.muiName === 'Avatar') { avatar = children.shift(); avatar = React.cloneElement(avatar, { style: Object.assign(styles.avatar, avatar.props.style), size: 32, }); } } return ( <EnhancedButton {...other} {...buttonEventHandlers} className={className} containerElement="div" // Firefox doesn't support nested buttons disableTouchRipple={true} disableFocusRipple={true} style={Object.assign(styles.root, style)} > {avatar} <span style={prepareStyles(Object.assign(styles.label, labelStyle))}> {children} </span> {deleteIcon} </EnhancedButton> ); } } export default Chip;
const session = require('express-session'), bodyParser = require('body-parser'), express = require("express"), app = express(), urlencodedParser = bodyParser.urlencoded({ extended: false }); app.use(require("body-parser").json()); app.use(express.static("public")); for (let k in data) { app.delete('/' + data[k] + '/:id', eval(data[k]).DELETE); app.get('/' + data[k] + '/', eval(data[k]).GET); app.get('/' + data[k] + '/:id', eval(data[k]).GET); app.post('/' + data[k] + '/', urlencodedParser, eval(data[k]).POST); app.put('/' + data[k], urlencodedParser, eval(data[k]).PUT); } app.listen({ type: 'http', port: '8888', host: '127.0.0.1', protocol: 'http' });
/** * DevExtreme (integration/angular/components.js) * Version: 16.2.5 * Build date: Mon Feb 27 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ "use strict"; var $ = require("jquery"), ngModule = require("./module"); ngModule.service("dxDigestCallbacks", ["$rootScope", function($rootScope) { var begin = $.Callbacks(), end = $.Callbacks(); var digestPhase = false; $rootScope.$watch(function() { if (digestPhase) { return } digestPhase = true; begin.fire(); $rootScope.$$postDigest(function() { digestPhase = false; end.fire() }) }); return { begin: { add: function(callback) { if (digestPhase) { callback() } begin.add(callback) }, remove: begin.remove }, end: end } }]);
// Do this as the first thing so that any code reading it knows the right env. process.env.BABEL_ENV = 'production'; process.env.NODE_ENV = 'production'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', err => { throw err; }); // Ensure environment variables are read. require('../config/env'); const fs = require('fs'); const chalk = require('chalk'); const webpack = require('webpack'); const serverConfig = require('../config/webpack.config.server.prod'); const paths = require('../config/paths'); const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); // Warn and crash if required files are missing if (!checkRequiredFiles([paths.serverIndexJs])) { process.exit(1); } // Create the production build and print the deployment instructions. function buildServer() { console.log('Creating an optimized server production build...'); let compiler = webpack(serverConfig); return new Promise((resolve, reject) => { compiler.run((err, stats) => { if (err) { return reject(err); } const messages = formatWebpackMessages(stats.toJson({}, true)); if (messages.errors.length) { return reject(new Error(messages.errors.join('\n\n'))); } if (process.env.CI && messages.warnings.length) { console.log( chalk.yellow( '\nTreating warnings as errors because process.env.CI = true.\n' + 'Most CI servers set it automatically.\n' ) ); return reject(new Error(messages.warnings.join('\n\n'))); } return resolve({ stats, warnings: messages.warnings, }); }); }); } if ( fs.exists(paths.appBuild + '/server.js', isFileExist => { if (isFileExist) { fs.unlinkSync(paths.appBuild + '/server.js'); } buildServer(); }) );
8.0-alpha3:146ab886922b4588872062d7e07480518020c90f072a1befdeea86178fb80d9c 8.0-alpha4:3750702f6f026215b2c1019e41559f79a0c7a37135e22f1dfaedc124df796b0f 8.0-alpha5:3750702f6f026215b2c1019e41559f79a0c7a37135e22f1dfaedc124df796b0f 8.0-alpha6:3750702f6f026215b2c1019e41559f79a0c7a37135e22f1dfaedc124df796b0f 8.0-alpha7:cc1c2680110e0c2545a884dc64fe7eb160041c9983754ba59ce4747dc754cd4f 8.0-alpha8:864a909bd6daccd3eacf268b41bdea6709f38bccabf5ac955869fcdf4313c133 8.0-alpha9:75de09bf248e0a945d10f1fb9032a7af30c420d1187e05ddd108a904a5b15d95 8.0-alpha10:75de09bf248e0a945d10f1fb9032a7af30c420d1187e05ddd108a904a5b15d95 8.0-alpha11:75de09bf248e0a945d10f1fb9032a7af30c420d1187e05ddd108a904a5b15d95 8.0-alpha12:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0-alpha13:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-alpha14:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-alpha15:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta1:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta2:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta3:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta4:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta6:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta7:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta9:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta10:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta11:e51ac6a0d42c8a0d90e09181809351d4dbfa92579c2536faee88dcbecc170a63 8.0.0-beta12:71dd7fa0e12ba73d5e65ab4cc7ecb6de2acf0aebfa9c183d6bcb348be693c2ad 8.0.0-beta13:71dd7fa0e12ba73d5e65ab4cc7ecb6de2acf0aebfa9c183d6bcb348be693c2ad 8.0.0-beta14:71dd7fa0e12ba73d5e65ab4cc7ecb6de2acf0aebfa9c183d6bcb348be693c2ad 8.0.0-beta15:54c43590959f28663e9d8ec204ac760b7d2784e4315539bbe20a1818109fafa6 8.0.0-beta16:54c43590959f28663e9d8ec204ac760b7d2784e4315539bbe20a1818109fafa6 8.0.0-rc1:54c43590959f28663e9d8ec204ac760b7d2784e4315539bbe20a1818109fafa6 8.0.0-rc2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.0-rc3:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.0-rc4:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.3:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.4:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.5:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.6:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.0-beta1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.0-beta2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.0-rc1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.3:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.4:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.5:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.6:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.7:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.8:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.9:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.10:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.0-beta1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.0-beta2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.0-beta3:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.0-rc1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.0-rc2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.3:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.4:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.5:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.6:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.3.0-alpha1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.3.0-beta1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.3.0-rc1:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.7:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.3.0-rc2:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.0.0:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.1.0:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.2.0:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4 8.3.0:8e88c46ed613d9510f76b938afacefa657ad8605d68911eaf2d8386dfb37f1e4
describe("About Functions", function() { it("should declare functions", function() { function add(a, b) { return a + b; } expect(add(1, 2)).toBe(3); }); it("should know internal variables override outer variables", function () { var message = "Outer"; function getMessage() { return message; } function overrideMessage() { var message = "Inner"; return message; } expect(getMessage()).toBe("Outer"); expect(overrideMessage()).toBe("Inner"); expect(message).toBe("Outer"); }); it("should have lexical scoping", function() { var variable = "top-level"; function parentfunction() { var variable = "local"; function childfunction() { return variable; } return childfunction(); } expect(parentfunction()).toBe("local"); }); it("should use lexical scoping to synthesise functions", function() { function makeIncreaseByFunction(increaseByAmount) { return function(numberToIncrease) { return numberToIncrease + increaseByAmount; }; } var increaseBy3 = makeIncreaseByFunction(3); var increaseBy5 = makeIncreaseByFunction(5); expect(increaseBy3(10) + increaseBy5(10)).toBe(28); }); it("should allow extra function arguments", function() { function returnFirstArg(firstArg) { return firstArg; } expect(returnFirstArg("first", "second", "third")).toBe("first"); function returnSecondArg(firstArg, secondArg) { return secondArg; } expect(returnSecondArg("only give first arg")).toBe(undefined); function returnAllArgs() { var argsArray = []; for (var i = 0; i < arguments.length; i += 1) { argsArray.push(arguments[i]); } return argsArray.join(","); } expect(returnAllArgs("first", "second", "third")).toBe("first,second,third"); }); it("should pass functions as values", function() { var appendRules = function(name) { return name + " rules!"; }; var appendDoubleRules = function(name) { return name + " totally rules!"; }; var praiseSinger = { givePraise: appendRules }; expect(praiseSinger.givePraise("John")).toBe("John rules!"); praiseSinger.givePraise = appendDoubleRules; expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!"); }); it("should use function body as a string", function() { var add = new Function("a", "b", "return a + b;"); expect(add(1, 2)).toBe(3); var multiply = function(a, b) { // An internal comment return a * b; }; expect(multiply.toString()).toBe('function(a, b) { // An internal comment return a * b; }'); }); });
'use strict'; var mongoose = require('mongoose'); var User = require('../models/user').User; var Playlist = require('../models/user').Playlist; var Item = require('../models/user').Item; module.exports = function(app){ //Create Playlist app.route('/movies/playlist/create') .post(function(req, res, next){ if(req.body.name){ var List = new Playlist(); List._id = mongoose.Types.ObjectId(); List._name = req.body.name; List.user_id = req.session.passport.user; List.save(); res.end('Playlist Created'); } else { next(); } //console.log(req.body.name); //console.log(req.body); }); //Get all playlists by user app.route('/movies/playlists') .get(function(req, res, next){ Playlist.find({'user_id': req.session.passport.user}, function(err, playlists){ if(err){ return done(err); } if(playlists){ res.send(playlists); } }); }); //Add item to playlist app.route('/movies/playlist/add') .post(function(req, res, next){ if(req.body.playlist && req.body.movie){ var Movie = new Item(); Movie._id = req.body.movie; Movie.playlist_id = req.body.playlist; Movie.save(); res.end('Item added!'); console.log(Movie); } else { next(); } }); //Get all items in playlist app.route('/movies/playlist/:id') .get(function(req, res, next){ var id = req.params.id; Item.find({'playlist_id': id}, function(err, items){ if(req.params.id){ res.send(items); } else { next(); } }); }); };
// @flow import { connect } from "react-redux"; import { fetchCoveo } from "../data/searchActions"; import locationSearch from "./locationSearch"; import SearchResults from "../components/search/SearchResults"; export const mapStateToProps = (state: Object) => { return { results: state.search.results, fetching: state.search.fetching, exception: state.search.exception }; }; export const mapDispatchToProps = (dispatch: Function) => { return { queryServer: (search: string) => { dispatch(fetchCoveo(search)); } }; }; export default locationSearch( connect(mapStateToProps, mapDispatchToProps)(SearchResults) );
/** * Created by carl.hand on 30/03/2017. */ import React from 'react'; var App;
'use strict'; /** * Module dependencies. */ var config = require('../config'), express = require('express'), app = express(), morgan = require('morgan'), logger = require('./logger'), bodyParser = require('body-parser'), session = require('express-session'), MongoStore = require('connect-mongo')(session), favicon = require('serve-favicon'), compress = require('compression'), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), helmet = require('helmet'), flash = require('connect-flash'), consolidate = require('consolidate'), path = require('path'), _ = require('lodash'), cors = require('cors'), lusca = require('lusca'), multer = require('multer'), os = require('os'); var passport = require('passport'); var whitelist = ['https://api.qykly.mobi', 'http://localhost:3000', 'http://localhost:9000' ]; var corsOptionsDelegate = function(req, callback) { console.log('test'); var corsOptions; if (whitelist.indexOf(req.header('Origin')) !== -1) { corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response } else { corsOptions = { origin: false }; // disable CORS for this request } callback(null, corsOptions); // callback expects two parameters: error and options }; /** * Initialize local variables */ module.exports.initLocalVariables = function(app) { app.use(function(req, res, next) { // var origin = req.get('origin'); // res.header('Access-Control-Allow-Credentials', true); // res.header('Access-Control-Allow-Origin', origin); var op = 'OPTIONS'; res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override,Authorization, Content-Type, Accept' ); if (op === req.method) { res.send(200); } else { next(); } }); app.use(function(req, res, next) { var op = 'OPTIONS'; res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override,Authorization, Content-Type, Accept' ); if (op === req.method) { res.send(200); } else { next(); } }); // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; if (config.secure && config.secure.ssl === true) { app.locals.secure = config.secure.ssl; } app.locals.keywords = config.app.keywords; app.locals.googleAnalyticsTrackingID = config.app.googleAnalyticsTrackingID; app.locals.facebookAppId = config.facebook.clientID; app.locals.jsFiles = config.files.client.js; app.locals.cssFiles = config.files.client.css; app.locals.livereload = config.livereload; app.locals.logo = config.logo; app.locals.favicon = config.favicon; // Passing the request url to environment locals app.use(function(req, res, next) { res.locals.host = req.protocol + '://' + req.hostname; res.locals.url = req.protocol + '://' + req.headers.host + req.originalUrl; next(); }); var timeout = require('connect-timeout'); app.use(timeout(600000)); app.use(haltOnTimedout); function haltOnTimedout(req, res, next) { if (!req.timedout) next(); } }; /** * Initialize application middleware */ module.exports.initMiddleware = function(app, passport) { app.use(function(req, res, next) { var op = 'OPTIONS'; res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override,Authorization, Content-Type, Accept' ); if (op === req.method) { res.send(200); } else { next(); } }); // Showing stack errors app.set('showStackError', true); // Enable jsonp app.enable('jsonp callback'); // Should be placed before express.static app.use(compress({ filter: function(req, res) { return (/json|text|javascript|css|font|svg/).test(res.getHeader( 'Content-Type')); }, level: 9 })); // Initialize favicon middleware app.use(favicon(app.locals.favicon)); // Enable logger (morgan) if enabled in the configuration file if (_.has(config, 'log.format')) { app.use(morgan(logger.getLogFormat(), logger.getMorganOptions())); } // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // Request body parsing middleware should be above methodOverride app.use(bodyParser.text()); app.use(bodyParser.urlencoded({ limit: '50mb', extended: true })); app.use(bodyParser.json({ limit: '50mb' })); app.use(methodOverride()); // Add the cookie parser and flash middleware app.use(cookieParser()); app.use(flash()); app.use(passport.initialize()); app.use(passport.session()); // persistent login sessions }; /** * Configure view engine */ module.exports.initViewEngine = function(app) { // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // Set views path and view engine app.set('view engine', 'server.view.html'); app.set('views', './'); }; /** * Configure Express session */ module.exports.initSession = function(app, db) { // Express MongoDB session storage app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret, cookie: { maxAge: config.sessionCookie.maxAge, httpOnly: config.sessionCookie.httpOnly, secure: config.sessionCookie.secure && config.secure.ssl }, key: config.sessionKey, store: new MongoStore({ mongooseConnection: db.connection, collection: config.sessionCollection }) })); // Add Lusca CSRF Middleware app.use(lusca(config.csrf)); }; /** * Invoke modules server configuration */ module.exports.initModulesConfiguration = function(app, db) { config.files.server.configs.forEach(function(configPath) { require(path.resolve(configPath))(app, db); }); }; /** * Configure Helmet headers configuration */ module.exports.initHelmetHeaders = function(app) { // Use helmet to secure Express headers var SIX_MONTHS = 15778476000; app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.use(helmet.hsts({ maxAge: SIX_MONTHS, includeSubdomains: true, force: true })); app.disable('x-powered-by'); }; /** * Configure the modules static routes */ module.exports.initModulesClientRoutes = function(app) { // Setting the app router and static folder app.use('/', express.static(path.resolve('./public'))); // Globbing static routing config.folders.client.forEach(function(staticPath) { app.use(staticPath, express.static(path.resolve('./' + staticPath))); }); }; /** * Configure the modules ACL policies */ module.exports.initModulesServerPolicies = function(app) { // Globbing policy files config.files.server.policies.forEach(function(policyPath) { require(path.resolve(policyPath)).invokeRolesPolicies(); }); }; /** * Configure the modules server routes */ module.exports.initModulesServerRoutes = function(app, passport) { // Globbing routing files config.files.server.routes.forEach(function(routePath) { require(path.resolve(routePath))(app, passport); }); }; /** * Configure error handling */ module.exports.initErrorRoutes = function(app) { app.use(function(err, req, res, next) { // If the error object doesn't exists if (!err) { return next(); } // Log it console.error(err.stack); // Redirect to error page res.redirect('/server-error'); }); }; /** * Configure Socket.io */ module.exports.configureSocketIO = function(app, db) { // Load the Socket.io configuration var server = require('./socket.io')(app, db); // Return server object return server; }; /** * Initialize the Express application */ module.exports.init = function(db) { // Initialize express app var app = express(); // Initialize local variables this.initLocalVariables(app); // Initialize Express middleware this.initMiddleware(app, passport); // Initialize Express view engine this.initViewEngine(app); // Initialize Helmet security headers this.initHelmetHeaders(app); // Initialize modules static client routes, before session! this.initModulesClientRoutes(app); // Initialize Express session this.initSession(app, db); // Initialize Modules configuration this.initModulesConfiguration(app); // Initialize modules server authorization policies this.initModulesServerPolicies(app); // Initialize modules server routes this.initModulesServerRoutes(app, passport); // Initialize error routes this.initErrorRoutes(app); // Configure Socket.io app = this.configureSocketIO(app, db); return app; };
'use strict'; const assert = require('assert'); const congress = require('../../../src/services/lib/congress'); const states = require('../../../src/services/lib/states'); const rp = require('request-promise'); //const app = require('../../../src/app'); describe('reps service', function() { it('registered the reps service', () => { //assert.ok(app.service('reps')); }); it('returns reps for a location', function(done) { this.timeout(10000); rp({ url: 'http://localhost:3030/reps', qs: { latitude: 37.540842, longitude: -77.48346 }, json: true }).then(function(data) { assert.ok(data, 'No response data'); assert.ok(data.length > 3, 'Not enough results'); assert.equal(data[0].level, 'federal', 'Missing federal results'); assert.equal(data[data.length - 1].level, 'state', 'Missing state results'); }).catch(function(err) { assert.fail(err); }).finally(done); }); }); describe('congress service', function() { it('finds reps by geo point', function(done) { this.timeout(10000); const lat = 37.540842; const lon = -77.483460; congress.findRepsByPoint(lat, lon) .then(function(body) { assert.ok(body.results, "No results key"); assert.equal(body.count, 3, "Wrong number of results"); var chambers = body.results.reduce(function(p,c) { p[c.chamber] = (p[c.chamber] || 0) + 1; return p; }, {}); assert.equal(chambers.senate, 2, "Wrong number of senators"); assert.equal(chambers.house, 1, "Wrong number of representatives"); }).catch(function(err) { assert.fail(err); }).finally(done); }); it('finds reps by zip', function(done) { this.timeout(10000); const zip = 23219; congress.findRepsByZip(zip) .then(function(body) { assert.ok(body.results, "No results key"); assert.equal(body.count, 3, "Wrong number of results"); var chambers = body.results.reduce(function(p,c) { p[c.chamber] = (p[c.chamber] || 0) + 1; return p; }, {}); assert.equal(chambers.senate, 2, "Wrong number of senators"); assert.equal(chambers.house, 1, "Wrong number of representatives"); }).catch(function(err) { assert.fail(err); }).finally(done); }); }); describe('states service', function() { it('finds reps by geo point', function(done) { this.timeout(10000); const lat = 37.540842; const lon = -77.483460; states.findRepsByPoint(lat, lon) .then(function(body) { assert.equal(body.length, 2, "Wrong number of results"); var chambers = body.reduce(function(p,c) { p[c.chamber] = (p[c.chamber] || 0) + 1; return p; }, {}); assert.equal(chambers.upper, 1, "Wrong number in upper chamber"); assert.equal(chambers.lower, 1, "Wrong number in lower chamber"); }).catch(function(err) { assert.fail(err); }).finally(done); }); });
module.exports = function(http, server) { return function(request, response) { var message = ''; if(response.message) { message = response.message.toString(); } if(response.state === 404) { server.trigger('response-404', request, response); } try { response.writeHead(response.state, response.headers); response.end(message, response.encoding); //event trigger server.trigger('output', request, response); } catch(error) { response.state = 500; //event trigger server.trigger('output-error', request, response, error); if(!message.length) { response.message = error.toString(); } response.writeHead(response.state, response.headers); response.end(response.message); } }; };
/*jshint esnext: true */ /* * filetype.js * * FileType "static" class * */ const FileType = { UNKNOWN: 1, ARCHIVE: 2, BINARY: 3, CODE: 4, TEXT: 5, XML: 6 }; Object.freeze(FileType); exports.FileType = FileType;
Appbus.MultiButton = new Class({ Extends : Appbus.Box, namespace: 'multibutton', items: [], buttons: [], cindex: 0, multiSelect: false, initialize : function(options) { this.parent(options); }, prepare: function() { var o = this.options; var self = this; this.multiSelect = o.multiSelect; if( o.fit ) { this.el.style[P_S3 + 'BoxFlex'] = 1; this.el.style.width = '100%'; } var items = this.items = o.items; for(var i=0;i < items.length;i++) { var item = items[i]; this.add(item); } }, add: function(item) { if( !item ) throw new AppbusException('item missing'); var o = this.options; var self = this; var index = this.buttons.length; var div = document.createElement('div'); div.setAttribute('index', index); if( item.selected ) div.className += ' active'; if( item.disabled ) div.className += ' disabled'; if( item.selected ) this.cindex = index; if( o.bw ) div.style.width = (isNaN(parseInt(o.bw))) ? o.bw : o.bw + 'px'; if( o.bmw ) div.style.minWidth = (isNaN(parseInt(o.bmw))) ? o.bmw : o.bmw + 'px'; if( o.bxw ) div.style.maxWidth = (isNaN(parseInt(o.bxw))) ? o.bxw : o.bxw + 'px'; if( item.width ) div.style.width = (isNaN(parseInt(item.width))) ? item.width : item.width + 'px'; if( item.image ) div.innerHTML = '<img src="' + item.image + '" />'; if( item.text ) div.innerHTML = '<span>' + item.text + '</span>'; else if( item.html ) div.innerHTML = item.html; new Appbus.AdvancedEvent(null, div, { touchstart: function(cmp, e, ae) { self.selected(ae.el.getAttribute('index')); } }); this.buttons.push(div); this.el.appendChild(div); }, selected: function(index) { //console.log('selected', index); var button = this.buttons[index]; var item = this.items[index]; if( !button ) return; if( !this.multiSelect ) { var pb = this.buttons[this.cindex]; pb.className = Util.replaceAll(pb.className, ' active', ''); } button.className += ' active'; this.cindex = index; this.fire('selected', this, parseInt(index), item, button); if( item.select ) item.select(this, parseInt(index), item, button); } }); Appbus.defineStyle('.multibutton', { '': { 'display': '-webkit-box', 'font-weight': 'bold', 'font-size': '11px', 'color': 'white', 'margin': '2px', 'margin-left': '10px', 'margin-right': '10px', 'text-shadow': 'rgba(0, 0, 0, 0.6) 0 -1px 0' }, '> div.disabled': { 'color': '#bbb', 'text-shadow': 'rgba(0, 0, 0, 0.3) 0 -1px 0' }, '> div': { 'display': '-webkit-box', '-webkit-box-align': 'center', '-webkit-box-pack': 'center', '-webkit-box-flex': '1', 'min-width': '60px', //'max-width': '120px', 'padding': '5px 7px', 'margin': '0', 'margin-bottom': '1px', 'cursor': 'pointer', 'border': '1px solid rgba(0,0,0,0.35)', 'border-left': 'none', '-webkit-box-shadow': 'inset 0 1px 10px rgba(0,0,0,0.2), 0 1px rgba(255,255,255,0.3)' }, '> div.active': { 'color': 'white', 'text-shadow': 'rgba(0, 0, 0, 0.6) 0 -1px 0', 'background-image ': '-webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(100%, rgba(74,74,74,0.5)), color-stop(51%, rgba(35,35,35,0.5)), color-stop(50%, rgba(25,25,25,0.5)), color-stop(0%, rgba(25,25,25,0.5)))' }, '> div:first-child': { 'border': '1px solid rgba(0,0,0,0.35)', '-webkit-border-top-left-radius': '6px', '-webkit-border-bottom-left-radius': '6px' }, '> div:last-child': { 'border': '1px solid rgba(0,0,0,0.35)', 'border-left': 'none', '-webkit-border-top-right-radius': '6px', '-webkit-border-bottom-right-radius': '6px' }, '> div > span': { 'display': 'block', 'max-width': '100%', 'overflow': 'hidden', 'padding': '1px', 'white-space': 'nowrap', 'text-overflow': 'ellipsis' } }); Appbus.defineStyle('.multibutton.vintage', { '> div': { '-webkit-box-shadow': 'inset 0 1px 10px rgba(0,0,0,0.2), 0 1px rgba(255,255,255,0.3)' } }); Appbus.defineStyle('.multibutton.red', { '> div': { 'background-color': 'rgba(141,13,0,0.8)' } });
import { draw } from "./draw"; (async () => { const fetchVertex = fetch("glsl/main.vert").then(req => req.text()); const fetchFragment = fetch("glsl/main.frag").then(req => req.text()); const waitLoading = new Promise(resolve => { window.addEventListener("DOMContentLoaded", resolve, { capture: false, once: true }); }); const [vertex, fragment] = await Promise.all([fetchVertex, fetchFragment, waitLoading]); const canvas = document.getElementById("canvas"); const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); draw(gl, [{vertex, fragment}]); })();
var assert = require("assert"); var uuid = require("node-uuid"); var DummyAggregateRoot = require("./support/DummyAggregateRoot"); var DummyAggregateRootCreatedEvent = require("./support/DummyAggregateRootCreatedEvent"); describe("Test Aggregate Root", function() { it("Should remove all uncommitted events when marked as committed", function() { this.id = uuid.v4(); this.name = "Something"; this.testAgg = new DummyAggregateRoot({ id: this.id, name: this.name }); this.testAgg.markAsCommitted(); assert.equal(this.testAgg.uncommittedEvents.length, 0); }); describe("Test Creating an AggregateRoot", function() { beforeEach(function() { this.id = uuid.v4(); this.name = "Something"; this.testAgg = new DummyAggregateRoot({ id: this.id, name: this.name }); }); it("Should initialize id from parameters", function() { assert.equal(this.testAgg.id, this.id); }); it("Should increment the version of the AggregateRoot after handling a known event", function() { assert.equal(this.testAgg.nextVersion, 1); }); it("Should add the event being handled to the AggregateRoots list of uncommitted events", function() { assert.equal(this.testAgg.uncommittedEvents.length, 1); }); it("Should assign the version of the AggregateRoot to the event being handled", function() { var event = this.testAgg.uncommittedEvents[0]; assert.equal(event.version, 1); }); it("Should assign the next version to the actual version once the aggregate root is committed", function(){ this.testAgg.markAsCommitted(); assert.equal(this.testAgg.version, 1); }); }); describe("Test Replaying Events on the AggregateRoot", function() { beforeEach(function(){ this.version = 1; var id = uuid.v4(); var name = "SomeName"; var events = [ new DummyAggregateRootCreatedEvent({ id: id, name: name, version: this.version })]; this.testAgg = new DummyAggregateRoot({ events: events }); }); it("Should assign the version of the event to the aggregate root", function() { assert.equal(this.testAgg.version, this.version); }); it("Should assign the version to the next version for further events to be applied", function(){ assert.equal(this.testAgg.nextVersion, this.version); }); }); });
(function() { 'use strict'; angular .module('demoApp') .controller('ElementsController', ElementsController); /** @ngInject */ function ElementsController() { } })();
"use strict"; debugger; let bufferObj = new ArrayBuffer(32); let oneObj = new Int16Array(bufferObj); console.log(oneObj.length); console.log(oneObj.byteLength); let twoObj = new Int32Array(bufferObj); console.log(twoObj.length); let dummy;
var React = require("react"); var ErrorView = React.createClass({ render() { return (<li className="error-message"> <span>{this.props.text}</span> <span className="dismiss-button">{this.props.dismissed}</span> </li>); } }); var SuccessView = React.createClass({ render() { return (<li className="success-message"> <span>{this.props.text}</span> <span className="dismiss-button">{this.props.dismissed}</span> </li>); } }); var WarningView = React.createClass({ render() { return (<li className="warning-message"> <span>{this.props.text}</span> <span className="dismiss-button">{this.props.dismissed}</span> </li>); } }); var FeedbackView = React.createClass({ render() { var feedback = this.props.feedback, dismissAction = this.props.dimiss; if (this.props.feedback.get("type") === "error") { return <ErrorView dismissed={dismissAction} text={feedback.get("message")} />; } else if (feedback.get("type") === "success") { return <SuccessView dismissed={dismissAction} text={feedback.get("message")} />; } else { return <WarningView dismissed={dismissAction} text={feedback.get("message")} />; } } }); export default { ErrorView, SuccessView, WarningView, FeedbackView };
/* global module */ var pkg = require('../package.json'); module.exports = Object.assign({}, pkg.jest, { rootDir: '../', moduleNameMapper: { '/src/index$': '<rootDir>/dist/index', }, });
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.form.CheckedMultiSelect"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.form.CheckedMultiSelect"] = true; dojo.provide("dojox.form.CheckedMultiSelect"); dojo.require("dijit.form.CheckBox"); dojo.require("dijit.Tooltip"); dojo.require("dijit.form._FormSelectWidget"); dojo.declare("dojox.form._CheckedMultiSelectItem", [dijit._Widget, dijit._Templated], { // summary: // The individual items for a CheckedMultiSelect widgetsInTemplate: true, templateString: dojo.cache("dojox.form", "resources/_CheckedMultiSelectItem.html", "<div class=\"dijitReset ${baseClass}\"\n\t><input class=\"${baseClass}Box\" dojoType=\"dijit.form.CheckBox\" dojoAttachPoint=\"checkBox\" \n\t\tdojoAttachEvent=\"_onClick:_changeBox\" type=\"${_type.type}\" baseClass=\"${_type.baseClass}\"\n\t/><div class=\"dijitInline ${baseClass}Label\" dojoAttachPoint=\"labelNode\" dojoAttachEvent=\"onclick:_onClick\"></div\n></div>\n"), baseClass: "dojoxMultiSelectItem", // option: dojox.form.__SelectOption // The option that is associated with this item option: null, parent: null, // disabled: boolean // Whether or not this widget is disabled disabled: false, // readOnly: boolean // Whether or not this widget is readOnly readOnly: false, postMixInProperties: function(){ // summary: // Set the appropriate _subClass value - based on if we are multi- // or single-select if(this.parent.multiple){ this._type = {type: "checkbox", baseClass: "dijitCheckBox"}; }else{ this._type = {type: "radio", baseClass: "dijitRadio"}; } this.disabled = this.option.disabled = this.option.disabled||false; this.inherited(arguments); }, postCreate: function(){ // summary: // Set innerHTML here - since the template gets messed up sometimes // with rich text this.inherited(arguments); this.labelNode.innerHTML = this.option.label; }, _changeBox: function(){ // summary: // Called to force the select to match the state of the check box // (only on click of the checkbox) Radio-based calls _setValueAttr // instead. if(this.get("disabled") || this.get("readOnly")){ return; } if(this.parent.multiple){ this.option.selected = this.checkBox.get('value') && true; }else{ this.parent.set('value', this.option.value); } // fire the parent's change this.parent._updateSelection(); // refocus the parent this.parent.focus(); }, _onClick: function(e){ // summary: // Sets the click state (passes through to the check box) if(this.get("disabled") || this.get("readOnly")){ dojo.stopEvent(e); }else{ this.checkBox._onClick(e); } }, _updateBox: function(){ // summary: // Called to force the box to match the state of the select this.checkBox.set('value', this.option.selected); }, _setDisabledAttr: function(value){ // summary: // Disables (or enables) all the children as well this.disabled = value||this.option.disabled; this.checkBox.set("disabled", this.disabled); dojo.toggleClass(this.domNode, "dojoxMultiSelectDisabled", this.disabled); }, _setReadOnlyAttr: function(value){ // summary: // Sets read only (or unsets) all the children as well this.checkBox.set("readOnly", value); this.readOnly = value; } }); dojo.declare("dojox.form.CheckedMultiSelect", dijit.form._FormSelectWidget, { // summary: // Extends the core dijit MultiSelect to provide a "checkbox" selector templateString: dojo.cache("dojox.form", "resources/CheckedMultiSelect.html", "<div class=\"dijit dijitReset dijitInline\" dojoAttachEvent=\"onmousedown:_onMouseDown,onclick:focus\"\n\t><select class=\"${baseClass}Select\" multiple=\"true\" dojoAttachPoint=\"containerNode,focusNode\"></select\n\t><div dojoAttachPoint=\"wrapperDiv\"></div\n></div>\n"), baseClass: "dojoxMultiSelect", // required: Boolean // User is required to check at least one item. required: false, // invalidMessage: String // The message to display if value is invalid. invalidMessage: "At least one item must be selected.", // _message: String // Currently displayed message _message: "", // tooltipPosition: String[] // See description of `dijit.Tooltip.defaultPosition` for details on this parameter. tooltipPosition: [], _onMouseDown: function(e){ // summary: // Cancels the mousedown event to prevent others from stealing // focus dojo.stopEvent(e); }, validator: function() { // summary: // Overridable function used to validate that an item is selected if required = // true. // tags: // protected if (!this.required){ return true; } return dojo.some(this.getOptions(), function(opt){ return opt.selected && opt.value != null && opt.value.toString().length != 0; }); }, validate: function(isFocused) { dijit.hideTooltip(this.domNode); var isValid = this.isValid(isFocused); if(!isValid){ this.displayMessage(this.invalidMessage); } return isValid; }, isValid: function(/*Boolean*/ isFocused) { // summary: // Tests if the required items are selected. // Can override with your own routine in a subclass. // tags: // protected return this.validator(); }, getErrorMessage: function(/*Boolean*/ isFocused) { // summary: // Return an error message to show if appropriate // tags: // protected return this.invalidMessage; }, displayMessage: function(/*String*/ message) { // summary: // Overridable method to display validation errors/hints. // By default uses a tooltip. // tags: // extension dijit.hideTooltip(this.domNode); if(message){ dijit.showTooltip(message, this.domNode, this.tooltipPosition); } }, onAfterAddOptionItem: function(item, option){ // summary: // a function that can be connected to in order to receive a // notification that an item as been added to this dijit. }, _addOptionItem: function(/* dojox.form.__SelectOption */ option){ var item = new dojox.form._CheckedMultiSelectItem({ option: option, parent: this }); this.wrapperDiv.appendChild(item.domNode); this.onAfterAddOptionItem(item, option); }, _refreshState: function(){ // summary: // Validate if selection changes. this.validate(this._focused); }, onChange: function(newValue){ // summary: // Validate if selection changes. this._refreshState(); }, reset: function(){ // summary: Overridden so that the state will be cleared. this.inherited(arguments); dijit.hideTooltip(this.domNode); }, _updateSelection: function(){ this.inherited(arguments); this._handleOnChange(this.value); dojo.forEach(this._getChildren(), function(c){ c._updateBox(); }); }, _getChildren: function(){ return dojo.map(this.wrapperDiv.childNodes, function(n){ return dijit.byNode(n); }); }, invertSelection: function(onChange){ // summary: Invert the selection // onChange: Boolean // If null, onChange is not fired. dojo.forEach(this.options, function(i){ i.selected = !i.selected; }); this._updateSelection(); }, _setDisabledAttr: function(value){ // summary: // Disable (or enable) all the children as well this.inherited(arguments); dojo.forEach(this._getChildren(), function(node){ if(node && node.set){ node.set("disabled", value); } }); }, _setReadOnlyAttr: function(value){ // summary: // Sets read only (or unsets) all the children as well if("readOnly" in this.attributeMap){ this._attrToDom("readOnly", value); } this.readOnly = value; dojo.forEach(this._getChildren(), function(node){ if(node && node.set){ node.set("readOnly", value); } }); }, uninitialize: function(){ dijit.hideTooltip(this.domNode); // Make sure these children are destroyed dojo.forEach(this._getChildren(), function(child){ child.destroyRecursive(); }); this.inherited(arguments); } }); }
var async = require('async'); var assert = require('assert'); var sinon = require('sinon'); var ThunderBatch = require('..'); // The actual URL is irrelevant, because we're never going to actually make a // real request. var URL = 'http://localhost:9999/test'; function fakeWorkingRequest(options, callback) { setTimeout(function() { var err = null; var response = {statusCode: 200}; var body = 'OK'; callback(err, response, body); }, 0); } function fakeErrorRequest(options, callback) { setTimeout(function() { var err = new Error("Something went wrong."); err.code = "FAKE" callback(err); }, 0); } function fakeTimeoutRequest(options, callback) { } describe('ThunderBatch', function() { var thunderBatch, workingSpy, errorSpy, timeoutSpy; var getOptions = { method: 'GET', uri: URL, timeout: 50 }; var postOptions = { method: 'POST', uri: URL, timeout: 50 }; beforeEach(function() { thunderBatch = new ThunderBatch(); sinon.spy(thunderBatch, 'passthrough'); sinon.spy(thunderBatch, 'intercept'); workingSpy = sinon.spy(fakeWorkingRequest); errorSpy = sinon.spy(fakeErrorRequest); timeoutSpy = sinon.spy(fakeTimeoutRequest); }); afterEach(function() { thunderBatch.quit(); }); // -- it('should intercept GET requests', function(done) { thunderBatch.extension(getOptions, function(err, response, body) { assert.equal(true, thunderBatch.intercept.calledOnce); assert.equal(false, thunderBatch.passthrough.called); done(); }, workingSpy); }); it('should pass non-GET requests', function(done) { thunderBatch.extension(postOptions, function(err, response, body) { assert.equal(false, thunderBatch.intercept.calledOnce); assert.equal(true, thunderBatch.passthrough.called); done(); }, workingSpy); }); var multipleRequests = [ function(cb) { thunderBatch.extension(getOptions, cb, workingSpy); }, function(cb) { thunderBatch.extension(getOptions, cb, workingSpy); } ]; it('should make one concurrent identical request', function(done) { async.parallel(multipleRequests, function(err) { assert(!err); assert(workingSpy.calledOnce); done(); }); }); it('should make multiple consecutive identical requests', function(done) { async.series(multipleRequests, function(err) { assert(!err); assert(workingSpy.calledTwice); done(); }); }); it('should handle backend errors', function(done) { thunderBatch.extension(getOptions, function(err, response, body) { assert.equal(err.code, 'FAKE'); assert(!response); assert(!body); done(); }, errorSpy); }); it('should timeout properly', function(done) { thunderBatch.extension(getOptions, function(err, response, body) { assert.equal(err.code, 'PUBSUBTIMEDOUT'); assert(!response); assert(!body); done(); }, timeoutSpy); }); });
'use strict'; var fs = require('fs'); module.exports = /*@ngInject*/ function yearPicker (dateFilter) { return { restrict: 'EA', replace: true, template: fs.readFileSync(__dirname + '/templates/year.html', 'utf8'), require: '^datepicker', link: function(scope, element, attrs, ctrl) { var range = ctrl.yearRange; ctrl.step = { years: range }; ctrl.element = element; function getStartingYear( year ) { return parseInt((year - 1) / range, 10) * range + 1; } ctrl._refreshView = function() { var years = new Array(range); for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) { years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), { uid: scope.uniqueId + '-' + i }); } scope.title = [years[0].label, years[range - 1].label].join(' - '); scope.rows = ctrl.split(years, 5); }; ctrl.compare = function(date1, date2) { return date1.getFullYear() - date2.getFullYear(); }; ctrl.handleKeyDown = function( key, evt ) { var date = ctrl.activeDate.getFullYear(); if (key === 'left') { date = date - 1; // up } else if (key === 'up') { date = date - 5; // down } else if (key === 'right') { date = date + 1; // down } else if (key === 'down') { date = date + 5; } else if (key === 'pageup' || key === 'pagedown') { date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years; } else if (key === 'home') { date = getStartingYear( ctrl.activeDate.getFullYear() ); } else if (key === 'end') { date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1; } ctrl.activeDate.setFullYear(date); }; ctrl.refreshView(); } }; }
// LPdefs.js // // definition of lpProblem object // for solution of LP problems by simplex method // // Copyright (C) 2017 Steven R. Costenoble and Stefan Waner // lp modes const lp_Integral = 1; // solve using integers? const lp_Fraction = lp_Integral+1; // using fractions? const lp_Decimal = lp_Fraction+1; // using decimals? // lp status const lp_no_problem = 0; // no problem, yet const lp_parsed = lp_no_problem+1; // parsed a problem const lp_phase1 = lp_parsed+1; // done with Phase I const lp_phase2 = lp_phase1+1; // done with Phase II const lp_optimal = lp_phase2+1; // completely done - not necessarily Phase II for integer programming const lp_no_solution = lp_optimal+1; // no solution, don't continue // verbosity level const lp_verbosity_none = 0; // how verbose should we be? const lp_verbosity_tableaus = lp_verbosity_none + 1; // show all tableaus const lp_verbosity_solutions = lp_verbosity_tableaus + 1; // tableaus and intermediate solutions // globals var lp_verboseLevel = lp_verbosity_none; var lp_reportErrorsTo = ""; // empty if default reporting, "alert" or id of an html element var lp_trace_string = ""; // string that will contain the tableaus, solutions, etc. // error messages (should be reassignable by a parent container - eg in Spanish - so these are not consts) var lp_noLPErr = "No LP problem given"; var lp_IllegCharsErr = "Illegal characters"; var lp_UnspecMaxMinErr = "Max or min not specified"; var lp_noRelationConstrErr = "Constraints must contain '=', '<=', or '>='"; var lo_tooManyTabloeausErr = "Number of tableaus exceeds "; var lp_emptyFeasibleRegionErr = "No solution; feasible region empty"; var lp_noMaxErr = "No maximum value; the objective function can be arbitrarily large"; var lp_noMinErr = "No minimum value; the objective function can be arbitrarily large negative"; var lp_phase2TooSoonErr = "Attempting to do Phase 2 when Phase 1 is not complete."; var lp_badExprErr = "Something's wrong in the expression "; var lp_illegalCoeffErr = "illegal coefficient of "; var lp_inExprErr = " in the expression\n"; var lp_objNotSetErr = "Objective not set in extractUnknowns"; var lp_noNiceSolutionErr = "No solution with the desired integer values exists" // Setting up an lpProblem // Do one of the following: // 1) Supply an existing lpProblem when constructing the object // 2) Set problemStr to a whole LP problem // For integer/mixed problems, add "integer x,y,z" as last line with unknowns that should be integer // 3) Set objective to the object function, as a string of the form // "[max|min]inmize var = linear expression" and // Set constraints to an array of constraints of the form // "linear expr <=, >=, or = number" // 4) Set maximize, objectiveName, unknowns, and numActualUnknowns, and // set tableaus to a one element array containing the first tableau // // Once the problem is set up, call solve(). // // Success is indicated by this.status, which could be lp_optimal or lp_no_solution. // // For ordinary LP problems, solutions, including all intermediate steps, are available // in this.objectiveValues and this.solutions, with tableaus in this.tableaus // Use the appropriate formatXXX() routine to get them nicely rounded and formatted. // // For integer LP problems, the actual solution is available in // this.integerSolution and this.integerObjValue. // Use formatIntegerXXX() to get them nicely formatted. class lpProblem { constructor ( problem = null ) { // linear expression to optimize this.objective = (problem != null && typeof problem.objective == 'string') ? problem.objective : ""; // array of constraints, linear expr <=, >=, or = number this.constraints = (problem != null && Array.isArray(problem.constraints)) ? problem.constraints.slice() : []; // integer/mixed programming? this.isIntegral = (problem != null && typeof problem.isIntegral == 'boolean') ? problem.isIntegral : false; // solve using integers, fractions, or decimals? this.mode = (problem != null && typeof problem.mode == 'number') ? problem.mode : lp_Decimal; // false for minimize this.maximize = (problem != null && typeof problem.maximize == 'boolean') ? problem.maximize : true; // either supplied with string problem or generated this.objectiveName = (problem != null && typeof problem.objectiveName == 'string') ? problem.objectiveName : "Obj"; // array of names of unknowns (includes slack/surplus variables) this.unknowns = (problem != null && Array.isArray(problem.unknowns)) ? problem.unknowns.slice() : []; // array of unknowns for which integer values are required (mixed programming) this.integerUnknowns = (problem != null && Array.isArray(problem.integerUnknowns)) ? problem.integerUnknowns.slice() : []; // whether or not to show the values of the slack and surplus variables in the solution this.showArtificialVariables = false; // initial matrix of system, a la Ax >= b. // doesn't need to be copied, as it won't change if already filled in this.systemMatrix = (problem != null && Array.isArray(problem.systemMatrix)) ? problem.systemMatrix : []; this.systemRowIsStarred = (problem != null && Array.isArray(problem.systemRowIsStarred)) ? problem.systemRowIsStarred : []; // same for right hand sides of constraints this.constraintRHS = (problem != null && Array.isArray(problem.constraintRHS)) ? problem.constraintRHS : []; // similar for objective function this.objectiveCoeffs = (problem != null && Array.isArray(problem.objectiveCoeffs)) ? problem.objectiveCoeffs : []; // additional constraints used in integer programming, indexed like integerUnknowns this.integerMins = (problem != null && Array.isArray(problem.integerMins)) ? problem.integerMins.slice() : []; this.integerMaxs = (problem != null && Array.isArray(problem.integerMaxs)) ? problem.integerMaxs.slice() : []; // how many original unknowns? this.numActualUnknowns = (problem != null && typeof problem.numActualUnknowns == 'number') ? problem.numActualUnknowns : 0; this.rowIsStarred = []; // ith entry is true if i row is starred this.tableaus = []; // array of tableaus this.tableauDimensions = []; // number of rows, number of columns this.maxNumTableaus=50; // quite arbitrary make it a setting if associated error is thrown this.status = lp_no_problem; // are we there yet? this.solutions = []; // array of intermediate solutions this.objectiveValues = []; // array of intermediate objective values this.error = ""; // error message for badly set up problem etc this.message = ""; // message when there is no solution for one reason or another this.integerSolution = []; // used to return solution to integer programming problems this.integerObjValue = 0; this.problemStr = (problem != null && typeof problem == 'string') ? problem : ""; // settings this.maxSigDigits = 13; // try to push to 16 but issues with roundSigDig which internally uses three more this.sigDigits = 6; // user specified for rounding of tableaus and results } // Functions solve ( ) {} // solve it, return true if succeeded formatObjectiveValues ( mode = 0 ) {} // return array of objective values, in proper form formatLastObjectiveValue ( mode = 0 ) {} // same, just the last value // return array of unknowns, with or w/o slack vars formatUnknowns ( includeSlackVariables = false ) {} // use this to get the solutions, in proper form, // with or w/o slack vars // mode defaults to setting of this.mode // returns an array of arrays, each in order of unknowns formatSolutions ( includeSlackVariables = false, mode = 0 ) {} // same, but just last solution, not all intermediates formatLastSolution ( includeSlackVariables = false, mode = 0 ) {} // use these to get the integer solution when doing ILP formatIntegerObjectiveValue ( mode = 0) {} formatIntegerSolution ( includeSlackVariables = false ) {} // return string showing values of vars in last or integer solution, // using settings of showArtificialVariables & mode solutionToString () {} // same, but shows last solution, even if doing ILP lastSolutionToString () {} } // tableau class is a subclass of Array // The 0th row and column contain labels // The entries of the tableau itself are indexed from [1][1] // class tableau extends Array { constructor ( arr = [] ) { // construct from a given 2D array or tableau super(); for ( var i = 0; i < arr.length; i++ ) this[i] = arr[i].slice(); } pivot ( pRow, pCol, sigDigs ) {} // pivot, return a new tableau toString ( theMode, sigDigs ) {} // returns an ascii formatted string representing the tableau toHTML ( theMode, sigDigs , params) {} // returns an HTML table representing the tableau }
var https = require('https'); var cheerio = require('cheerio'); var iconv = require('iconv-lite'); module.exports = function() { function hebUrlEncode(string) { var u = ""; for (var i = 0; i < string.length; i++) { var code = string.charCodeAt(i); if (code > 256) { u = u + "%" + (code%256+16).toString(16).toUpperCase();; } else if (code === 32) u = u + "+" else u = u + string.charAt(i); } return u; } function timeStringToTime(timeString) { var t = timeString.match(/([0-9].)[^0-9]([0-9].)/); if (!t || t.length != 3) return 0; return Number(t[1]) + t[2]/60; } function postQuery(data) { var postData = ""; for (d in data) postData += d+"="+data[d]+"&"; // Remove last & return postData.substr(0, postData.length-1); } function normalizeNumber(courseNumber) { var number = courseNumber.replace(/[^0-9]/g, ""); var dep = number.substr(0, 3); var level = number.substr(3, 1); var crs = number.substr(4, 4); return dep + "." + level + "." + crs; } return { normalizeNumber: normalizeNumber, searchCourses: function(string, year, semester, next) { var data = { "oc_course_name" : hebUrlEncode(string), "on_year" : year, "on_semester" : semester, "step" : 1, "on_course_ins" : 0, "on_course_department" : "", "on_course_ldegree_level" : "", "on_course_degree_level" : "", "on_course" : "", "on_hours" : "", "on_credit_points" : "", "oc_lecturer_first_name" : "", "oc_lecturer_last_name" : "", "oc_end_time" : "", "oc_start_time" : "", "on_campus" : "" }; var postData = postQuery(data); var options = { hostname: 'bgu4u.bgu.ac.il', path: '/pls/scwp/!sc.AnnualCoursesAdv', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; var req = https.request(options, function(res) { if (res.statusCode !== 200) return next(null); var chunks = []; res.on('data', function(chunk) { chunks.push(chunk); }) .on('end', function() { var html = iconv.decode(Buffer.concat(chunks), 'win1255'); var courses = []; var $ = cheerio.load(html); //var hd = $('td.BlueInputKind') //semester = hd[2].text.trim if hd[2] var tds = $('td.BlackTextEng'); // English name of course for (var i = 0; i < tds.length; i++) { var p = $(tds[i]).parent(); courses.push( { number: $(p.children('td')[3]).text().trim(), name: $('a', p).text().trim(), english: $(tds[i]).text().trim(), //semester: semester }); } return next(courses); }); }); req.write(postData, function(err) { req.end(); }); req.on('error', function(e) { next(null); }); }, courseInfo: function(courseNumber, year, semester, next) { var number = courseNumber.replace(/[^0-9]/g, ""); var dep = number.substr(0, 3); var level = number.substr(3, 1); var crs = number.substr(4, 4); var data = { "rn_course_department" : dep, "rn_course_degree_level" : level, "rn_course" : crs, "rn_year" : year, "rn_semester" : semester, "rn_institution" : 0 }; var postData = postQuery(data); var options = { hostname: 'bgu4u.bgu.ac.il', path: '/pls/scwp/!sc.AnnualCourseSemester', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; var req = https.request(options, function(res) { if (res.statusCode !== 200) return next(null); var chunks = []; res.on('data', function(chunk) { chunks.push(chunk); }) .on('end', function() { var html = iconv.decode(Buffer.concat(chunks), 'win1255'); // hideous hack to fix dangled </td> in BGU exams table, which breaks cheerio html = html.replace(/<\/td><\/td>/g, "</td>"); var $ = cheerio.load(html); tds = $('form#mainForm td.BlackText') var course = { year: year, semester: semester, number: normalizeNumber(courseNumber) }; if (!tds || tds.length == 0) return next(course); course.name = $(tds[1]).text().trim(); course.homepage = $('a', $(tds[1])).attr('href'); course.points = $(tds[3]).text().trim(); course.hours = $(tds[4]).text().trim(); course.groups = []; course.exams = []; var group = null; var trs = $("tr", $('form#mainForm table')[2]); for (var t = 2; t < trs.length; t++) { var row = trs[t]; var tds = $("td", row); // Skip some padding lines if (tds.length != 11) continue; // Group number can be a link var number = parseInt($("a", row).text()); // Or without a link if (isNaN(number)) number = parseInt($(tds[7]).text()); // Or no group number - This is the same group from previous row if (!isNaN(number)) { if (group !== null) course.groups.push(group); group = { "number": number, "type": $(tds[9]).text().trim(), "lecturer": $(tds[5]).text().trim(), "hours": [] } } var hours = { "room": $(tds[1]).text().trim() }; var h = $(tds[3]).text().match(/ ([^ ]) ([0-9][0-9]:[0-9][0-9]) - ([0-9][0-9]:[0-9][0-9])/); if (h && h.length == 4) { hours['day'] = h[1].charCodeAt(0) - 'א'.charCodeAt(0) + 1; hours['startTime'] = timeStringToTime(h[3]); hours['endTime'] = timeStringToTime(h[2]); } group.hours.push(hours); } if (group !== null) course.groups.push(group); //Exams if ($('form#mainForm table')[4]) { var group = 0; var trs = $("tr", $('form#mainForm table')[4]); for (var t = 1; t < trs.length; t++) { var row = trs[t]; var tds = $("td", row); if (tds.length != 7 && tds.length != 5) continue; if (tds.length == 7) group = parseInt($(tds[4]).text()); var startTime = null; var d = $(tds[2]).text().match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})[^0-9]*([0-9]{2}):([0-9]{2})/); if (d.length == 6) startTime = new Date(d[3]+'-'+d[2]+'-'+d[1] + 'T'+d[4]+':'+d[5]+':00.000Z'); course.exams.push({ group: group, startTime: startTime, rooms: $(tds[1]).text().trim(), order: $(tds[3]).text().trim(), }); } } return next(course); }); }); req.write(postData, function(err) { req.end(); }); req.on('error', function(e) { console.error('Error', e); next(null); }); }, generalCourses: function(year, semester, department, degree_year, next) { var postData = "cmdkey=PROD&server=rep_aristo4stu4_FRHome1&report=acrr008w&desformat=html" + "&DESTYPE=cache&P_PATH=&P_SPEC=&P_YEAR_DEGREE=&P_SORT=1&P_WEB=1&P_SPECIAL_PATH=0"; postData = postData + "&P_YEAR=" + year; postData = postData + "&P_SEMESTER=" + semester; postData = postData + "&P_DEGREE_LEVEL=" + 1; postData = postData + "&P_DEPARTMENT=" + department; postData = postData + "&P_GLOBAL_COURSES=" + 3; //Global courses only! var options = { hostname: 'reports4u.bgu.ac.il', path: '/reports/rwservlet', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; var req = https.request(options, function(res) { if (res.statusCode !== 200) return next(null); var chunks = []; res.on('data', function(chunk) { chunks.push(chunk); }) .on('end', function() { var html = iconv.decode(Buffer.concat(chunks), 'win1255'); var courses = html.match(/[0-9]{3}[.][0-9][.][0-9]{4}/g); return next(courses); }); }); req.write(postData, function(err) { req.end(); }); req.on('error', function(e) { next(null); }); } } };
'use strict'; require('mocha'); const assert = require('assert'); const Comments = require('..'); const doctrine = require('doctrine'); const { tag, type } = require('../lib/parse'); /** * some of these integration tests are based on tests from doctrine * https://github.com/eslint/doctrine/LICENSE.BSD * https://github.com/eslint/doctrine/LICENSE.closure-compiler * https://github.com/eslint/doctrine/LICENSE.esprima */ describe('tagged namepaths', () => { it('should parse alias with namepath', () => { const res = tag('@alias aliasName.OK'); assert(res.hasOwnProperty('title', 'alias')); assert(res.hasOwnProperty('name', 'aliasName.OK')); }); it('should parse alias with namepath', () => { const res = tag('@alias module:mymodule/mymodule.init'); assert(res.hasOwnProperty('title', 'alias')); assert(res.hasOwnProperty('name', 'module:mymodule/mymodule.init')); }); it('should parse alias with namepath with hyphen in it', () => { const res = tag('@alias module:mymodule/my-module'); assert(res.hasOwnProperty('title', 'alias')); assert(res.hasOwnProperty('name', 'module:mymodule/my-module')); }); it('should parse mixes with namepath', () => { const res = tag('@mixes thingName.name'); assert(res.hasOwnProperty('title', 'mixes')); assert(res.hasOwnProperty('name', 'thingName.name')); }); it('should parse mixin with namepath', () => { const res = tag('@mixin thingName.name'); assert(res.hasOwnProperty('title', 'mixin')); assert(res.hasOwnProperty('name', 'thingName.name')); }); it('should parse extends with class name path', () => { const res = tag('@extends ClassName.OK'); assert(res.hasOwnProperty('title', 'extends')); assert(res.hasOwnProperty('name', 'ClassName.OK')); }); it('should parse extends with namepath', () => { const res = tag('@extends module:path/ClassName~OK'); assert(res.hasOwnProperty('title', 'extends')); assert(res.hasOwnProperty('name', 'module:path/ClassName~OK')); }); it('should parse this with namepath', () => { const res = tag(' * @this thingName.name'); assert(res.hasOwnProperty('title', 'this')); assert(res.hasOwnProperty('name', 'thingName.name')); }); }); describe('tagged namepaths', () => { it('should recognize module:', () => { const res = tag('@alias module:Foo.bar'); assert(res.hasOwnProperty('title', 'alias')); assert(res.hasOwnProperty('name', 'module:Foo.bar')); assert(res.hasOwnProperty('description', '')); }); it('should recognize external:', () => { const res = tag('@param {external:Foo.bar} baz description'); assert(res.hasOwnProperty('title', 'param')); res.type = type(res.rawType.slice(1, -1)).value; assert.deepEqual(res.type, { name: 'external:Foo.bar', type: 'NameExpression' }); assert(res.hasOwnProperty('name', 'baz')); assert(res.hasOwnProperty('description', 'description')); }); it('should recognize event:', () => { const res = tag('@function event:Foo.bar'); assert(res.hasOwnProperty('title', 'function')); assert(res.hasOwnProperty('name', 'event:Foo.bar')); assert(res.hasOwnProperty('description', null)); }); it('should not parse invalid tags', () => { const comments = new Comments(); const res = comments.parse('@method bogus:Foo.bar'); assert.deepEqual(res, []); }); });
/** * @author: @AngularClass */ const helpers = require('./helpers'); /** * This object is the diff required to add coverage support to karma. * Every property set here will OVERWRITE the property in the original config, no merges. */ const COVERAGE_CONFIG_DIFF = { preprocessors: { './config/spec-bundle.js': [ 'coverage', 'webpack', 'sourcemap'], }, reporters: ['mocha', 'coverage', 'remap-coverage'], coverageReporter: { type: 'in-memory', }, remapCoverageReporter: { 'text-summary': null, json: './coverage/coverage.json', html: './coverage/html', }, }; module.exports = function(config) { var testWebpackConfig = require('./webpack.test.js')({env: 'test'}); var configuration = { // base path that will be used to resolve all patterns (e.g. files, exclude) basePath: '', /* * Frameworks to use * * available frameworks: https://npmjs.org/browse/keyword/karma-adapter */ frameworks: ['jasmine'], // list of files to exclude exclude: [], client: { captureConsole: false, }, /* * list of files / patterns to load in the browser * * we are building the test environment in ./spec-bundle.js */ files: [ { pattern: './config/spec-bundle.js', watched: false, }, { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false, }, ], /* * By default all assets are served at http://localhost:[PORT]/base/ */ proxies: { '/assets/': '/base/src/assets/', }, /* * preprocess matching files before serving them to the browser * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor */ preprocessors: { './config/spec-bundle.js': [ 'webpack', 'sourcemap'], }, // Webpack Config at ./webpack.test.js webpack: testWebpackConfig, // Webpack please don't spam the console when running in karma! webpackMiddleware: { // webpack-dev-middleware configuration // i.e. noInfo: true, // and use stats to turn off verbose output stats: { // options i.e. chunks: false, }, }, /* * test results reporter to use * * possible values: 'dots', 'progress' * available reporters: https://npmjs.org/browse/keyword/karma-reporter */ reporters: ['mocha'], // 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_WARN, // 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', ], customLaunchers: { ChromeTravisCi: { base: 'Chrome', flags: ['--no-sandbox'], }, }, /* * Continuous Integration mode * if true, Karma captures browsers, runs the tests and exits */ singleRun: true, }; if (process.env.TRAVIS) { configuration.browsers = [ 'ChromeTravisCi', ]; } if (helpers.useCoverage()) { Object.assign(configuration, COVERAGE_CONFIG_DIFF); } config.set(configuration); };
/* VRT - Copyright © 2014 Odd Marthon Lende All Rights Reserved */ define([ 'types/widget' ], function ( Widget ) { function DateTime (fields) { Widget.call(this, fields); } DateTime.prototype = Object.create(Widget.prototype); DateTime.required = { '(options)' : Object } return DateTime; });
'use strict'; var Derivative = require('./Derivative'); var DerivativeNumber = require('./DerivativeNumber'); var DerivativeBoolean = require('./DerivativeBoolean'); var DerivativeString = require('./DerivativeString'); var DerivativeList = require('./DerivativeList'); var DerivativeMap = require('./DerivativeMap'); module.exports = { //side effects forEach: function forEach(sideEffect, context) { return this.get().forEach(sideEffect, context); }, //reading values getKey: function getKey(key, notSetValue) { return new Derivative([this, key, notSetValue], function (list, key, notSetValue) { return list.get(key, notSetValue); }); }, has: function has(key) { return new DerivativeBoolean([this, key], function (list, key) { return list.has(key); }); }, includes: function includes(value) { return new DerivativeBoolean([this, value], function (list, value) { return list.includes(value); }); }, first: function first() { return new Derivative([this], function (list) { return list.first(); }); }, last: function last() { return new Derivative([this], function (list) { return list.last(); }); }, getSize: function getSize() { return new DerivativeNumber([this], function (list) { return list.size; }); }, //reducing a value reduce: function reduce(reducer, initial, context) { return new Derivative([this, initial], function (list, initial) { return list.reduce(reducer, initial, context); }); }, reduceRight: function reduceRight(reducer, initialReduction, context) { return new Derivative([this, initial], function (list, initial) { return list.reduceRight(reducer, initial, context); }); }, every: function every(predicate, context) { return new DerivativeBoolean([this], function (list) { return list.every(predicate, context); }); }, some: function some(predicate, context) { return new DerivativeBoolean([this], function (list) { return list.some(predicate, context); }); }, join: function join(separator) { return new DerivativeString([this, separator], function (list, separator) { return list.join(separator); }); }, isEmpty: function isEmpty() { return new DerivativeBoolean([this], function (list) { return list.isEmpty(); }); }, count: function count(predicate, context) { return new DerivativeNumber([this], function (list) { return list.count(predicate, context); }); }, //search for value find: function find(predicate, context, notSetValue) { return new Derivative([this], function (list) { return list.find(predicate, context, notSetValue); }); }, findLast: function findLast(predicate, context, notSetValue) { return new Derivative([this], function (list) { return list.findLast(predicate, context, notSetValue); }); }, findEntry: function findEntry(predicate, context, notSetValue) { return new Derivative([this], function (list) { return list.findEntry(predicate, context, notSetValue); }); }, findLastEntry: function findLastEntry(predicate, context, notSetValue) { return new Derivative([this], function (list) { return list.findLastEntry(predicate, context, notSetValue); }); }, findKey: function findKey(predicate, context) { return new Derivative([this], function (list) { return list.findKey(predicate, context); }); }, findLastKey: function findLastKey(predicate, context) { return new Derivative([this], function (list) { return list.findLastKey(predicate, context); }); }, keyOf: function keyOf(searchValue) { return new Derivative([this, searchValue], function (list, searchValue) { return list.keyOf(searchValue); }); }, lastKeyOf: function lastKeyOf(searchValue) { return new Derivative([this, searchValue], function (list, searchValue) { return list.lastKeyOf(searchValue); }); }, max: function max(comparator) { return new Derivative([this], function (list) { return list.max(comparator); }); }, maxBy: function maxBy(comparatorValueMapper, comparator) { return new Derivative([this], function (list) { return list.maxBy(comparatorValueMapper, comparator); }); }, min: function min(comparator) { return new Derivative([this], function (list) { return list.min(comparator); }); }, minBy: function minBy(comparatorValueMapper, comparator) { return new Derivative([this], function (list) { return list.minBy(comparatorValueMapper, comparator); }); }, //comparison isSubset: function isSubset(iterable) { return new DerivativeBoolean([this, iterable], function (list, iterable) { return list.isSubset(iterable); }); }, isSuperset: function isSuperset(iterable) { return new DerivativeBoolean([this, iterable], function (list, iterable) { return list.isSuperset(iterable); }); }, //conversion toList: function toList() { return new DerivativeList([this], function (map) { return map.toList(); }); }, toMap: function toMap() { return new DerivativeMap([this], function (list) { return list.toMap(); }); } };
var tools = require('./tools') var async = require('async') var AllocateServer = require('./allocateserver') function loadAllocations(etcd, state, done){ var runJobs = [] /* loop over each job in proc and make sure it has an entry in /run (i.e. it is allocated) */ Object.keys(state.proc || {}).forEach(function(key){ if(!state.run[key]){ runJobs.push(state.proc[key]) } }) if(runJobs.length<=0){ return done(null, []) } var serverIds = Object.keys(state.host || {}) if(serverIds.length<=0){ return done('no servers') } var allocated = [] var failed = [] // run jobs is an array of jobs that are in /proc but not in /run (need allocating) async.forEach(runJobs, function(job, nextJob){ AllocateServer(etcd, job, state, function(err, server){ if(err){ return nextJob(err) } if(!server){ failed.push(job) return nextJob() } allocated.push({ job:job, server:server }) nextJob() }) }, function(err){ // we have a list of allocations that is jobs to deploy onto servers done(err, allocated, failed) }) } module.exports = loadAllocations
'use strict'; const fs = require('fs'); const path = require('path'); const { exec } = require('child_process'); const { BrowserWindow } = require('electron'); const simulator = root => { const WIDTH = 800; const HEIGHT = 600; //Deserialize project info from projInfo file, contains path to index.html and presence of webpack among other things const projInfo = JSON.parse(fs.readFileSync(path.join(__dirname, '../lib/projInfo.js'))); //Dynamic simulation if (projInfo.hotLoad) { let child = exec( 'npm start', { cwd: projInfo.rootPath }, (err, stdout, stderr) => { let child = new BrowserWindow({ width: WIDTH, height: HEIGHT }); child.loadURL('http://localhost:8080'); child.toggleDevTools(); } ); } else if (projInfo.webpack) { let child = exec( 'webpack', { cwd: projInfo.rootPath, shell: '/bin/bash' }, (err, stdout, stderr) => { let child = new BrowserWindow({ width: WIDTH, height: HEIGHT }); child.loadURL('file://' + projInfo.htmlPath); child.toggleDevTools(); } ); } else if (projInfo.htmlPath) { let child = new BrowserWindow({ width: WIDTH, height: HEIGHT }); child.loadURL('file://' + projInfo.htmlPath); child.toggleDevTools(); } else { console.log('No Index.html found'); } }; module.exports = simulator;
var animation = require('../../touchstone/animation'); var Container = require('react-container'); var Sentry = require('react-sentry'); var React = require('react'); var Tappable = require('react-tappable'); var Social = require('../../mixins/social'); var PeopleList = require('../../components/PeopleList'); var Sponsor = require('./sponsor'); var capitalize = require('capitalize'); var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); var TIER_PRIORITIES = { 'diamond': 0, 'platinum': 1, 'gold': 2, 'silver': 3, 'bronze': 4, 'startup': 5, 'supporter': 6 }; const scrollable = Container.initScrollable(); module.exports = React.createClass({ displayName: 'ViewEvent', mixins: [Sentry(), Social, animation.Mixins.ScrollContainerToTop], contextTypes: { dataStore: React.PropTypes.object.isRequired }, statics: { navigationBar: 'main', getNavigation () { return { leftIcon: 'ion-android-menu', leftAction: emitter.emit.bind(emitter, 'navigationBarLeftAction'), title: 'Event' }; } }, getInitialState () { return { searchString: '', organisers: this.context.dataStore.getOrganisers(), sponsors: this.context.dataStore.getSponsors() }; }, componentDidMount () { var body = document.getElementsByTagName('body')[0]; var menuWrapper = document.getElementsByClassName('Tabs-Navigator-wrapper')[0]; body.classList.remove('android-menu-is-open'); menuWrapper.addEventListener('click', function(e) { body.classList.remove('android-menu-is-open'); }); this.watch(emitter, 'navigationBarLeftAction', function () { body.classList.toggle('android-menu-is-open'); }); this.watch(this.context.dataStore, 'update-people', this.updateEventState); this.watch(this.context.dataStore, 'update-sponsors', this.updateEventState); }, updateEventState () { this.setState({ organisers: this.context.dataStore.getOrganisers(), sponsors: this.context.dataStore.getSponsors() }); }, openAddress () { window.open('https://www.google.com/maps/dir//Metro-Straße+1,+40235+Düsseldorf,+Deutschland', '_blank', 'toolbar=yes,location=no,transitionstyle=coververtical') }, render () { var organisers = this.state.organisers; var sponsorData = this.state.sponsors; var sponsors = []; function orderByPriority (sponsor1, sponsor2) { return TIER_PRIORITIES[sponsor1.tier] - TIER_PRIORITIES[sponsor2.tier]; } var lastTier; sponsorData.sort(orderByPriority).forEach(function (sponsor, i) { var tierName = capitalize(sponsor.tier); var tierPriority = TIER_PRIORITIES[sponsor.tier]; var lite = tierPriority > 3; if (tierName !== lastTier) { var tierLabel = tierName === 'Supporter' ? 'Supporters' : tierName; sponsors.push( <div key={'tierHeading' + i} className="EventInfo__sponsors__tier"> <span className="EventInfo__sponsors__tier-text">{tierName}</span> </div> ); lastTier = tierName; } sponsors.push(<Sponsor key={'sponsor' + i} { ... sponsor} lite={lite} />) }); // Social var dataStore = this.context.dataStore; var eventTwitter = dataStore.getSettings().eventTwitter; var eventFacebook = dataStore.getSettings().eventFacebookPageId; return ( <Container fill scrollable={scrollable} ref="scrollContainer" className="EventInfo"> <div className="EventInfo__hero"> <div className="EventInfo__hero-inner"> <div className="EventInfo__hero_title">METRO AG Headquarters</div> <div className="EventInfo__hero_address">Metrostraße 1, 40235 Düsseldorf</div> <Tappable onTap={this.openAddress} className="EventInfo__hero_button button">Get Directions</Tappable> <div className="EventInfo__hero_date">October 1st, 2015 Düsseldorf, Germany</div> </div> </div> <div className="EventInfo__summary text-block">METRO meet IT 2015 is the occasion to meet CIOs to learn, socialize and have fun in the beautiful city of Düsseldorf with great food, entertainment, connectivity and more!</div> <div className="button-table"> <Tappable onTap={this.openTwitter.bind(this, eventTwitter)} className="button-table__item EventInfo__link"> <span className="button-table__item__icon EventInfo__link__icon--twitter ion-social-twitter" /> <div className="button-table__item__label">@meetit2015</div> </Tappable> <Tappable onTap={this.openFacebook.bind(this, eventFacebook)} className="button-table__item EventInfo__link"> <span className="button-table__item__icon EventInfo__link__icon--facebook ion-social-facebook" /> <div className="button-table__item__label">METRO meet IT 2015</div> </Tappable> </div> <PeopleList people={organisers} heading="Organisers" previousView="event" className="EventInfo__organisers" /> <div className="EventInfo__sponsors"> <div className="EventInfo__sponsors__heading">Sponsors</div> {sponsors} </div> </Container> ); } });
MobTemplates = { shroom : { tick : function(mob) { if(Math.random() > 0.7) { GameState.lord.energy += 1; Stage.flashText(mob.pos.x, mob.pos.y, '+'); } }, }, } Rules = { mobsAt : function(x, y) { var result = []; $.each(GameState.mobs, function(idx, mob) { if(mob.pos.x == x && mob.pos.y == y) result.push(mob); }); return(result); }, createMob : function(mob) { if(!mob.width) mob.width = Config.tileSize; mob.img = mob.type+'.png'; if(MobTemplates[mob.type]) $.each(MobTemplates[mob.type], function(k, v) { mob[k] = v; }); if(mob.create) mob.create(mob); Stage.placeAsset(mob); GameState.mobs.push(mob); }, }
'use strict'; const Bcrypt = require('bcrypt'); const BasicAuth = require('hapi-auth-basic'); exports.register = (server, options, next) => { const basicValidation = (request, username, password, callback) => { const user = server.users[username]; if (!user) { return callback(null, false) } Bcrypt.compare(password, user.password, function (err, isValid) { callback(err, isValid, { 'id': user.id, 'username': user.username, 'role': user.role }) }) }; server.register(BasicAuth); server.auth.strategy('simple', 'basic', { validateFunc: basicValidation }); server.auth.default('simple'); next() }; exports.register.attributes = { name: 'auth-wrapper' };
module.exports = function(body, user, serverCallback) { serverCallback('Available commands: STOP, /sub [category name], /unsub [category name]. To send a message, text "#[category name] [your renting item]"'); };
import {expect} from 'chai'; import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import TokenizerInput from '../src/TokenizerInput.react'; import states from '../example/exampleData'; describe('<TokenizerInput>', () => { it('renders a TokenizerInput', () => { const instance = ReactTestUtils.renderIntoDocument( <TokenizerInput options={[]} selected={[]} text="" /> ); const inputNode = ReactTestUtils.findRenderedDOMComponentWithClass( instance, 'bootstrap-tokenizer' ); expect(inputNode).to.exist; }); it('renders tokens in the tokenizer', () => { const instance = ReactTestUtils.renderIntoDocument( <TokenizerInput options={states} selected={states.slice(0, 3)} text="" /> ); const tokens = ReactTestUtils.scryRenderedDOMComponentsWithClass( instance, 'token' ); expect(tokens.length).to.equal(3); }); });
import createBrowserHistory from 'history/createBrowserHistory'; import { routerMiddleware } from 'react-router-redux'; import logger from 'redux-logger'; import { createStore, applyMiddleware } from 'redux'; import createSagaMiddleware from 'redux-saga'; import rootSaga from '../sagas'; import reducers from '../reducers'; // Create a history const history = createBrowserHistory(); // Create middlewares const sagaMiddleware = createSagaMiddleware(); const middlewares = [ routerMiddleware(history), sagaMiddleware, ]; if (process.env.NODE_ENV !== 'production') { middlewares.push(logger); } // Create store const store = createStore( reducers, applyMiddleware(...middlewares), ); sagaMiddleware.run(rootSaga); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers/index'); store.replaceReducer(nextRootReducer); }); } const action = (type, payload) => store.dispatch({ type, payload }); // Export history and store export { history, store, action };
/* * jQuery UI Effects 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/ */ jQuery.effects||function(f,j){function m(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1], 16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return n.transparent;return n[f.trim(c).toLowerCase()]}function s(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor"}while(c=c.parentNode);return m(b)}function o(){var c=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle, a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase()});a[d]=c[b]}}else for(b in c)if(typeof c[b]==="string")a[b]=c[b];return a}function p(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in t||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a]}return c}function u(c,a){var b={_:0},d;for(d in a)if(c[d]!=a[d])b[d]=a[d];return b}function k(c,a,b,d){if(typeof c=="object"){d= a;b=null;a=c;c=a.effect}if(f.isFunction(a)){d=a;b=null;a={}}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={}}if(f.isFunction(b)){d=b;b=null}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:b in f.fx.speeds?f.fx.speeds[b]:f.fx.speeds._default;d=d||a.complete;return[c,a,b,d]}function l(c){if(!c||typeof c==="number"||f.fx.speeds[c])return true;if(typeof c==="string"&&!f.effects[c])return true;return false}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor", "borderTopColor","borderColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=s(b.elem,a);b.end=m(b.end);b.colorInit=true}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")"}});var n={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0, 0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],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],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211, 211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},q=["add","remove","toggle"],t={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b, d){if(f.isFunction(b)){d=b;b=null}return this.queue(function(){var e=f(this),g=e.attr("style")||" ",h=p(o.call(this)),r,v=e.attr("class");f.each(q,function(w,i){c[i]&&e[i+"Class"](c[i])});r=p(o.call(this));e.attr("class",v);e.animate(u(h,r),{queue:false,duration:a,easing:b,complete:function(){f.each(q,function(w,i){c[i]&&e[i+"Class"](c[i])});if(typeof e.attr("style")=="object"){e.attr("style").cssText="";e.attr("style").cssText=g}else e.attr("style",g);d&&d.apply(this,arguments);f.dequeue(this)}})})}; f.fn.extend({_addClass:f.fn.addClass,addClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c)},_removeClass:f.fn.removeClass,removeClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c)},_toggleClass:f.fn.toggleClass,toggleClass:function(c,a,b,d,e){return typeof a=="boolean"||a===j?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this, [{toggle:c},a,b,d])},switchClass:function(c,a,b,d,e){return f.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e])}});f.extend(f.effects,{version:"1.8.16",save:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.data("ec.storage."+a[b],c[0].style[a[b]])},restore:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]))},setMode:function(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a},getBaseline:function(c,a){var b;switch(c[0]){case "top":b= 0;break;case "middle":b=0.5;break;case "bottom":b=1;break;default:b=c[0]/a.height}switch(c[1]){case "left":c=0;break;case "center":c=0.5;break;case "right":c=1;break;default:c=c[1]/a.width}return{x:c,y:b}},createWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent();var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}), d=document.activeElement;c.wrap(b);if(c[0]===d||f.contains(c[0],d))f(d).focus();b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(e,g){a[g]=c.css(g);if(isNaN(parseInt(a[g],10)))a[g]="auto"});c.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})}return b.css(a).show()},removeWrapper:function(c){var a,b=document.activeElement; if(c.parent().is(".ui-effects-wrapper")){a=c.parent().replaceWith(c);if(c[0]===b||f.contains(c[0],b))f(b).focus();return a}return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=k.apply(this,arguments),b={options:a[1],duration:a[2],callback:a[3]};a=b.options.mode;var d=f.effects[c];if(f.fx.off||!d)return a?this[a](b.duration,b.callback):this.each(function(){b.callback&&b.callback.call(this)}); return d.call(this,b)},_show:f.fn.show,show:function(c){if(l(c))return this._show.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(l(c))return this._hide.apply(this,arguments);else{var a=k.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(l(c)||typeof c==="boolean"||f.isFunction(c))return this.__toggle.apply(this,arguments);else{var a=k.apply(this, arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c,a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQuad:function(c,a,b,d,e){if((a/=e/2)<1)return d/ 2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+b},easeInQuint:function(c,a,b, d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b},easeInExpo:function(c,a,b,d,e){return a==0?b:d*Math.pow(2,10*(a/e-1))+b},easeOutExpo:function(c, a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)*a)+1)+b},easeInElastic:function(c,a,b, d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b},easeOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b},easeInOutElastic:function(c,a,b,d,e){c=1.70158;var g= 0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b},easeInBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b},easeOutBack:function(c,a,b,d,e,g){if(g==j)g=1.70158;return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b},easeInOutBack:function(c,a,b,d,e,g){if(g==j)g=1.70158; if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b},easeInBounce:function(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b},easeOutBounce:function(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b},easeInOutBounce:function(c,a,b,d,e){if(a<e/2)return f.easing.easeInBounce(c,a*2,0,d,e)*0.5+b;return f.easing.easeOutBounce(c, a*2-e,0,d,e)*0.5+d*0.5+b}})}(jQuery); ;/* * jQuery UI Effects Transfer 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Transfer * * Depends: * jquery.effects.core.js */ (function(e){e.effects.transfer=function(a){return this.queue(function(){var b=e(this),c=e(a.options.to),d=c.offset();c={top:d.top,left:d.left,height:c.innerHeight(),width:c.innerWidth()};d=b.offset();var f=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(a.options.className).css({top:d.top,left:d.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(c,a.duration,a.options.easing,function(){f.remove();a.callback&&a.callback.apply(b[0],arguments); b.dequeue()})})}})(jQuery); ;
$('.like-buttons-containers').on('click', '.like-button', function(e) { var url = $(this).attr('url'); $.getJSON( url ); $(this).css("display", "none"); $(this).parent().children('.unlike-button').css('display', 'inline-block'); var count = parseInt($(this).parent().parent().find('.like-span:first').text()); count++; $(this).parent().parent().find('.like-span:first').text(count); }); $('.like-buttons-containers').on('click', '.unlike-button', function(e) { var url = $(this).attr('url'); $.getJSON( url ); $(this).css("display", "none"); $(this).parent().children('.like-button').css('display', 'inline-block'); var count = parseInt($(this).parent().parent().find('.like-span:first').text()); count--; $(this).parent().parent().find('.like-span:first').text(count); }); $('.like-buttons-containers').on('click', '.comment-button', function(e) { var url = $(this).attr('url'); var target = $(this).attr('data-target'); var form_contaier = $('#reply-form-' + target); var loader = $("#loader-" + target); $(form_contaier).html(""); $(form_contaier).css("display", "none"); $(loader).css("display", "block"); $.get(url, function(data) { $(form_contaier).html(data); $(form_contaier).css("display", "block"); $(loader).css("display", "none"); }); }); $('.like-buttons-containers').on('submit', 'div.reply-form-container form', function(e) { e.preventDefault(); var $this = $(this); var target = $this.attr("data-target"); var loader = $("#loader-" + target); var form_container = $('#reply-form-' + target); $(loader).css("display", "block"); $(form_container).css("display", "none"); $.ajax({ url: $this.attr('action'), type: $this.attr('method'), data: $this.serialize(), success: function(html) { $this.parent().parent().find('.reply-comments:first').prepend(html); form_container.html(""); $(loader).css("display", "none"); } }); });
import './nav-menu-item.css'; const navMenuItemTemplate = ` <md-list-item ng-click="$ctrl.onItemClick($ctrl.item)"> <md-icon md-svg-icon="{{ $ctrl.item.icon }}" aria-label="{{ $ctrl.item.title }}"></md-icon> <p class="md-body-2">{{ $ctrl.item.title }}</p> </md-list-item> `; class NavMenuItemController { } export default { require: '^navMenu', bindings: { item: '<', onItemClick: '&' }, template: navMenuItemTemplate, controller: NavMenuItemController, };
import "babel-polyfill"; /* globals document */ // import "babel-core/register"; import React from 'react'; import { render } from 'react-dom'; import { Router, hashHistory } from 'react-router'; import { Provider } from 'react-redux'; import routes from './routes'; import configureStore from 'store/configure_store'; import * as gh from 'actions/github.act.js'; const store = configureStore(hashHistory); render( <Provider store={store}> <Router history={hashHistory} routes={routes} /> </Provider>, document.getElementById('root') );
window.onload = (function () { var students = [ { firstname: 'Jelio', lastname: 'Jelev', age: 15,}, { firstname: 'Boiko', lastname: 'Atanasov', age: 23, }, { firstname: 'Dimitar', lastname: 'Ovcharov', age: 20, }, { firstname: 'Teodor', lastname: 'Mihailov', age: 27, }, ]; var studentsBetween18and24 = _.filter(students, function (student) { return student.age >= 18 && student.age <= 24; }); _.map(studentsBetween18and24, function (student) { console.log('firstname: ' + student.firstname + ', lastname: ' + student.lastname); }); }());
$(function(){ $( "#inputFecha" ).datepicker({ dateFormat: 'dd-mm-yy' }); });
import React from 'react'; import 'react-native'; import renderer from 'react-test-renderer'; import Organization from './Organization'; import organization from './Organization.mock'; it('renders correctly', () => { const tree = renderer.create( <Organization organization={organization} />, ).toJSON(); expect(tree).toMatchSnapshot(); });
module.exports = function (grunt) { /* Generates localization excel files */ grunt.registerMultiTask( "genL10nExcels", "Generate localization excel files", function () { var locale = grunt.option('locale'), locales, templateLocale = grunt.option('templateLocale') || 'en', i; if (!locale) { grunt.fail.fatal("Locale not defined."); } locales = locale.split(',').map(Function.prototype.call, String.prototype.trim); this.files.forEach(function (file) { file.src.map(function (filepath) { //if (filepath.indexOf('n-layerri') > -1) { var pathTokens = filepath.trim().split('/'), bundleName = pathTokens[pathTokens.length - 2]; for (i = 0; i < locales.length; i++) { grunt.config.set( 'generate-l10n-excel.' + bundleName + '_' + locales[i], [{ bundleName: bundleName, bundleDir: filepath, locale: locales[i], templateLocale: templateLocale }] ); } //} }); }); grunt.task.run('generate-l10n-excel'); } ); /* Imports lozalization excels */ grunt.registerMultiTask( "impL10nExcels", "Import localization excel file translations back to localization json.", function () { var pattern = grunt.option('pattern'), delimiter = grunt.option('delimiter') || '.', locale = grunt.option('locale'), templateLocale = grunt.option('templateLocale') || 'en'; if (!pattern) { grunt.fail.fatal("No import pattern defined"); } if (grunt.option('delimiter')) { grunt.log.writeln("User set delimiter:", delimiter); } if (grunt.option('locale')) { grunt.log.writeln("User set locale:", locale); } var files = grunt.file.expandMapping([pattern]), idx = 0; files.forEach(function (file) { file.src.map(function (filepath) { var config = { delimiter: delimiter, file: filepath, templateLocale: templateLocale }; if (locale) { config.locale = locale; } grunt.config.set( 'import-l10n-excel.' + new Date().getTime() + "" + idx, [config] ); idx++; }); }); grunt.task.run('import-l10n-excel'); } ); /* Generates a single localization excel */ grunt.registerMultiTask( 'generate-l10n-excel', 'Generate localization excel files for given bundles and locales', function () { var done = this.async(), AdmZip = require('adm-zip'), archiver = require('archiver'), fs = require('node-fs-extra'), me = this, bundleName = this.data[0].bundleName, bundleDir = this.data[0].bundleDir, locale = this.data[0].locale, templateLocale = this.data[0].templateLocale, rowTemplate = ' <row r="{row}" spans="1:6">\n' + ' <c r="A{row}" t="inlineStr">\n' + ' <is>\n' + ' <t>{path}<\/t>\n' + ' <\/is>\n' + ' <\/c>\n' + ' <c r="B{row}" t="inlineStr">\n' + ' <is>\n' + ' <t>{filename}<\/t>\n' + ' <\/is>\n' + ' <\/c>\n' + ' <c r="C{row}" t="inlineStr">\n' + ' <is>\n' + ' <t>{key}<\/t>\n' + ' <\/is>\n' + ' <\/c>\n' + ' <c r="D{row}" t="inlineStr">\n' + ' <is>\n' + ' <t>{value}<\/t>\n' + ' <\/is>\n' + ' <\/c>\n' + ' <c r="E{row}" t="inlineStr">\n' + ' <is>\n' + ' <t>{translation}<\/t>\n' + ' <\/is>\n' + ' <\/c>\n' + ' <c r="F{row}" t="inlineStr">\n' + ' <is>\n' + ' <t>{notes}<\/t>\n' + ' <\/is>\n' + ' <\/c>\n' + ' <\/row>\n', sourceLocale, translation, notes, worksheet, localizationDir = '..\\dist\\L10N\\' + locale, notesFile = '../docs/L10N/' + bundleDir.substring(3) + 'notes.js', worksheetFile = localizationDir + '\\' + bundleName + '_' + locale + '\\xl\\worksheets\\sheet1.xml', output, asyncCounter = 4; // decremented on async done if (!locale) { grunt.log.error('No locale defined.'); done(false); } if (!templateLocale) { grunt.log.error('No template locale defined.'); done(false); } //console.log(notesFile); var cleanup = function (finish, ret) { // delete copied template... var templateDir = localizationDir + '\\' + bundleName + '_' + locale; if (fs.existsSync(templateDir)) { fs.remove(templateDir, function (err) { if (err) { grunt.log.error('Failed to remove temporary files from ' + templateDir + ':\n' + err); } if (finish) { done(ret); } }); } else { if (finish) { done(ret); } } }; var rowIndex = 2, escape = function (value) { return value.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); }, addExcelRow = function (path, filename, key, value, translation, notes) { var row = rowTemplate.replace(/{row}/g, rowIndex); row = row.replace('{path}', escape(path)); row = row.replace('{filename}', escape(filename)); row = row.replace('{key}', escape(key)); row = row.replace('{value}', escape(value)); row = row.replace('{translation}', escape(translation)); row = row.replace('{notes}', escape(notes)); //grunt.log.writeln(row); output += row; rowIndex++; }, getTranslation = function (pathStack) { if (!translation) { return ''; } var currNode = translation, i; for (i = 0; i < pathStack.length; i++) { currNode = currNode[pathStack[i]]; if (!currNode) { return ''; } } return currNode !== 'NOT TRANSLATED' ? currNode : ''; }, getTranslationNote = function (pathStack) { if (!notes) { return ''; } var currNode = notes, i; for (i = 0; i < pathStack.length; i++) { currNode = currNode[pathStack[i]]; if (!currNode) { return ''; } } return currNode; }, printNodePath = function (node, stack) { var pathStack = stack || [], translation; // Print the node if its value is a string if (typeof node == 'string' || node instanceof String) { translation = getTranslation(pathStack); if (!translation && pathStack.join('') === 'lang') { translation = locale; } addExcelRow('/Oskari' + bundleDir.substring(2) + 'locale', locale + '.js', pathStack.join('.'), node, translation, getTranslationNote(pathStack)); } else if (( !! node) && (node.constructor === Object)) { // Node value is an object, recurse var p; for (p in node) { if (node.hasOwnProperty(p)) { pathStack.push(p); printNodePath(node[p], pathStack); pathStack.pop(); } } } else if (toString.call(node) === "[object Array]") { var i; for (i = 0; i < node.length; i++) { pathStack.push(i); printNodePath(node[i], pathStack); pathStack.pop(); } } else { // ignore... } }, writeExcelFile = function () { // write output to worksheet xml fs.writeFileSync(worksheetFile, output); // create zip file var out = fs.createWriteStream(localizationDir + '\\' + bundleName + '_' + locale + '.xlsx'), archive = archiver('zip'); out.on('close', function () { //grunt.log.writeln(bundleName + ' done, running cleanup'); cleanup(true, true); }); archive.on('error', function (err) { grunt.log.error('Failed to create excel archive:\n' + err); cleanup(true, false); }); archive.pipe(out); archive.bulk([{ expand: true, cwd: localizationDir + '\\' + bundleName + '_' + locale, src: ['*', '**/*', '**/**/*', '_rels\\.rels'] }]); archive.finalize(); }, checkAsyncStatus = function () { if (--asyncCounter === 0) { // All async tasks are done // Check that we have everything we need if (sourceLocale) { // write rows to output printNodePath(sourceLocale); // write rest of the template to output output += worksheet.substring(worksheet.indexOf('</row>') + '</row>'.length); writeExcelFile(); } else { cleanup(true, true); } } }; // Hackhack, easy way to read/load the localization files var Oskari = { registerLocalization: function (localization) { return localization; } }; var readTemplate = function (file) { // Read template worksheet if (!fs.existsSync(file)) { grunt.log.error('Template file doesn\'t exist.'); cleanup(true, false); } fs.readFile(file, { encoding: 'utf8' }, function (err, data) { if (err) { grunt.log.error('Failed to read template:\n' + err); cleanup(true, false); } else { worksheet = data; // Write worksheet to output all the way up to the end of the first row output = data.substring(0, data.indexOf('</row>') + '</row>'.length); checkAsyncStatus(); } }); }; // TODO support new locale directory structure // Read english locale // TODO move source locale to options fs.readFile(bundleDir + '\\locale\\' + templateLocale + '.js', { encoding: 'utf8' }, function (err, data) { if (err) { // We must have a source locale, fail in checkAsyncStatus when all asyncs are done grunt.log.writeln('No source location file found for ' + bundleName + ', skipping.'); } else { sourceLocale = eval(data); } checkAsyncStatus(); }); // Read old locale fs.readFile(bundleDir + '\\locale\\' + locale + '.js', { encoding: 'utf8' }, function (err, data) { if (err) { // ignore, old translation isn't mandatory //grunt.log.writeln('No old ' + locale + ' localization found for ' + bundleName); } else { try { translation = eval(data); } catch (e) { grunt.fail.fatal("Couldn't read localization file: " + bundleDir + '\\locale\\' + locale + '.js, ' + e); } } checkAsyncStatus(); }); // Read translation notes fs.readFile(notesFile, { encoding: 'utf8' }, function (err, data) { if (err) { // ignore, notes aren't mandatory //grunt.log.writeln('No translation notes found for ' + bundleName); } else { notes = JSON.parse(data); } checkAsyncStatus(); }); // make sure we have a L10N folder in dist if (!fs.existsSync(localizationDir + '\\' + bundleName + '_' + locale)) { fs.mkdirsSync(localizationDir + '\\' + bundleName + '_' + locale); } // Extract excel template to dist/L10n/bundleName_?? if (!fs.existsSync('..\\tools\\template.xlsx')) { grunt.log.error('Template excel file doesn\'t exist.'); } var zip = new AdmZip('..\\tools\\template.xlsx'); zip.extractAllTo(localizationDir + '\\' + bundleName + '_' + locale, true); readTemplate(worksheetFile); } ); /* Imports a single localization excel * oskari-import-l10n-excel */ grunt.registerMultiTask( 'import-l10n-excel', 'Import localization excel files', function () { var fs = require('fs'), file = this.data[0].file; if (!file) { grunt.fail.fatal('No file defined.'); } if (!fs.existsSync(file)) { grunt.fail.fatal('File ' + file + ' doesn\'t exist.'); } grunt.log.writeln('Importing', file); var AdmZip = require('adm-zip'), parseString = require('xml2js').parseString, sst = [], si, i, j, k, row, cell, localeDir, localeFile = null, targetFile, key, original, localized, translation, sourceLocale, me = this, delimiter = this.data[0].delimiter, locale = this.data[0].locale, templateLocale = this.data[0].templateLocale, textNode; grunt.log.writeln('Parsing', file); // xl/sharedStrings.xml, Shared strings <si><t>val, 0-based index // (partially?) styled strings <si><r><t><_>val, <si><r><t>val parseString(new AdmZip(file).readAsText('xl/sharedStrings.xml'), function (err, result) { if (result && result.sst && result.sst.si) { si = result.sst.si; for (i = 0; i < si.length; i++) { if (si[i].t) { textNode = si[i].t[0]; } else { // (partially?) styled text is chopped into pieces textNode = ""; for (j = 0, k = si[i].r.length; j < k; j++) { textNode += si[i].r[j].t[0]["_"] || si[i].r[j].t; } } if (typeof textNode == 'string' || textNode instanceof String) { sst.push(textNode.trim()); } else if (textNode.hasOwnProperty('_')) { sst.push(textNode._.trim()); } else { sst.push(''); } } } }); // Hackhack, easy way to read/load the localization files var Oskari = { registerLocalization: function (localization) { return localization; } }; // Get the original translation. Returns 'NOT TRANSLATED' if translation is not available. var getTranslation = function (pathStack) { if (!translation) { return ''; } var currNode = translation, i; for (i = 0; i < pathStack.length; i++) { currNode = currNode[pathStack[i]]; if (!currNode) { return ''; } } return currNode || ''; }; // Sets a new translation value var setNewValue = function (pathStack, val) { var currNode = sourceLocale, i, newValue = val && val.length ? val : 'NOT TRANSLATED'; for (i = 0; i < pathStack.length; i++) { if (i + 1 === pathStack.length) { if (pathStack.join('.') !== 'key') { if (currNode.hasOwnProperty(pathStack[i])) { if (currNode[pathStack[i]] && currNode[pathStack[i]].length) { // We have an old value, replace it with something (why would anyone translate an empty string?) currNode[pathStack[i]] = newValue; } else { // No previous value, set a new value only if we have one. if (val && val.length) { currNode[pathStack[i]] = newValue; } } } else { grunt.log.warn('Unknown localization key: ', pathStack.join('.')); break; } } } else { currNode = currNode[pathStack[i]]; if (!currNode) { grunt.log.warn('Unknown localization key: ', pathStack.join('.')); break; } } } }; var initLocalization = function (node, stack) { var pathStack = stack || [], p; if (typeof node == 'string' || node instanceof String) { setNewValue(pathStack, getTranslation(pathStack)); } else if (node.constructor === Object) { // Node value is an object, recurse for (p in node) { if (node.hasOwnProperty(p)) { pathStack.push(p); initLocalization(node[p], pathStack); pathStack.pop(); } } } else if (node instanceof Array) { for (p = 0; p < node.length; p++) { pathStack.push(p); initLocalization(node[p], pathStack); pathStack.pop(); } } else { // booleans, numbers... stuff that isn't translated } }; var getLocalization = function (path, fileName) { var data = null; // read template if (fs.existsSync(path + '\\en.js')) { data = fs.readFileSync(path + '\\' + templateLocale + '.js', { encoding: 'utf8' }); sourceLocale = eval(data); } else { grunt.fail.fatal('Couldn\'t read template localization:', path + '\\' + templateLocale + '.js'); } // Read old locale targetFile = path + '/' + fileName; if (fs.existsSync(targetFile)) { data = fs.readFileSync(targetFile, { encoding: 'utf8' }); translation = eval(data); } else { grunt.log.warn('Couldn\'t find old translation at ' + path + '\\' + fileName); } initLocalization(sourceLocale); }; var getCellValue = function (cell) { if (cell === null || cell === undefined) { return ''; } if (cell.v) { return sst[parseInt(cell.v)]; } else if (cell.is) { return cell.is[0].t[0].trim(); } else { return ''; } }; // xl/worksheets/sheet1.xml Table <sheetData><row><c>[<v>sharedstringid|<is><t>val] grunt.log.writeln('Reading sheet from', file); var sheet = new AdmZip(file).readAsText('xl/worksheets/sheet1.xml'); parseString(sheet, function (err, result) { if (result && result.worksheet && result.worksheet.sheetData && result.worksheet.sheetData[0].row) { // skip header row for (i = 1; i < result.worksheet.sheetData[0].row.length; i++) { cells = result.worksheet.sheetData[0].row[i].c; if (localeFile === null) { localeDir = '..\\' + getCellValue(cells[0]).substring(8); localeFile = getCellValue(cells[1]); getLocalization(localeDir, locale ? locale + '.js' : localeFile); } key = getCellValue(cells[2]); if (key && key !== 'key') { original = getCellValue(cells[3]); localized = getCellValue(cells[4]); var pathStack = key.split(delimiter); setNewValue(pathStack, localized); } } } else { grunt.fail.fatal('No parse result'); } }); // Set user defined locale if available if (locale) { setNewValue(['lang'], locale); } // Write file to targetFile fs.writeFileSync( targetFile, 'Oskari.registerLocalization(\n' + JSON.stringify(sourceLocale, null, 4) + '\n);' ); } ); };
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/components/**/*.js', 'app/users/**/*.js', 'app/login/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'utils/styled-components'; import { StaggeredMotion } from 'react-motion'; import { connect } from 'react-redux'; import colors from 'theme/color'; import { routeIsReady as routeIsReadyAction } from '../../containers/App/actions'; import selector from './selectors'; import getStaggeredMotionStyle from './helpers'; const Wrapper = styled.div` display: flex; position: absolute; flex-direction: column; width: 100%; box-sizing: border-box; min-height: 100vh; overflow: hidden; `; const Box = styled.div` height: 100%; width: ${(props) => props.width}%; position: absolute; background-color: ${(props) => props.bgColor}; z-index: 2; &:nth-child(2) { align-self: flex-end; } `; const ContentWrapper = styled.div` box-sizing: border-box; min-height: 100vh; justify-content: center; align-items: center; font-size: 40px; width: 100%; overflow-x: hidden; `; // eslint-disable-line react/prefer-stateless-function const GateAnimation = ({ children, gateStatus, isRouteReady, routeToLoad, routeIsReady, }) => ( <StaggeredMotion defaultStyles={[{ width: 50 }, { width: 50 }, { width: 0 }]} styles={getStaggeredMotionStyle(gateStatus)} > {(styles) => { if ( !gateStatus && styles[0].width === 50 && !isRouteReady && routeToLoad ) { setTimeout(() => { routeIsReady(); }, 1); } return ( <Wrapper> <Box bgColor={colors.black1} width={styles[0].width} /> <Box bgColor={colors.black1} width={styles[1].width} /> <ContentWrapper>{children}</ContentWrapper> </Wrapper> ); }} </StaggeredMotion> ); GateAnimation.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, gateStatus: PropTypes.bool, isRouteReady: PropTypes.bool, routeToLoad: PropTypes.string, routeIsReady: PropTypes.func, }; const mapStateToProps = selector(); const mapDispatchToProps = { routeIsReady: routeIsReadyAction, }; export default connect(mapStateToProps, mapDispatchToProps)(GateAnimation);
var TypeOtter = (function(obj, $) { var regMarkup = /^[\s\b]*<[\w]+/; /** * Wrap free text in paragraph tags, call recusively on children. */ function recWrap(elem) { if (elem.html() === undefined) { return elem; // ignore special elements without markup: style, script.. } var html = '', // returning markup clone = elem.clone(); // Elements to skip var skipElem = ["P", "SCRIPT", "TH", "TD", "LI", "STYLE", "FIGCAPTION", "H1", "H2", "H3", "H4", "H5", "E", "SPAN", "Q"]; if (skipElem.indexOf(clone.prop('tagName')) !== -1) { return elem; } //Check empty elements if (clone.html().trim() === '') { return elem; } // Iterate over all children while (clone.children().length > 0) { if (regMarkup.test(clone.html()) === false) { clone.html('<p>' + clone.html()); // When rendering the browser will wrap the end </p> appropriately html += clone.children(':nth-child(1)').clone().wrap('<div>').parent().html(); clone.children(':nth-child(1)').remove(); } var temp = recWrap(clone.children(':nth-child(1)')); if (temp.html() !== undefined) { html += temp.wrap('<div>').parent().html(); } clone.children(':nth-child(1)').remove(); } // Check for text after last child if (clone.html().trim() !== '' && regMarkup.test(clone.html()) === false) { clone.html('<p>' + clone.html()); html += clone.children(':nth-child(1)').clone().wrap('<div>').parent().html(); clone.children(':nth-child(1)').remove(); } // Overwrite dom html elem.html(html); return elem; } /** * Wrap plain text in paragraph tags to make dom more consistent. */ obj.wrapper = function (dom) { var html = dom.html().replace(/<!--(.*?)-->/g, ""); // Remove all html comments recWrap(dom.html(html)); }; return obj; }(TypeOtter || {}, jQuery));
__report = {"info":{"file":"lib/tokens.js","fileShort":"tokens.js","fileSafe":"tokens_js","link":"files/tokens_js/index.html"},"complexity":{"aggregate":{"line":1,"complexity":{"sloc":{"physical":16,"logical":15},"cyclomatic":1,"halstead":{"operators":{"distinct":4,"total":18,"identifiers":["__stripped__"]},"operands":{"distinct":31,"total":32,"identifiers":["__stripped__"]},"length":50,"vocabulary":35,"difficulty":2.064516129032258,"volume":256.46415084724833,"effort":529.4743759427063,"bugs":0.08548805028241611,"time":29.415243107928127},"params":0}},"functions":[],"maintainability":61.80101802662765,"params":0,"module":"tokens.js"},"jshint":{"messages":[{"severity":"error","line":16,"column":2,"message":"Missing semicolon.","source":"Missing semicolon."}]}}
import m from 'mithril'; import replaceDiacritics from 'replaceDiacritics'; const vm = postgrest.filtersVM({ full_text_index: '@@', deactivated_at: 'is.null' }), paramToString = function(p) { return (p || '').toString().trim(); }; // Set default values vm.deactivated_at(null).order({ id: 'desc' }); vm.deactivated_at.toFilter = function() { var filter = JSON.parse(vm.deactivated_at()); return filter; }; vm.full_text_index.toFilter = function() { var filter = paramToString(vm.full_text_index()); return filter && replaceDiacritics(filter) || undefined; }; export default vm;
import React from 'react'; import SearchStore from '../stores/SearchStore'; import Result from './Result'; class ResultList extends React.Component { constructor(props, context) { super(props, context); this.state = { results: SearchStore.getResults() }; this.onChange = this.onChange.bind(this); } onChange() { this.setState({results: SearchStore.getResults()}); } componentDidMount() { SearchStore.addChangeListener(this.onChange); } componentWillUnmount() { SearchStore.removeChangeListener(this.onChange); } render() { return ( <div> {this.state.results.map((result) => { return <Result key={result.id} result={result} />; })} </div> ); } } export default ResultList;
var helpers = require('./helpers') require('should') var target = 'IncreaseStreamRetentionPeriod', request = helpers.request, opts = helpers.opts.bind(null, target), randomName = helpers.randomName, assertType = helpers.assertType.bind(null, target), assertValidation = helpers.assertValidation.bind(null, target), assertNotFound = helpers.assertNotFound.bind(null, target), assertInvalidArgument = helpers.assertInvalidArgument.bind(null, target) describe('increaseStreamRetentionPeriod', function() { describe('serializations', function() { it('should return SerializationException when StreamName is not a String', function(done) { assertType('StreamName', 'String', done) }) it('should return SerializationException when RetentionPeriodHours is not an Integer', function(done) { assertType('RetentionPeriodHours', 'Integer', done) }) }) describe('validations', function() { it('should return ValidationException for no StreamName', function(done) { assertValidation({}, [ 'Value null at \'retentionPeriodHours\' failed to satisfy constraint: ' + 'Member must not be null', 'Value null at \'streamName\' failed to satisfy constraint: ' + 'Member must not be null', ], done) }) it('should return ValidationException for empty StreamName', function(done) { assertValidation({StreamName: '', RetentionPeriodHours: -1}, [ 'Value \'-1\' at \'retentionPeriodHours\' failed to satisfy constraint: ' + 'Member must have value greater than or equal to 1', 'Value \'\' at \'streamName\' failed to satisfy constraint: ' + 'Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+', 'Value \'\' at \'streamName\' failed to satisfy constraint: ' + 'Member must have length greater than or equal to 1', ], done) }) it('should return ValidationException for long StreamName', function(done) { var name = new Array(129 + 1).join('a') assertValidation({StreamName: name, RetentionPeriodHours: 24}, [ 'Value \'' + name + '\' at \'streamName\' failed to satisfy constraint: ' + 'Member must have length less than or equal to 128', ], done) }) it('should return ValidationException for retention period greater than 168', function(done) { assertValidation({StreamName: 'a', RetentionPeriodHours: 169}, [ 'Value \'169\' at \'retentionPeriodHours\' failed to satisfy constraint: ' + 'Member must have value less than or equal to 168', ], done) }) it('should return InvalidArgumentException for retention period less than 24', function(done) { assertInvalidArgument({StreamName: helpers.testStream, RetentionPeriodHours: 23}, 'Minimum allowed retention period is 24 hours. ' + 'Requested retention period (23 hours) is too short.', done) }) it('should return ResourceNotFoundException if stream does not exist', function(done) { var name1 = randomName() assertNotFound({StreamName: name1, RetentionPeriodHours: 25}, 'Stream ' + name1 + ' under account ' + helpers.awsAccountId + ' not found.', done) }) }) describe('functionality', function() { it('should increase stream retention period', function(done) { this.timeout(100000) request(opts({ StreamName: helpers.testStream, RetentionPeriodHours: 25, }), function(err, res) { if (err) return done(err) res.statusCode.should.equal(200) helpers.waitUntilActive(helpers.testStream, function(err, res) { if (err) return done(err) res.body.StreamDescription.RetentionPeriodHours.should.eql(25) request(opts({ StreamName: helpers.testStream, RetentionPeriodHours: 25, }), function(err, res) { if (err) return done(err) res.statusCode.should.equal(200) assertInvalidArgument({StreamName: helpers.testStream, RetentionPeriodHours: 24}, 'Requested retention period (24 hours) for stream ' + helpers.testStream + ' can not be shorter than existing retention period (25 hours).' + ' Use DecreaseRetentionPeriod API.', function(err) { if (err) return done(err) request(helpers.opts('DecreaseStreamRetentionPeriod', { StreamName: helpers.testStream, RetentionPeriodHours: 24, }), function(err, res) { if (err) return done(err) res.statusCode.should.equal(200) helpers.waitUntilActive(helpers.testStream, function(err, res) { if (err) return done(err) res.body.StreamDescription.RetentionPeriodHours.should.eql(24) done() }) }) }) }) }) }) }) }) })
// @flow // // Copyright (c) 2018 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. import logInputToQsParser from "./log-input-to-qs-parser.js"; import logQsToInputParser from "./log-qs-to-input-parser.js"; import logCompleter from "./log-completer.js"; import type { $scopeT, $locationT } from "angular"; import type { qsStreamT } from "../qs-stream/qs-stream-module.js"; import type { PropagateChange } from "../extend-scope-module.js"; export function controller( $scope: $scopeT, $location: $locationT, $stateParams: Object, qsStream: qsStreamT, propagateChange: PropagateChange ) { "ngInject"; const p = propagateChange.bind(null, $scope, this, "qs"); const qs$ = qsStream($stateParams); qs$.map(x => x.qs).through(p); $scope.$on("$destroy", () => { qs$.destroy(); this.tzPickerB.endBroadcast(); }); Object.assign(this, { parserFormatter: { parser: logInputToQsParser, formatter: logQsToInputParser }, completer: logCompleter, onSubmit: $location.search.bind($location) }); } export default { bindings: { tzPickerB: "<" }, controller, template: ` <div class="container log container-full"> <div class="row"> <div class="col-xs-12"> <parsely-box on-submit="::$ctrl.onSubmit(qs)" query="$ctrl.qs" parser-formatter="::$ctrl.parserFormatter" completer="::$ctrl.completer(value, cursorPosition)" ></parsely-box> <tz-picker stream="::$ctrl.tzPickerB"></tz-picker> </div> </div> <ui-loader-view class="log-table"></ui-loader-view> </div> ` };
/* * Copyright (C) 2012 Google 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 GOOGLE 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 GOOGLE 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. */ /** * @constructor * @extends {WebInspector.VBox} */ WebInspector.NavigatorView = function() { WebInspector.VBox.call(this); this.registerRequiredCSS("sources/navigatorView.css"); this.element.classList.add("navigator-container"); <<<<<<< HEAD var scriptsOutlineElement = this.element.createChild("div", "outline-disclosure navigator"); var scriptsTreeElement = scriptsOutlineElement.createChild("ol"); this._scriptsTree = new WebInspector.NavigatorTreeOutline(scriptsTreeElement); ======= var scriptsOutlineElement = this.element.createChild("div", "navigator"); this._scriptsTree = new TreeOutline(); this._scriptsTree.setComparator(WebInspector.NavigatorView._treeElementsCompare); this._scriptsTree.element.classList.add("outline-disclosure"); scriptsOutlineElement.appendChild(this._scriptsTree.element); >>>>>>> 793500c01f8bb29015a736c79cc8d3e4322558bd this.setDefaultFocusedElement(this._scriptsTree.element); /** @type {!Map.<!WebInspector.UISourceCode, !WebInspector.NavigatorUISourceCodeTreeNode>} */ this._uiSourceCodeNodes = new Map(); /** @type {!Map.<!WebInspector.NavigatorTreeNode, !Map.<string, !WebInspector.NavigatorFolderTreeNode>>} */ this._subfolderNodes = new Map(); this._rootNode = new WebInspector.NavigatorRootTreeNode(this); this._rootNode.populate(); this.element.addEventListener("contextmenu", this.handleContextMenu.bind(this), false); } WebInspector.NavigatorView.Events = { ItemSelected: "ItemSelected", ItemRenamed: "ItemRenamed", } WebInspector.NavigatorView.Types = { Root: "Root", Domain: "Domain", Folder: "Folder", UISourceCode: "UISourceCode", FileSystem: "FileSystem" } /** * @param {string} type * @return {string} */ WebInspector.NavigatorView.iconClassForType = function(type) { if (type === WebInspector.NavigatorView.Types.Domain) return "navigator-domain-tree-item"; if (type === WebInspector.NavigatorView.Types.FileSystem) return "navigator-folder-tree-item"; return "navigator-folder-tree-item"; } /** * @param {!WebInspector.ContextMenu} contextMenu */ WebInspector.NavigatorView.appendAddFolderItem = function(contextMenu) { function addFolder() { WebInspector.isolatedFileSystemManager.addFileSystem(); } var addFolderLabel = WebInspector.UIString.capitalize("Add ^folder to ^workspace"); contextMenu.appendItem(addFolderLabel, addFolder); } WebInspector.NavigatorView.prototype = { setWorkspace: function(workspace) { this._workspace = workspace; this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectRemoved, this._projectRemoved.bind(this), this); }, wasShown: function() { if (this._loaded) return; this._loaded = true; this._workspace.uiSourceCodes().forEach(this._addUISourceCode.bind(this)); }, /** * @param {!WebInspector.UISourceCode} uiSourceCode * @return {boolean} */ accept: function(uiSourceCode) { return !uiSourceCode.project().isServiceProject(); }, /** * @param {!WebInspector.UISourceCode} uiSourceCode */ _addUISourceCode: function(uiSourceCode) { if (!this.accept(uiSourceCode)) return; var projectNode = this._projectNode(uiSourceCode.project()); var folderNode = this._folderNode(projectNode, uiSourceCode.parentPath()); var uiSourceCodeNode = new WebInspector.NavigatorUISourceCodeTreeNode(this, uiSourceCode); this._uiSourceCodeNodes.set(uiSourceCode, uiSourceCodeNode); folderNode.appendChild(uiSourceCodeNode); }, /** * @param {!WebInspector.Event} event */ _uiSourceCodeAdded: function(event) { var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data); this._addUISourceCode(uiSourceCode); }, /** * @param {!WebInspector.Event} event */ _uiSourceCodeRemoved: function(event) { var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data); this._removeUISourceCode(uiSourceCode); }, /** * @param {!WebInspector.Event} event */ _projectRemoved: function(event) { var project = /** @type {!WebInspector.Project} */ (event.data); project.removeEventListener(WebInspector.Project.Events.DisplayNameUpdated, this._updateProjectNodeTitle, this); var uiSourceCodes = project.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) this._removeUISourceCode(uiSourceCodes[i]); }, /** * @param {!WebInspector.Project} project * @return {!WebInspector.NavigatorTreeNode} */ _projectNode: function(project) { if (!project.displayName()) return this._rootNode; var projectNode = this._rootNode.child(project.id()); if (!projectNode) { projectNode = this._createProjectNode(project); this._rootNode.appendChild(projectNode); } return projectNode; }, /** * @param {!WebInspector.Project} project * @return {!WebInspector.NavigatorTreeNode} */ _createProjectNode: function(project) { var type = project.type() === WebInspector.projectTypes.FileSystem ? WebInspector.NavigatorView.Types.FileSystem : WebInspector.NavigatorView.Types.Domain; var projectNode = new WebInspector.NavigatorFolderTreeNode(this, project, project.id(), type, "", project.displayName()); project.addEventListener(WebInspector.Project.Events.DisplayNameUpdated, this._updateProjectNodeTitle, this); return projectNode; }, /** * @param {!WebInspector.Event} event */ _updateProjectNodeTitle: function(event) { var project = /** @type {!WebInspector.Project} */(event.target); var projectNode = this._rootNode.child(project.id()); if (!projectNode) return; projectNode.treeNode().titleText = project.displayName(); }, /** * @param {!WebInspector.NavigatorTreeNode} projectNode * @param {string} folderPath * @return {!WebInspector.NavigatorTreeNode} */ _folderNode: function(projectNode, folderPath) { if (!folderPath) return projectNode; var subfolderNodes = this._subfolderNodes.get(projectNode); if (!subfolderNodes) { subfolderNodes = /** @type {!Map.<string, !WebInspector.NavigatorFolderTreeNode>} */ (new Map()); this._subfolderNodes.set(projectNode, subfolderNodes); } var folderNode = subfolderNodes.get(folderPath); if (folderNode) return folderNode; var parentNode = projectNode; var index = folderPath.lastIndexOf("/"); if (index !== -1) parentNode = this._folderNode(projectNode, folderPath.substring(0, index)); var name = folderPath.substring(index + 1); folderNode = new WebInspector.NavigatorFolderTreeNode(this, null, name, WebInspector.NavigatorView.Types.Folder, folderPath, name); subfolderNodes.set(folderPath, folderNode); parentNode.appendChild(folderNode); return folderNode; }, /** * @param {!WebInspector.UISourceCode} uiSourceCode * @param {boolean=} select */ revealUISourceCode: function(uiSourceCode, select) { var node = this._uiSourceCodeNodes.get(uiSourceCode); if (!node) return; if (this._scriptsTree.selectedTreeElement) this._scriptsTree.selectedTreeElement.deselect(); this._lastSelectedUISourceCode = uiSourceCode; node.reveal(select); }, /** * @param {!WebInspector.UISourceCode} uiSourceCode * @param {boolean} focusSource */ _sourceSelected: function(uiSourceCode, focusSource) { this._lastSelectedUISourceCode = uiSourceCode; var data = { uiSourceCode: uiSourceCode, focusSource: focusSource}; this.dispatchEventToListeners(WebInspector.NavigatorView.Events.ItemSelected, data); }, /** * @param {!WebInspector.UISourceCode} uiSourceCode */ sourceDeleted: function(uiSourceCode) { }, /** * @param {!WebInspector.UISourceCode} uiSourceCode */ _removeUISourceCode: function(uiSourceCode) { var node = this._uiSourceCodeNodes.get(uiSourceCode); if (!node) return; var projectNode = this._projectNode(uiSourceCode.project()); var subfolderNodes = this._subfolderNodes.get(projectNode); var parentNode = node.parent; this._uiSourceCodeNodes.remove(uiSourceCode); parentNode.removeChild(node); node = parentNode; while (node) { parentNode = node.parent; if (!parentNode || !node.isEmpty()) break; if (subfolderNodes) subfolderNodes.remove(node._folderPath); parentNode.removeChild(node); node = parentNode; } }, /** * @param {!WebInspector.UISourceCode} uiSourceCode */ _updateIcon: function(uiSourceCode) { var node = this._uiSourceCodeNodes.get(uiSourceCode); node.updateIcon(); }, reset: function() { var nodes = this._uiSourceCodeNodes.valuesArray(); for (var i = 0; i < nodes.length; ++i) nodes[i].dispose(); this._scriptsTree.removeChildren(); this._uiSourceCodeNodes.clear(); this._subfolderNodes.clear(); this._rootNode.reset(); }, /** * @param {!Event} event */ handleContextMenu: function(event) { var contextMenu = new WebInspector.ContextMenu(event); WebInspector.NavigatorView.appendAddFolderItem(contextMenu); contextMenu.show(); }, /** * @param {!WebInspector.Project} project * @param {string} path */ _handleContextMenuRefresh: function(project, path) { project.refresh(path); }, /** * @param {!WebInspector.Project} project * @param {string} path * @param {!WebInspector.UISourceCode=} uiSourceCode */ _handleContextMenuCreate: function(project, path, uiSourceCode) { this.create(project, path, uiSourceCode); }, /** * @param {!WebInspector.UISourceCode} uiSourceCode */ _handleContextMenuRename: function(uiSourceCode) { this.rename(uiSourceCode, false); }, /** * @param {!WebInspector.Project} project * @param {string} path */ _handleContextMenuExclude: function(project, path) { var shouldExclude = window.confirm(WebInspector.UIString("Are you sure you want to exclude this folder?")); if (shouldExclude) { WebInspector.startBatchUpdate(); project.excludeFolder(path); WebInspector.endBatchUpdate(); } }, /** * @param {!WebInspector.UISourceCode} uiSourceCode */ _handleContextMenuDelete: function(uiSourceCode) { var shouldDelete = window.confirm(WebInspector.UIString("Are you sure you want to delete this file?")); if (shouldDelete) uiSourceCode.project().deleteFile(uiSourceCode.path()); }, /** * @param {!Event} event * @param {!WebInspector.UISourceCode} uiSourceCode */ handleFileContextMenu: function(event, uiSourceCode) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendApplicableItems(uiSourceCode); contextMenu.appendSeparator(); var project = uiSourceCode.project(); if (project.type() === WebInspector.projectTypes.FileSystem) { var path = uiSourceCode.parentPath(); contextMenu.appendItem(WebInspector.UIString.capitalize("Rename\u2026"), this._handleContextMenuRename.bind(this, uiSourceCode)); contextMenu.appendItem(WebInspector.UIString.capitalize("Make a ^copy\u2026"), this._handleContextMenuCreate.bind(this, project, path, uiSourceCode)); contextMenu.appendItem(WebInspector.UIString.capitalize("Delete"), this._handleContextMenuDelete.bind(this, uiSourceCode)); contextMenu.appendSeparator(); } contextMenu.show(); }, /** * @param {!Event} event * @param {!WebInspector.NavigatorFolderTreeNode} node */ handleFolderContextMenu: function(event, node) { var contextMenu = new WebInspector.ContextMenu(event); var path = "/"; var projectNode = node; while (projectNode.parent !== this._rootNode) { path = "/" + projectNode.id + path; projectNode = projectNode.parent; } var project = projectNode._project; if (project.type() === WebInspector.projectTypes.FileSystem) { contextMenu.appendItem(WebInspector.UIString.capitalize("Refresh"), this._handleContextMenuRefresh.bind(this, project, path)); contextMenu.appendItem(WebInspector.UIString.capitalize("New ^file"), this._handleContextMenuCreate.bind(this, project, path)); contextMenu.appendItem(WebInspector.UIString.capitalize("Exclude ^folder"), this._handleContextMenuExclude.bind(this, project, path)); } contextMenu.appendSeparator(); WebInspector.NavigatorView.appendAddFolderItem(contextMenu); function removeFolder() { var shouldRemove = window.confirm(WebInspector.UIString("Are you sure you want to remove this folder?")); if (shouldRemove) project.remove(); } if (project.type() === WebInspector.projectTypes.FileSystem && node === projectNode) { var removeFolderLabel = WebInspector.UIString.capitalize("Remove ^folder from ^workspace"); contextMenu.appendItem(removeFolderLabel, removeFolder); } contextMenu.show(); }, /** * @param {!WebInspector.UISourceCode} uiSourceCode * @param {boolean} deleteIfCanceled */ rename: function(uiSourceCode, deleteIfCanceled) { var node = this._uiSourceCodeNodes.get(uiSourceCode); console.assert(node); node.rename(callback.bind(this)); /** * @this {WebInspector.NavigatorView} * @param {boolean} committed */ function callback(committed) { if (!committed) { if (deleteIfCanceled) uiSourceCode.remove(); return; } this.dispatchEventToListeners(WebInspector.NavigatorView.Events.ItemRenamed, uiSourceCode); this._updateIcon(uiSourceCode); this._sourceSelected(uiSourceCode, true); } }, /** * @param {!WebInspector.Project} project * @param {string} path * @param {!WebInspector.UISourceCode=} uiSourceCodeToCopy */ create: function(project, path, uiSourceCodeToCopy) { var filePath; var uiSourceCode; /** * @this {WebInspector.NavigatorView} * @param {?string} content */ function contentLoaded(content) { createFile.call(this, content || ""); } if (uiSourceCodeToCopy) uiSourceCodeToCopy.requestContent(contentLoaded.bind(this)); else createFile.call(this); /** * @this {WebInspector.NavigatorView} * @param {string=} content */ function createFile(content) { project.createFile(path, null, content || "", fileCreated.bind(this)); } /** * @this {WebInspector.NavigatorView} * @param {?string} path */ function fileCreated(path) { if (!path) return; filePath = path; uiSourceCode = project.uiSourceCode(filePath); if (!uiSourceCode) { console.assert(uiSourceCode); return; } this._sourceSelected(uiSourceCode, false); this.revealUISourceCode(uiSourceCode, true); this.rename(uiSourceCode, true); } }, __proto__: WebInspector.VBox.prototype } /** * @constructor * @extends {WebInspector.NavigatorView} */ WebInspector.SourcesNavigatorView = function() { WebInspector.NavigatorView.call(this); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); } WebInspector.SourcesNavigatorView.prototype = { /** * @override * @param {!WebInspector.UISourceCode} uiSourceCode * @return {boolean} */ accept: function(uiSourceCode) { if (!WebInspector.NavigatorView.prototype.accept(uiSourceCode)) return false; return uiSourceCode.project().type() !== WebInspector.projectTypes.ContentScripts && uiSourceCode.project().type() !== WebInspector.projectTypes.Snippets; }, /** * @param {!WebInspector.Event} event */ _inspectedURLChanged: function(event) { var nodes = this._uiSourceCodeNodes.valuesArray(); for (var i = 0; i < nodes.length; ++i) { var uiSourceCode = nodes[i].uiSourceCode(); var inspectedPageURL = WebInspector.targetManager.inspectedPageURL(); if (inspectedPageURL && WebInspector.networkMapping.networkURL(uiSourceCode) === inspectedPageURL) this.revealUISourceCode(uiSourceCode, true); } }, /** * @override * @param {!WebInspector.UISourceCode} uiSourceCode */ _addUISourceCode: function(uiSourceCode) { WebInspector.NavigatorView.prototype._addUISourceCode.call(this, uiSourceCode); var inspectedPageURL = WebInspector.targetManager.inspectedPageURL(); if (inspectedPageURL && WebInspector.networkMapping.networkURL(uiSourceCode) === inspectedPageURL) this.revealUISourceCode(uiSourceCode, true); }, __proto__: WebInspector.NavigatorView.prototype } /** * @constructor * @extends {WebInspector.NavigatorView} */ WebInspector.ContentScriptsNavigatorView = function() { WebInspector.NavigatorView.call(this); } WebInspector.ContentScriptsNavigatorView.prototype = { /** * @override * @param {!WebInspector.UISourceCode} uiSourceCode * @return {boolean} */ accept: function(uiSourceCode) { if (!WebInspector.NavigatorView.prototype.accept(uiSourceCode)) return false; return uiSourceCode.project().type() === WebInspector.projectTypes.ContentScripts; }, __proto__: WebInspector.NavigatorView.prototype } /** <<<<<<< HEAD * @constructor * @extends {TreeOutline} * @param {!Element} element */ WebInspector.NavigatorTreeOutline = function(element) { TreeOutline.call(this, element); this.element = element; this.comparator = WebInspector.NavigatorTreeOutline._treeElementsCompare; } WebInspector.NavigatorTreeOutline.Types = { Root: "Root", Domain: "Domain", Folder: "Folder", UISourceCode: "UISourceCode", FileSystem: "FileSystem" } /** ======= >>>>>>> 793500c01f8bb29015a736c79cc8d3e4322558bd * @param {!TreeElement} treeElement1 * @param {!TreeElement} treeElement2 * @return {number} */ WebInspector.NavigatorView._treeElementsCompare = function compare(treeElement1, treeElement2) { // Insert in the alphabetical order, first domains, then folders, then scripts. function typeWeight(treeElement) { var type = treeElement.type(); if (type === WebInspector.NavigatorView.Types.Domain) { if (treeElement.titleText === WebInspector.targetManager.inspectedPageDomain()) return 1; return 2; } if (type === WebInspector.NavigatorView.Types.FileSystem) return 3; if (type === WebInspector.NavigatorView.Types.Folder) return 4; return 5; } var typeWeight1 = typeWeight(treeElement1); var typeWeight2 = typeWeight(treeElement2); var result; if (typeWeight1 > typeWeight2) result = 1; else if (typeWeight1 < typeWeight2) result = -1; else { var title1 = treeElement1.titleText; var title2 = treeElement2.titleText; result = title1.compareTo(title2); } return result; } /** * @constructor * @extends {TreeElement} * @param {string} type * @param {string} title * @param {!Array.<string>} iconClasses * @param {boolean} expandable * @param {boolean=} noIcon */ WebInspector.BaseNavigatorTreeElement = function(type, title, iconClasses, expandable, noIcon) { this._type = type; TreeElement.call(this, "", expandable); this._titleText = title; this._iconClasses = iconClasses; this._noIcon = noIcon; } WebInspector.BaseNavigatorTreeElement.prototype = { onattach: function() { this.listItemElement.removeChildren(); if (this._iconClasses) { for (var i = 0; i < this._iconClasses.length; ++i) this.listItemElement.classList.add(this._iconClasses[i]); } this.listItemElement.createChild("div", "selection"); if (!this._noIcon) this.imageElement = this.listItemElement.createChild("img", "icon"); this.titleElement = this.listItemElement.createChild("div", "base-navigator-tree-element-title"); this.titleElement.textContent = this._titleText; }, /** * @param {!Array.<string>} iconClasses */ updateIconClasses: function(iconClasses) { for (var i = 0; i < this._iconClasses.length; ++i) this.listItemElement.classList.remove(this._iconClasses[i]); this._iconClasses = iconClasses; for (var i = 0; i < this._iconClasses.length; ++i) this.listItemElement.classList.add(this._iconClasses[i]); }, onreveal: function() { if (this.listItemElement) this.listItemElement.scrollIntoViewIfNeeded(true); }, /** * @return {string} */ get titleText() { return this._titleText; }, set titleText(titleText) { if (this._titleText === titleText) return; this._titleText = titleText || ""; if (this.titleElement) { this.titleElement.textContent = this._titleText; this.titleElement.title = this._titleText; } }, /** * @return {string} */ type: function() { return this._type; }, __proto__: TreeElement.prototype } /** * @constructor * @extends {WebInspector.BaseNavigatorTreeElement} * @param {!WebInspector.NavigatorView} navigatorView * @param {string} type * @param {string} title */ WebInspector.NavigatorFolderTreeElement = function(navigatorView, type, title) { var iconClass = WebInspector.NavigatorView.iconClassForType(type); WebInspector.BaseNavigatorTreeElement.call(this, type, title, [iconClass], true); this._navigatorView = navigatorView; } WebInspector.NavigatorFolderTreeElement.prototype = { onpopulate: function() { this._node.populate(); }, onattach: function() { WebInspector.BaseNavigatorTreeElement.prototype.onattach.call(this); this.collapse(); this.listItemElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), false); }, /** * @param {!WebInspector.NavigatorFolderTreeNode} node */ setNode: function(node) { this._node = node; var paths = []; while (node && !node.isRoot()) { paths.push(node._title); node = node.parent; } paths.reverse(); this.tooltip = paths.join("/"); }, /** * @param {!Event} event */ _handleContextMenuEvent: function(event) { if (!this._node) return; this.select(); this._navigatorView.handleFolderContextMenu(event, this._node); }, __proto__: WebInspector.BaseNavigatorTreeElement.prototype } /** * @constructor * @extends {WebInspector.BaseNavigatorTreeElement} * @param {!WebInspector.NavigatorView} navigatorView * @param {!WebInspector.UISourceCode} uiSourceCode * @param {string} title */ WebInspector.NavigatorSourceTreeElement = function(navigatorView, uiSourceCode, title) { this._navigatorView = navigatorView; this._uiSourceCode = uiSourceCode; WebInspector.BaseNavigatorTreeElement.call(this, WebInspector.NavigatorView.Types.UISourceCode, title, this._calculateIconClasses(), false); this.tooltip = uiSourceCode.originURL(); } WebInspector.NavigatorSourceTreeElement.prototype = { /** * @return {!WebInspector.UISourceCode} */ get uiSourceCode() { return this._uiSourceCode; }, /** * @return {!Array.<string>} */ _calculateIconClasses: function() { return ["navigator-" + this._uiSourceCode.contentType().name() + "-tree-item"]; }, updateIcon: function() { this.updateIconClasses(this._calculateIconClasses()); }, onattach: function() { WebInspector.BaseNavigatorTreeElement.prototype.onattach.call(this); this.listItemElement.draggable = true; this.listItemElement.addEventListener("click", this._onclick.bind(this), false); this.listItemElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), false); this.listItemElement.addEventListener("mousedown", this._onmousedown.bind(this), false); this.listItemElement.addEventListener("dragstart", this._ondragstart.bind(this), false); }, _onmousedown: function(event) { if (event.which === 1) // Warm-up data for drag'n'drop this._uiSourceCode.requestContent(callback.bind(this)); /** * @param {?string} content * @this {WebInspector.NavigatorSourceTreeElement} */ function callback(content) { this._warmedUpContent = content; } }, _shouldRenameOnMouseDown: function() { if (!this._uiSourceCode.canRename()) return false; var isSelected = this === this.treeOutline.selectedTreeElement; var document = this.treeOutline.element.ownerDocument; var isFocused = this.treeOutline.element.isSelfOrAncestor(document.activeElement); return isSelected && isFocused && !WebInspector.isBeingEdited(this.treeOutline.element); }, selectOnMouseDown: function(event) { if (event.which !== 1 || !this._shouldRenameOnMouseDown()) { TreeElement.prototype.selectOnMouseDown.call(this, event); return; } setTimeout(rename.bind(this), 300); /** * @this {WebInspector.NavigatorSourceTreeElement} */ function rename() { if (this._shouldRenameOnMouseDown()) this._navigatorView.rename(this.uiSourceCode, false); } }, _ondragstart: function(event) { event.dataTransfer.setData("text/plain", this._warmedUpContent); event.dataTransfer.effectAllowed = "copy"; return true; }, /** * @override * @return {boolean} */ onspace: function() { this._navigatorView._sourceSelected(this.uiSourceCode, true); return true; }, /** * @param {!Event} event */ _onclick: function(event) { this._navigatorView._sourceSelected(this.uiSourceCode, false); }, /** * @override * @return {boolean} */ ondblclick: function(event) { var middleClick = event.button === 1; this._navigatorView._sourceSelected(this.uiSourceCode, !middleClick); return false; }, /** * @override * @return {boolean} */ onenter: function() { this._navigatorView._sourceSelected(this.uiSourceCode, true); return true; }, /** * @override * @return {boolean} */ ondelete: function() { this._navigatorView.sourceDeleted(this.uiSourceCode); return true; }, /** * @param {!Event} event */ _handleContextMenuEvent: function(event) { this.select(); this._navigatorView.handleFileContextMenu(event, this._uiSourceCode); }, __proto__: WebInspector.BaseNavigatorTreeElement.prototype } /** * @constructor * @param {string} id */ WebInspector.NavigatorTreeNode = function(id) { this.id = id; /** @type {!Map.<string, !WebInspector.NavigatorTreeNode>} */ this._children = new Map(); } WebInspector.NavigatorTreeNode.prototype = { /** * @return {!TreeElement} */ treeNode: function() { throw "Not implemented"; }, dispose: function() { }, /** * @return {boolean} */ isRoot: function() { return false; }, /** * @return {boolean} */ hasChildren: function() { return true; }, populate: function() { if (this.isPopulated()) return; if (this.parent) this.parent.populate(); this._populated = true; this.wasPopulated(); }, wasPopulated: function() { var children = this.children(); for (var i = 0; i < children.length; ++i) this.treeNode().appendChild(/** @type {!TreeElement} */ (children[i].treeNode())); }, /** * @param {!WebInspector.NavigatorTreeNode} node */ didAddChild: function(node) { if (this.isPopulated()) this.treeNode().appendChild(/** @type {!TreeElement} */ (node.treeNode())); }, /** * @param {!WebInspector.NavigatorTreeNode} node */ willRemoveChild: function(node) { if (this.isPopulated()) this.treeNode().removeChild(/** @type {!TreeElement} */ (node.treeNode())); }, /** * @return {boolean} */ isPopulated: function() { return this._populated; }, /** * @return {boolean} */ isEmpty: function() { return !this._children.size; }, /** * @param {string} id * @return {?WebInspector.NavigatorTreeNode} */ child: function(id) { return this._children.get(id) || null; }, /** * @return {!Array.<!WebInspector.NavigatorTreeNode>} */ children: function() { return this._children.valuesArray(); }, /** * @param {!WebInspector.NavigatorTreeNode} node */ appendChild: function(node) { this._children.set(node.id, node); node.parent = this; this.didAddChild(node); }, /** * @param {!WebInspector.NavigatorTreeNode} node */ removeChild: function(node) { this.willRemoveChild(node); this._children.remove(node.id); delete node.parent; node.dispose(); }, reset: function() { this._children.clear(); } } /** * @constructor * @extends {WebInspector.NavigatorTreeNode} * @param {!WebInspector.NavigatorView} navigatorView */ WebInspector.NavigatorRootTreeNode = function(navigatorView) { WebInspector.NavigatorTreeNode.call(this, ""); this._navigatorView = navigatorView; } WebInspector.NavigatorRootTreeNode.prototype = { /** * @override * @return {boolean} */ isRoot: function() { return true; }, /** * @override * @return {!TreeElement} */ treeNode: function() { return this._navigatorView._scriptsTree.rootElement(); }, __proto__: WebInspector.NavigatorTreeNode.prototype } /** * @constructor * @extends {WebInspector.NavigatorTreeNode} * @param {!WebInspector.NavigatorView} navigatorView * @param {!WebInspector.UISourceCode} uiSourceCode */ WebInspector.NavigatorUISourceCodeTreeNode = function(navigatorView, uiSourceCode) { WebInspector.NavigatorTreeNode.call(this, uiSourceCode.name()); this._navigatorView = navigatorView; this._uiSourceCode = uiSourceCode; this._treeElement = null; } WebInspector.NavigatorUISourceCodeTreeNode.prototype = { /** * @return {!WebInspector.UISourceCode} */ uiSourceCode: function() { return this._uiSourceCode; }, updateIcon: function() { if (this._treeElement) this._treeElement.updateIcon(); }, /** * @override * @return {!TreeElement} */ treeNode: function() { if (this._treeElement) return this._treeElement; this._treeElement = new WebInspector.NavigatorSourceTreeElement(this._navigatorView, this._uiSourceCode, ""); this.updateTitle(); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.TitleChanged, this._titleChanged, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this); this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this); return this._treeElement; }, /** * @param {boolean=} ignoreIsDirty */ updateTitle: function(ignoreIsDirty) { if (!this._treeElement) return; var titleText = this._uiSourceCode.displayName(); if (!ignoreIsDirty && (this._uiSourceCode.isDirty() || this._uiSourceCode.hasUnsavedCommittedChanges())) titleText = "*" + titleText; this._treeElement.titleText = titleText; }, /** * @override * @return {boolean} */ hasChildren: function() { return false; }, dispose: function() { if (!this._treeElement) return; this._uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.TitleChanged, this._titleChanged, this); this._uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this); this._uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this); }, _titleChanged: function(event) { this.updateTitle(); }, _workingCopyChanged: function(event) { this.updateTitle(); }, _workingCopyCommitted: function(event) { this.updateTitle(); }, /** * @param {boolean=} select */ reveal: function(select) { this.parent.populate(); this.parent.treeNode().expand(); this._treeElement.reveal(); if (select) this._treeElement.select(true); }, /** * @param {function(boolean)=} callback */ rename: function(callback) { if (!this._treeElement) return; // Tree outline should be marked as edited as well as the tree element to prevent search from starting. var treeOutlineElement = this._treeElement.treeOutline.element; WebInspector.markBeingEdited(treeOutlineElement, true); /** * @param {!Element} element * @param {string} newTitle * @param {string} oldTitle * @this {WebInspector.NavigatorUISourceCodeTreeNode} */ function commitHandler(element, newTitle, oldTitle) { if (newTitle !== oldTitle) { this._treeElement.titleText = newTitle; this._uiSourceCode.rename(newTitle, renameCallback.bind(this)); return; } afterEditing.call(this, true); } /** * @param {boolean} success * @this {WebInspector.NavigatorUISourceCodeTreeNode} */ function renameCallback(success) { if (!success) { WebInspector.markBeingEdited(treeOutlineElement, false); this.updateTitle(); this.rename(callback); return; } afterEditing.call(this, true); } /** * @this {WebInspector.NavigatorUISourceCodeTreeNode} */ function cancelHandler() { afterEditing.call(this, false); } /** * @param {boolean} committed * @this {WebInspector.NavigatorUISourceCodeTreeNode} */ function afterEditing(committed) { WebInspector.markBeingEdited(treeOutlineElement, false); this.updateTitle(); this._treeElement.treeOutline.focus(); if (callback) callback(committed); } var editingConfig = new WebInspector.InplaceEditor.Config(commitHandler.bind(this), cancelHandler.bind(this)); this.updateTitle(true); WebInspector.InplaceEditor.startEditing(this._treeElement.titleElement, editingConfig); treeOutlineElement.window().getSelection().setBaseAndExtent(this._treeElement.titleElement, 0, this._treeElement.titleElement, 1); }, __proto__: WebInspector.NavigatorTreeNode.prototype } /** * @constructor * @extends {WebInspector.NavigatorTreeNode} * @param {!WebInspector.NavigatorView} navigatorView * @param {?WebInspector.Project} project * @param {string} id * @param {string} type * @param {string} folderPath * @param {string} title */ WebInspector.NavigatorFolderTreeNode = function(navigatorView, project, id, type, folderPath, title) { WebInspector.NavigatorTreeNode.call(this, id); this._navigatorView = navigatorView; this._project = project; this._type = type; this._folderPath = folderPath; this._title = title; } WebInspector.NavigatorFolderTreeNode.prototype = { /** * @override * @return {!TreeElement} */ treeNode: function() { if (this._treeElement) return this._treeElement; this._treeElement = this._createTreeElement(this._title, this); return this._treeElement; }, /** * @return {!TreeElement} */ _createTreeElement: function(title, node) { var treeElement = new WebInspector.NavigatorFolderTreeElement(this._navigatorView, this._type, title); treeElement.setNode(node); return treeElement; }, wasPopulated: function() { if (!this._treeElement || this._treeElement._node !== this) return; this._addChildrenRecursive(); }, _addChildrenRecursive: function() { var children = this.children(); for (var i = 0; i < children.length; ++i) { var child = children[i]; this.didAddChild(child); if (child instanceof WebInspector.NavigatorFolderTreeNode) child._addChildrenRecursive(); } }, _shouldMerge: function(node) { return this._type !== WebInspector.NavigatorView.Types.Domain && node instanceof WebInspector.NavigatorFolderTreeNode; }, didAddChild: function(node) { function titleForNode(node) { return node._title; } if (!this._treeElement) return; var children = this.children(); if (children.length === 1 && this._shouldMerge(node)) { node._isMerged = true; this._treeElement.titleText = this._treeElement.titleText + "/" + node._title; node._treeElement = this._treeElement; this._treeElement.setNode(node); return; } var oldNode; if (children.length === 2) oldNode = children[0] !== node ? children[0] : children[1]; if (oldNode && oldNode._isMerged) { delete oldNode._isMerged; var mergedToNodes = []; mergedToNodes.push(this); var treeNode = this; while (treeNode._isMerged) { treeNode = treeNode.parent; mergedToNodes.push(treeNode); } mergedToNodes.reverse(); var titleText = mergedToNodes.map(titleForNode).join("/"); var nodes = []; treeNode = oldNode; do { nodes.push(treeNode); children = treeNode.children(); treeNode = children.length === 1 ? children[0] : null; } while (treeNode && treeNode._isMerged); if (!this.isPopulated()) { this._treeElement.titleText = titleText; this._treeElement.setNode(this); for (var i = 0; i < nodes.length; ++i) { delete nodes[i]._treeElement; delete nodes[i]._isMerged; } return; } var oldTreeElement = this._treeElement; var treeElement = this._createTreeElement(titleText, this); for (var i = 0; i < mergedToNodes.length; ++i) mergedToNodes[i]._treeElement = treeElement; oldTreeElement.parent.appendChild(treeElement); oldTreeElement.setNode(nodes[nodes.length - 1]); oldTreeElement.titleText = nodes.map(titleForNode).join("/"); oldTreeElement.parent.removeChild(oldTreeElement); this._treeElement.appendChild(oldTreeElement); if (oldTreeElement.expanded) treeElement.expand(); } if (this.isPopulated()) this._treeElement.appendChild(node.treeNode()); }, willRemoveChild: function(node) { if (node._isMerged || !this.isPopulated()) return; this._treeElement.removeChild(node._treeElement); }, __proto__: WebInspector.NavigatorTreeNode.prototype }
(function () { 'use strict'; angular .module('rtsApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('document', { parent: 'entity', url: '/document', data: { authorities: ['ROLE_USER'], pageTitle: 'rtsApp.documentRTS.home.title' }, views: { 'content@': { templateUrl: 'app/entities/document-rts/document-rts.html', controller: 'DocumentRTSController', controllerAs: 'vm' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('documentRTS'); $translatePartialLoader.addPart('contentType'); $translatePartialLoader.addPart('global'); return $translate.refresh(); }] } }) .state('document.new', { parent: 'entity', url: '/document/new', data: { authorities: ['ROLE_USER'], pageTitle: 'rtsApp.content.detail.title' }, views: { 'content@': { templateUrl: 'app/entities/document-rts/document-rts-write.html', controller: 'DocumentRTSWriteController', controllerAs: 'vm' }, 'documentrts@app': { templateUrl: 'app/entities/document-rts/document-rts-stuff.new.html', controller: 'DocumentRTSStuffController', controllerAs: 'vm' } }, resolve: { entity: function () { return { title: "Unknown Title", author: null, content: [{ id: "p1", type: "paragraph", content: "" }], type: null, thump: null, thumpContentType: null, id: null }; }, translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('content'); $translatePartialLoader.addPart('contentType'); return $translate.refresh(); }] } }) .state('document.new.stuff', { parent: 'document.new', url: '/stuff', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function ($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/document-rts/document-rts-stuff-dialog.html', controller: 'DocumentRTSStuffDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: ['DocumentRTSDepositary', function (documentRTSDepositary) { return documentRTSDepositary.getDocument(); }] } }).result.then(function () { $state.go('document.new'); }, function () { $state.go('document.new'); }); }] }) .state('document.edit', { parent: 'entity', url: '/document/{id}/edit', data: { authorities: ['ROLE_USER'], pageTitle: 'rtsApp.documentRTS.detail.title' }, views: { 'content@': { templateUrl: 'app/entities/document-rts/document-rts-write.html', controller: 'DocumentRTSWriteController', controllerAs: 'vm' }, 'documentrts@app': { templateUrl: 'app/entities/document-rts/document-rts-stuff.edit.html', controller: 'DocumentRTSStuffController', controllerAs: 'vm' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('documentRTS'); $translatePartialLoader.addPart('contentType'); return $translate.refresh(); }], entity: ['$stateParams', 'DocumentRTS', function ($stateParams, DocumentRTS) { return DocumentRTS.get({id: $stateParams.id}).$promise; }] } }) .state('document.edit.stuff', { parent: 'document.edit', url: '/stuff', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function ($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/document-rts/document-rts-stuff-dialog.html', controller: 'DocumentRTSStuffDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: ['DocumentRTSDepositary', function (documentRTSDepositary) { return documentRTSDepositary.getDocument(); }] } }).result.then(function () { $state.go('document-rts-edit'); }, function () { $state.go('document-rts-edit'); }); }] }) .state('document.view', { parent: 'entity', url: '/document/{id}/view', data: { authorities: [], pageTitle: 'rtsApp.documentRTS.view.title' }, views: { 'content@': { templateUrl: 'app/entities/document-rts/document-rts-view.html', controller: 'DocumentRTSWriteController', controllerAs: 'vm' }, 'documentrts@app': { templateUrl: 'app/entities/document-rts/document-rts-stuff.view.html', controller: 'DocumentRTSStuffController', controllerAs: 'vm' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('documentRTS'); $translatePartialLoader.addPart('contentType'); return $translate.refresh(); }], entity: ['$stateParams', 'DocumentRTS', function ($stateParams, DocumentRTS) { return DocumentRTS.get({id: $stateParams.id}).$promise; }] } }) .state('document.delete', { parent: 'document', url: '/{id}/delete', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function ($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/document-rts/document-rts-delete-dialog.html', controller: 'DocumentRTSDeleteController', controllerAs: 'vm', size: 'md', resolve: { entity: ['DocumentRTS', function (DocumentRTS) { return DocumentRTS.get({id: $stateParams.id}).$promise; }] } }).result.then(function () { $state.go('document-rts', null, {reload: true}); }, function () { $state.go('^'); }); }] }); } })();
'use strict'; const fs = require('fs'); const path = require('path'); /* * 将文件输出base64编码字符串 * @param file : 文件路径 */ function encode(file) { let bitmap = fs.readFileSync(file); return new Buffer(bitmap).toString('base64'); } /* * 将base64编码字符串保存为文件 * @param base64Str : base64编码字符串 * @param file : 文件路径 */ function decode(base64str, file) { let bitmap = new Buffer(base64str, 'base64'); fs.writeFileSync(file, bitmap); logger.info('已保存图片文件:'+file); } /* * 保存图片 */ function save(notePath,base64Str,callback){ let filename = generateImageName() + '.jpg';//自动生成文件名 let imgPath = path.join(__dataPath, notePath,filename);//图片文件真实路径 mkdir(path.join(__dataPath,notePath)); decode(base64Str,imgPath); callback && callback(filename); } /* * 生成图片名称 */ function generateImageName(){ return 'img' + new Date().getTime(); } /* * 创建文件目录 */ function mkdir(dir){ if(!fs.existsSync(dir)){ fs.mkdirSync(dir); } } module.exports.save=save;
/** * a HUD container and child items */ game.HUD = game.HUD || {}; game.HUD.Container = me.ObjectContainer.extend({ init: function() { // call the constructor this.parent(); // persistent across level change this.isPersistent = true; // non collidable this.collidable = false; // make sure our object is always draw first this.z = Infinity; // give a name this.name = "HUD"; // add our child score object at the top left corner this.addChild(new game.HUD.ScoreItem(5, 5)); } }); /** * a basic HUD item to display score */ game.HUD.ScoreItem = me.Renderable.extend({ /** * constructor */ init: function(x, y) { // call the parent constructor // (size does not matter here) this.parent(new me.Vector2d(x, y), 10, 10); // local copy of the global score this.stepsFont = new me.Font('gamefont', 80, '#000', 'center'); // make sure we use screen coordinates this.floating = true; }, update: function() { return true; }, draw: function (context) { if (game.data.start && me.state.isCurrent(me.state.PLAY)) this.stepsFont.draw(context, game.data.steps, me.video.getWidth()/2, 10); } }); var BackgroundLayer = me.ImageLayer.extend({ init: function(image, z, speed) { name = image; width = 900; height = 600; ratio = 1; this.fixed = speed > 0 ? false : true; // call parent constructor this.parent(name, width, height, image, z, ratio); }, update: function() { if (!this.fixed) { if (this.pos.x >= this.imagewidth - 1) this.pos.x = 0; this.pos.x += this.speed; } return true; } });
var gulp = require('gulp'); var util = require('gulp-util'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var clean = require('gulp-clean-css'); var less = require('gulp-less'); var watch = require('gulp-watch'); var browserSync = require('browser-sync').create(); var sourceMaps = require('gulp-sourcemaps'); var Path = { BaseDir: './', Dist: { CSS: './dist/css', JS: './dist/js' }, Src:{ LESS: './src/less/*.less', JS: './src/js/*.js', Modules: './src/less/modules/*.less' } }; var path = require('path'); '' gulp.task('less', function() { gulp.src(Path.Src.LESS) .pipe(sourceMaps.init()) .pipe(less({ paths:[ path.join(__dirname,'less','includes') ] })) .pipe(clean()) .pipe(rename({ suffix: '.min' })) .pipe(sourceMaps.write('./')) .pipe(gulp.dest(Path.Dist.CSS)); }); gulp.task('js',function() { gulp.src(Path.Src.JS) .pipe(sourceMaps.init()) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(sourceMaps.write('./maps')) .pipe(gulp.dest(Path.Dist.JS)); }); gulp.task('default', [ 'js', 'less', 'browersync' ], function() { gulp.watch([Path.Src.LESS, Path.Src.Modules],function(event){ util.log('File '+event.path+' was '+event.type+', running tasks...'); gulp.run('less'); }); gulp.watch([ Path.Src.JS ], function(event){ util.log('File '+event.path+' was '+event.type+', running tasks...'); gulp.run('js'); }); }); gulp.task('browersync',function() { browserSync.init([Path.Src.JS, Path.Src.LESS, Path.Src.Modules],{ server: {baseDir: Path.BaseDir} }); gulp.watch(Path.BaseDir + '**/*.*').on('change', browserSync.reload); }); gulp.task('build', function() { gulp.run('less'); gulp.run('js'); });
!function(t){"use strict";t.fn.bootstrapTable.locales["ar-SA"]={formatLoadingMessage:function(){return"جاري التحميل, يرجى الإنتظار..."},formatRecordsPerPage:function(t){return t+" سجل لكل صفحة"},formatShowingRows:function(t,n,r){return"الظاهر "+t+" إلى "+n+" من "+r+" سجل"},formatSearch:function(){return"بحث"},formatNoMatches:function(){return"لا توجد نتائج مطابقة للبحث"},formatPaginationSwitch:function(){return"إخفاءإظهار ترقيم الصفحات"},formatRefresh:function(){return"تحديث"},formatToggle:function(){return"تغيير"},formatColumns:function(){return"أعمدة"}},t.extend(t.fn.bootstrapTable.defaults,t.fn.bootstrapTable.locales["ar-SA"])}(jQuery);
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); var aurelia_pal_1 = require("aurelia-pal"); var aurelia_validation_1 = require("aurelia-validation"); var ui_validation_1 = require("./utils/ui-validation"); var ui_constants_1 = require("./utils/ui-constants"); var ui_utils_1 = require("./utils/ui-utils"); require("lodash"); require("moment"); require("numeral"); require("./libs/countries"); require("./libs/currencies"); require("./libs/filetypes"); require("./libs/phonelib"); require("./libs/window"); var ld = require("lodash"); var km = require("kramed"); var mm = require("moment"); var nm = require("numeral"); exports._ = ld; exports.kramed = km; exports.moment = mm; exports.numeral = nm; __export(require("./utils/ui-application")); __export(require("./utils/ui-constants")); __export(require("./utils/ui-dialog")); __export(require("./utils/ui-event")); __export(require("./utils/ui-format")); __export(require("./utils/ui-http")); __export(require("./utils/ui-model")); __export(require("./utils/ui-tree-model")); __export(require("./utils/ui-utils")); require("./elements/core/ui-grid"); require("./elements/core/ui-page"); require("./elements/core/ui-viewport"); require("./elements/inputs/ui-button"); require("./elements/inputs/ui-date"); require("./elements/inputs/ui-form"); require("./elements/inputs/ui-input"); require("./elements/inputs/ui-lists"); require("./elements/inputs/ui-markdown"); require("./elements/inputs/ui-options"); require("./elements/inputs/ui-phone"); require("./elements/inputs/ui-textarea"); require("./elements/components/ui-alerts"); require("./elements/components/ui-bars"); require("./elements/components/ui-breadcrumb"); require("./elements/components/ui-datagrid"); require("./elements/components/ui-dg-columns"); require("./elements/components/ui-drawer"); require("./elements/components/ui-dropdown"); require("./elements/components/ui-menu"); require("./elements/components/ui-panel"); require("./elements/components/ui-sidebar"); require("./elements/components/ui-tab"); require("./elements/components/ui-tree"); require("./attributes/ui-badge"); require("./attributes/ui-ribbon"); require("./attributes/ui-tooltip"); require("./attributes/md-view"); require("./value-converters/ui-lodash"); require("./value-converters/ui-text"); require("text!./ui-glyphs.html"); function configure(config, configCallback) { ui_utils_1.UIUtils.auContainer = config.container; document.documentElement.classList.add(window.browserAgent()); aurelia_validation_1.ValidationController.prototype.validateTrigger = aurelia_validation_1.validateTrigger.changeOrBlur; config.container.registerHandler('ui-validator', function (container) { return container.get(ui_validation_1.UIValidationRenderer); }); config.globalResources(aurelia_pal_1.PLATFORM.moduleName('./elements/core/ui-grid'), aurelia_pal_1.PLATFORM.moduleName('./elements/core/ui-page'), aurelia_pal_1.PLATFORM.moduleName('./elements/core/ui-viewport')); config.globalResources(aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-button'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-date'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-form'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-input'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-lists'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-options'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-phone'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-textarea'), aurelia_pal_1.PLATFORM.moduleName('./elements/inputs/ui-markdown')); config.globalResources(aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-alerts'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-bars'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-breadcrumb'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-datagrid'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-dg-columns'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-drawer'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-dropdown'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-menu'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-panel'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-sidebar'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-tab'), aurelia_pal_1.PLATFORM.moduleName('./elements/components/ui-tree')); config.globalResources(aurelia_pal_1.PLATFORM.moduleName('./attributes/ui-badge'), aurelia_pal_1.PLATFORM.moduleName('./attributes/ui-ribbon'), aurelia_pal_1.PLATFORM.moduleName('./attributes/ui-tooltip'), aurelia_pal_1.PLATFORM.moduleName('./attributes/md-view')); config.globalResources(aurelia_pal_1.PLATFORM.moduleName('./value-converters/ui-lodash'), aurelia_pal_1.PLATFORM.moduleName('./value-converters/ui-text')); var Configure = { title: function (t) { ui_constants_1.UIConstants.Title = t; return Configure; }, subTitle: function (t) { ui_constants_1.UIConstants.SubTitle = t; return Configure; }, version: function (t) { ui_constants_1.UIConstants.Version = t; return Configure; }, appKey: function (t) { ui_constants_1.UIConstants.AppKey = t; return Configure; }, apiUrl: function (t) { ui_constants_1.UIConstants.Http.BaseUrl = t; return Configure; }, apiHeaders: function (t) { ui_constants_1.UIConstants.Http.Headers = t; return Configure; }, sendAuthHeader: function (t) { ui_constants_1.UIConstants.Http.AuthorizationHeader = t; return Configure; }, languages: function (l) { ui_constants_1.UIConstants.Languages = l; return Configure; } }; if (configCallback !== undefined && typeof configCallback === 'function') { configCallback(Configure); } var validator = ui_utils_1.UIUtils.lazy(aurelia_validation_1.Validator); aurelia_validation_1.ValidationRules .customRule('url', function (value, obj) { return value === null || value === undefined || value === '' || (/^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/).test(value); }, '\${$displayName } is not a valid url.'); aurelia_validation_1.ValidationRules .customRule('phone', function (value, obj) { return value === null || value === undefined || value === '' || PhoneLib.isValid(value); }, '\${$displayName } is not a valid phone number.'); aurelia_validation_1.ValidationRules .customRule('number', function (value, obj, min, max) { return value === null || value === undefined || value === '' || (isNumber(value) && value >= (isEmpty(min) ? Number.MIN_VALUE : min) && value <= (isEmpty(max) ? Number.MAX_VALUE : max)); }, '\${$displayName} must be an number value between \${$config.min} and \${$config.max}.', function (min, max) { return ({ min: min, max: max }); }); aurelia_validation_1.ValidationRules .customRule('decimal', function (value, obj, min, max) { return value === null || value === undefined || value === '' || (isDecimal(value) && value >= (isEmpty(min) ? Number.MIN_VALUE : min) && value <= (isEmpty(max) ? Number.MAX_VALUE : max)); }, '\${$displayName} must be a decimal value between \${$config.min} and \${$config.max}.', function (min, max) { return ({ min: min, max: max }); }); aurelia_validation_1.ValidationRules .customRule('language', function (map, obj, langs) { if (langs === void 0) { langs = ''; } var promises = []; map.__errored__ = []; exports._.forEach(map, function (model, key) { if (model && key != '__errored__') { promises.push(validator.validateObject(model) .then(function (e) { if (exports._.filter(e, ['valid', false]).length > 0) { map.__errored__.push(key); return true; } return false; })); } }); return Promise.all(promises).then(function (e) { return exports._.filter(e).length == 0; }); }, 'Some language entries contain invalid values'); exports._.mixin({ 'findByValues': function (collection, property, values) { if (exports._.isArray(collection)) { return exports._.filter(collection, function (item) { return exports._.indexOf(values, item[property] + '') > -1; }); } else { var ret_1 = []; exports._.forEach(collection, function (list) { ret_1.concat(exports._.filter(list, function (item) { return exports._.indexOf(values, item[property] + '') > -1; })); }); return ret_1; } }, 'removeByValues': function (collection, property, values) { if (exports._.isArray(collection)) { return exports._.remove(collection, function (item) { return exports._.indexOf(values, item[property] + '') > -1; }) || []; } else { var ret_2 = []; exports._.forEach(collection, function (list, key) { ret_2 = ret_2.concat(exports._.remove(list, function (item) { return exports._.indexOf(values, item[property] + '') > -1; })); }); return ret_2; } }, 'findDeep': function (collection, property, value) { if (exports._.isArray(collection)) { return exports._.find(collection, function (item) { return item[property] + '' === value + ''; }); } else { var ret_3; exports._.forEach(collection, function (item) { ret_3 = exports._.find(item, function (v) { return v[property] + '' === value + ''; }); return ret_3 === undefined; }); return ret_3 || {}; } }, 'findChildren': function (collection, listProperty, property, value) { var ret; exports._.forEach(collection, function (item) { ret = exports._.find(item[listProperty], function (v) { return v[property] + '' === value + ''; }); return ret === undefined; }); return ret || {}; } }); } exports.configure = configure;
export default { _id: '60eea4803b352ff0441d4843', type: 'form', components: [ { label: 'Day', hideInputLabels: false, inputsLabelPosition: 'top', useLocaleSettings: false, tableView: false, fields: { day: { hide: false }, month: { hide: false }, year: { hide: false } }, key: 'day', type: 'day', input: true, defaultValue: '00/00/0000' }, { type: 'button', label: 'Submit', key: 'submit', disableOnInvalid: true, input: true, tableView: false } ], title: 'dat test', display: 'form', controller: '', name: 'dateTest', path: 'datetest', };
var cHelpers = require('./helpers'), gruntMod = require('grunt'); var PYTHON_BINARY = 'python'; // path to depswriter from closure lib path var DEPSWRITER = '/closure/bin/build/depswriter.py'; var depsWriter = {}; /** * Perform validations for given options * * @return {boolean|Object} false if error */ depsWriter.validate = function validate( options ) { // --- // check depsExec existence // --- // check for closure lib path var libPath = options.closureLibraryPath, depsExec; if (!libPath) { // check for direct assignment of depswriter script depsExec = options.depswriter; if (!depsExec) { cHelpers.log.error('One of ' + 'closureLibraryPath'.red + ' or ' + 'depswriter'.red + ' properties are required'); return false; } } else { depsExec = libPath + DEPSWRITER; } depsExec = gruntMod.template.process(depsExec); if (!gruntMod.file.isFile( depsExec )) { cHelpers.log.error('depswriter file/path not valid: ' + depsExec.red); return false; } return true; }; /** * Prepare and compile the depswriter command we will execute * * @param {Object} options The options. * @param {Object} fileObj The (grunt) file object. * @return {string|boolean} boolean false if we failed, command string if all ok */ depsWriter.createCommand = function createCommand( options, fileObj ) { // get python binary var pythonBinary = options.pythonBinary || PYTHON_BINARY; var cmd = pythonBinary + ' '; // define the depsWriter executable var depsExec = options.depswriter || options.closureLibraryPath + DEPSWRITER; depsExec = gruntMod.template.process( depsExec ); cmd += depsExec + ' '; // // Check for root, root_with_prefix and path_with_depspath options // var directives = ['root', 'root_with_prefix', 'path_with_depspath'], directive = directives.shift(); while(directive) { if ( options.hasOwnProperty(directive) ) { cmd += cHelpers.makeParam( options[directive], '--' + directive + '=', true); } directive = directives.shift(); } // --- // check if output file is defined // --- var dest = fileObj.dest; if (dest && dest.length) { gruntMod.file.write(dest, ''); // create the file if it's not there. cmd += ' --output_file=' + gruntMod.template.process(dest); } // --- // Check for file targets... // --- var files = gruntMod.file.expand(fileObj.src || {}); for (var i = 0, len = files.length; i < len; i++) { cmd += ' ' + files[i]; } return cmd; }; module.exports = depsWriter;
// All code points in the `Kaithi` script as per Unicode v8.0.0: [ 0x11080, 0x11081, 0x11082, 0x11083, 0x11084, 0x11085, 0x11086, 0x11087, 0x11088, 0x11089, 0x1108A, 0x1108B, 0x1108C, 0x1108D, 0x1108E, 0x1108F, 0x11090, 0x11091, 0x11092, 0x11093, 0x11094, 0x11095, 0x11096, 0x11097, 0x11098, 0x11099, 0x1109A, 0x1109B, 0x1109C, 0x1109D, 0x1109E, 0x1109F, 0x110A0, 0x110A1, 0x110A2, 0x110A3, 0x110A4, 0x110A5, 0x110A6, 0x110A7, 0x110A8, 0x110A9, 0x110AA, 0x110AB, 0x110AC, 0x110AD, 0x110AE, 0x110AF, 0x110B0, 0x110B1, 0x110B2, 0x110B3, 0x110B4, 0x110B5, 0x110B6, 0x110B7, 0x110B8, 0x110B9, 0x110BA, 0x110BB, 0x110BC, 0x110BD, 0x110BE, 0x110BF, 0x110C0, 0x110C1 ];
'use strict'; const AstNodeInfo = require('../helpers/ast-node-info'); const Rule = require('./base'); module.exports = class NoInvalidMeta extends Rule { logNode({ node, message }) { return this.log({ message, line: node.loc && node.loc.start.line, column: node.loc && node.loc.start.column, source: this.sourceForNode(node), }); } visitor() { return { ElementNode(node) { const isMeta = node.tag === 'meta'; const hasMetaRedirect = AstNodeInfo.hasAttribute(node, 'http-equiv'); const contentAttr = AstNodeInfo.hasAttribute(node, 'content'); const contentAttrValue = AstNodeInfo.elementAttributeValue(node, 'content'); if (isMeta && hasMetaRedirect) { if (contentAttr) { // if there is a semicolon, it is a REDIRECT and should not have a delay value greater than zero if (contentAttrValue.includes(';')) { if (contentAttrValue.charAt(0) !== '0') { this.log({ message: 'a meta redirect should not have a delay value greater than zero', line: node.loc && node.loc.start.line, column: node.loc && node.loc.start.column, source: this.sourceForNode(node), }); } } else { // eslint-disable-next-line radix if (parseInt(contentAttrValue) <= 72000) { this.log({ message: 'a meta refresh should have a delay greater than 72000 seconds', line: node.loc && node.loc.start.line, column: node.loc && node.loc.start.column, source: this.sourceForNode(node), }); } } } } // Looks for spaces because Apple allowed spaces in their spec. let userScalableRegExp = /user-scalable(\s*?)=(\s*?)no/gim; if (contentAttrValue.match(userScalableRegExp)) { this.log({ message: 'a meta viewport should not restrict user-scalable', line: node.loc && node.loc.start.line, column: node.loc && node.loc.start.column, source: this.sourceForNode(node), }); } if (contentAttrValue.includes('maximum-scale')) { this.log({ message: 'a meta viewport should not set a maximum scale on content', line: node.loc && node.loc.start.line, column: node.loc && node.loc.start.column, source: this.sourceForNode(node), }); } }, }; } };
// @flow import buildCommon from "../buildCommon"; import defineFunction from "../defineFunction"; import delimiter from "../delimiter"; import mathMLTree from "../mathMLTree"; import ParseError from "../ParseError"; import utils from "../utils"; import {assertNodeType, checkSymbolNodeType} from "../parseNode"; import * as html from "../buildHTML"; import * as mml from "../buildMathML"; import type Options from "../Options"; import type {AnyParseNode, ParseNode, SymbolParseNode} from "../parseNode"; import type {FunctionContext} from "../defineFunction"; // Extra data needed for the delimiter handler down below const delimiterSizes = { "\\bigl" : {mclass: "mopen", size: 1}, "\\Bigl" : {mclass: "mopen", size: 2}, "\\biggl": {mclass: "mopen", size: 3}, "\\Biggl": {mclass: "mopen", size: 4}, "\\bigr" : {mclass: "mclose", size: 1}, "\\Bigr" : {mclass: "mclose", size: 2}, "\\biggr": {mclass: "mclose", size: 3}, "\\Biggr": {mclass: "mclose", size: 4}, "\\bigm" : {mclass: "mrel", size: 1}, "\\Bigm" : {mclass: "mrel", size: 2}, "\\biggm": {mclass: "mrel", size: 3}, "\\Biggm": {mclass: "mrel", size: 4}, "\\big" : {mclass: "mord", size: 1}, "\\Big" : {mclass: "mord", size: 2}, "\\bigg" : {mclass: "mord", size: 3}, "\\Bigg" : {mclass: "mord", size: 4}, }; const delimiters = [ "(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "\u230a", "\u230b", "\\lceil", "\\rceil", "\u2308", "\u2309", "<", ">", "\\langle", "\u27e8", "\\rangle", "\u27e9", "\\lt", "\\gt", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "\u27ee", "\u27ef", "\\lmoustache", "\\rmoustache", "\u23b0", "\u23b1", "/", "\\backslash", "|", "\\vert", "\\|", "\\Vert", "\\uparrow", "\\Uparrow", "\\downarrow", "\\Downarrow", "\\updownarrow", "\\Updownarrow", ".", ]; type IsMiddle = {delim: string, options: Options}; // Delimiter functions function checkDelimiter( delim: AnyParseNode, context: FunctionContext, ): SymbolParseNode { const symDelim = checkSymbolNodeType(delim); if (symDelim && utils.contains(delimiters, symDelim.text)) { return symDelim; } else { throw new ParseError( "Invalid delimiter: '" + (symDelim ? symDelim.text : JSON.stringify(delim)) + "' after '" + context.funcName + "'", delim); } } defineFunction({ type: "delimsizing", names: [ "\\bigl", "\\Bigl", "\\biggl", "\\Biggl", "\\bigr", "\\Bigr", "\\biggr", "\\Biggr", "\\bigm", "\\Bigm", "\\biggm", "\\Biggm", "\\big", "\\Big", "\\bigg", "\\Bigg", ], props: { numArgs: 1, }, handler: (context, args) => { const delim = checkDelimiter(args[0], context); return { type: "delimsizing", mode: context.parser.mode, size: delimiterSizes[context.funcName].size, mclass: delimiterSizes[context.funcName].mclass, delim: delim.text, }; }, htmlBuilder: (group, options) => { if (group.delim === ".") { // Empty delimiters still count as elements, even though they don't // show anything. return buildCommon.makeSpan([group.mclass]); } // Use delimiter.sizedDelim to generate the delimiter. return delimiter.sizedDelim( group.delim, group.size, options, group.mode, [group.mclass]); }, mathmlBuilder: (group) => { const children = []; if (group.delim !== ".") { children.push(mml.makeText(group.delim, group.mode)); } const node = new mathMLTree.MathNode("mo", children); if (group.mclass === "mopen" || group.mclass === "mclose") { // Only some of the delimsizing functions act as fences, and they // return "mopen" or "mclose" mclass. node.setAttribute("fence", "true"); } else { // Explicitly disable fencing if it's not a fence, to override the // defaults. node.setAttribute("fence", "false"); } return node; }, }); function assertParsed(group: ParseNode<"leftright">) { if (!group.body) { throw new Error("Bug: The leftright ParseNode wasn't fully parsed."); } } defineFunction({ type: "leftright-right", names: ["\\right"], props: { numArgs: 1, }, handler: (context, args) => { // \left case below triggers parsing of \right in // `const right = parser.parseFunction();` // uses this return value. return { type: "leftright-right", mode: context.parser.mode, delim: checkDelimiter(args[0], context).text, }; }, }); defineFunction({ type: "leftright", names: ["\\left"], props: { numArgs: 1, }, handler: (context, args) => { const delim = checkDelimiter(args[0], context); const parser = context.parser; // Parse out the implicit body ++parser.leftrightDepth; // parseExpression stops before '\\right' const body = parser.parseExpression(false); --parser.leftrightDepth; // Check the next token parser.expect("\\right", false); const right = assertNodeType(parser.parseFunction(), "leftright-right"); return { type: "leftright", mode: parser.mode, body, left: delim.text, right: right.delim, }; }, htmlBuilder: (group, options) => { assertParsed(group); // Build the inner expression const inner = html.buildExpression(group.body, options, true, ["mopen", "mclose"]); let innerHeight = 0; let innerDepth = 0; let hadMiddle = false; // Calculate its height and depth for (let i = 0; i < inner.length; i++) { // Property `isMiddle` not defined on `span`. See comment in // "middle"'s htmlBuilder. // $FlowFixMe if (inner[i].isMiddle) { hadMiddle = true; } else { innerHeight = Math.max(inner[i].height, innerHeight); innerDepth = Math.max(inner[i].depth, innerDepth); } } // The size of delimiters is the same, regardless of what style we are // in. Thus, to correctly calculate the size of delimiter we need around // a group, we scale down the inner size based on the size. innerHeight *= options.sizeMultiplier; innerDepth *= options.sizeMultiplier; let leftDelim; if (group.left === ".") { // Empty delimiters in \left and \right make null delimiter spaces. leftDelim = html.makeNullDelimiter(options, ["mopen"]); } else { // Otherwise, use leftRightDelim to generate the correct sized // delimiter. leftDelim = delimiter.leftRightDelim( group.left, innerHeight, innerDepth, options, group.mode, ["mopen"]); } // Add it to the beginning of the expression inner.unshift(leftDelim); // Handle middle delimiters if (hadMiddle) { for (let i = 1; i < inner.length; i++) { const middleDelim = inner[i]; // Property `isMiddle` not defined on `span`. See comment in // "middle"'s htmlBuilder. // $FlowFixMe const isMiddle: IsMiddle = middleDelim.isMiddle; if (isMiddle) { // Apply the options that were active when \middle was called inner[i] = delimiter.leftRightDelim( isMiddle.delim, innerHeight, innerDepth, isMiddle.options, group.mode, []); } } } let rightDelim; // Same for the right delimiter if (group.right === ".") { rightDelim = html.makeNullDelimiter(options, ["mclose"]); } else { rightDelim = delimiter.leftRightDelim( group.right, innerHeight, innerDepth, options, group.mode, ["mclose"]); } // Add it to the end of the expression. inner.push(rightDelim); return buildCommon.makeSpan(["minner"], inner, options); }, mathmlBuilder: (group, options) => { assertParsed(group); const inner = mml.buildExpression(group.body, options); if (group.left !== ".") { const leftNode = new mathMLTree.MathNode( "mo", [mml.makeText(group.left, group.mode)]); leftNode.setAttribute("fence", "true"); inner.unshift(leftNode); } if (group.right !== ".") { const rightNode = new mathMLTree.MathNode( "mo", [mml.makeText(group.right, group.mode)]); rightNode.setAttribute("fence", "true"); inner.push(rightNode); } return mml.makeRow(inner); }, }); defineFunction({ type: "middle", names: ["\\middle"], props: { numArgs: 1, }, handler: (context, args) => { const delim = checkDelimiter(args[0], context); if (!context.parser.leftrightDepth) { throw new ParseError("\\middle without preceding \\left", delim); } return { type: "middle", mode: context.parser.mode, delim: delim.text, }; }, htmlBuilder: (group, options) => { let middleDelim; if (group.delim === ".") { middleDelim = html.makeNullDelimiter(options, []); } else { middleDelim = delimiter.sizedDelim( group.delim, 1, options, group.mode, []); const isMiddle: IsMiddle = {delim: group.delim, options}; // Property `isMiddle` not defined on `span`. It is only used in // this file above. // TODO: Fix this violation of the `span` type and possibly rename // things since `isMiddle` sounds like a boolean, but is a struct. // $FlowFixMe middleDelim.isMiddle = isMiddle; } return middleDelim; }, mathmlBuilder: (group, options) => { const middleNode = new mathMLTree.MathNode( "mo", [mml.makeText(group.delim, group.mode)]); middleNode.setAttribute("fence", "true"); return middleNode; }, });
//= require vendor/rot //= require vendor/rant //= require vendor/rant.dic //= require vendor/rung //= require vendor/overprint
var webpackCfg = require('./webpack.config'); // want more? // https://github.com/krasimir/react-webpack-starter module.exports = function(config) { config.set({ basePath: '', browsers: ['PhantomJS'], files: [ 'test/loadtests.js' ], port: 8080, captureTimeout: 60000, frameworks: ['phantomjs-shim', 'mocha', 'chai'], client: { mocha: {} }, singleRun: true, reporters: ['mocha'], preprocessors: { 'test/loadtests.js': ['webpack', 'sourcemap'] }, webpack: webpackCfg, webpackServer: { noInfo: true } }); };
Array.prototype.remove = function(object) { let index = this.indexOf(object) if (index < 0) return null this.splice(index, 1) return object } let testItems = [{ description: 'Do shopping', done: true }, { description: 'Do code', done: false }, { description: 'Sleep', done: false }] Vue.component('check-list', { template: '#checkListTemplate', props: ['title'], data: () => ({ tasks: testItems, editing: false, newTaskDescription: '' }), computed: { incompleteTasksCount() { return this.tasks.filter(task => !task.done).length } }, methods: { addTask() { let description = this.newTaskDescription.trim() if (!description || !description.trim()) { alert('Please enter a name for your new task.') return } let alreadyExists = !!this.tasks .filter(task => task.description.toLowerCase() == description.toLowerCase()).length if (alreadyExists) { alert('This task already exists. Please try another.') return } this.tasks.push({ description: description.toString(), done: false }) this.$emit('tasks-changed', this.tasks) this.newTaskDescription = '' }, remove(task) { this.tasks.remove(task) this.$emit('tasks-changed', this.tasks) }, toggleDone(task) { if (this.editing) return task.done = !task.done this.$emit('tasks-changed', this.tasks) }, checkReturnKey(e) { if (e.which == 13) //enter key this.addTask() } } }) let app = new Vue({ el: '#checkListApp', methods: { synchroniseWithServer(tasks) { //alert('changed') console.log('changed') //TODO: handle server synchronisation with ajax } } })