code
stringlengths
2
1.05M
//>>built define(["dojo","dijit","dojox","dojo/require!dojox/wire/_base"],function(d,m,h){d.provide("dojox.wire.Wire");d.require("dojox.wire._base");d.declare("dojox.wire.Wire",null,{_wireClass:"dojox.wire.Wire",constructor:function(b){d.mixin(this,b);if(this.converter)if(d.isString(this.converter)){b=d.getObject(this.converter);if(d.isFunction(b))try{var a=new b;a&&!d.isFunction(a.convert)?this.converter={convert:b}:this.converter=a}catch(c){}else d.isObject(b)&&d.isFunction(b.convert)&&(this.converter=b); d.isString(this.converter)&&(this.converter=(a=h.wire._getClass(this.converter))?new a:void 0)}else d.isFunction(this.converter)&&(this.converter={convert:this.converter})},getValue:function(b){var a=void 0,a=h.wire.isWire(this.object)?this.object.getValue(b):this.object||b;if(this.property){b=this.property.split(".");for(var c in b){if(!a)return a;a=this._getPropertyValue(a,b[c])}}c=void 0;if(c=this._getValue?this._getValue(a):a)this.type&&("string"==this.type?c=c.toString():"number"==this.type? c=parseInt(c,10):"boolean"==this.type?c="false"!=c:"array"==this.type&&(d.isArray(c)||(c=[c]))),this.converter&&this.converter.convert&&(c=this.converter.convert(c,this));return c},setValue:function(b,a){var c=void 0,c=h.wire.isWire(this.object)?this.object.getValue(a):this.object||a,e=void 0,f;if(this.property){if(!c)if(h.wire.isWire(this.object))c={},this.object.setValue(c,a);else throw Error(this._wireClass+".setValue(): invalid object");for(var e=this.property.split("."),d=e.length-1,k=0;k<d;k++){var l= e[k];f=this._getPropertyValue(c,l);f||(f={},this._setPropertyValue(c,l,f));c=f}e=e[d]}if(this._setValue){if(e&&(f=this._getPropertyValue(c,e),f||(f={},this._setPropertyValue(c,e,f)),c=f),b=this._setValue(c,b),!c&&b)if(h.wire.isWire(this.object))this.object.setValue(b,a);else throw Error(this._wireClass+".setValue(): invalid object");}else if(e)this._setPropertyValue(c,e,b);else if(h.wire.isWire(this.object))this.object.setValue(b,a);else throw Error(this._wireClass+".setValue(): invalid property"); },_getPropertyValue:function(b,a){var c=void 0,e=a.indexOf("[");if(0<=e){var f=a.indexOf("]"),f=a.substring(e+1,f),g=null;0===e?g=b:(a=a.substring(0,e),(g=this._getPropertyValue(b,a))&&!d.isArray(g)&&(g=[g]));g&&(c=g[f])}else b.getPropertyValue?c=b.getPropertyValue(a):(c="get"+a.charAt(0).toUpperCase()+a.substring(1),c=this._useGet(b)?b.get(a):this._useAttr(b)?b.attr(a):b[c]?b[c]():b[a]);return c},_setPropertyValue:function(b,a,c){var e=a.indexOf("[");if(0<=e){var d=a.indexOf("]"),d=a.substring(e+ 1,d),g=null;0===e?g=b:(a=a.substring(0,e),g=this._getPropertyValue(b,a),g||(g=[],this._setPropertyValue(b,a,g)));g[d]=c}else if(b.setPropertyValue)b.setPropertyValue(a,c);else if(e="set"+a.charAt(0).toUpperCase()+a.substring(1),this._useSet(b))b.set(a,c);else if(this._useAttr(b))b.attr(a,c);else if(b[e])b[e](c);else b[a]=c},_useGet:function(b){var a=!1;d.isFunction(b.get)&&(a=!0);return a},_useSet:function(b){var a=!1;d.isFunction(b.set)&&(a=!0);return a},_useAttr:function(b){var a=!1;d.isFunction(b.attr)&& (a=!0);return a}})});
'use strict'; describe('Service: datos', function () { // load the service's module beforeEach(module('frontendApp')); // instantiate service var datos; beforeEach(inject(function (_datos_) { datos = _datos_; })); it('should do something', function () { expect(!!datos).toBe(true); }); });
OC.L10N.register( "files_external", { "Step 1 failed. Exception: %s" : "1 Urratsak huts egin du. Salbuespena: %s", "Step 2 failed. Exception: %s" : "2 Urratsak huts egin du. Salbuespena: %s", "External storage" : "Kanpoko biltegiratzea", "Google Drive App Configuration" : "Google Drive App Ezarpenak", "Error verifying OAuth2 Code for " : "Errorea gertatu da OAuth2 Kodea egiaztatzean honentzat", "Personal" : "Pertsonala", "System" : "Sistema", "Grant access" : "Baimendu sarrera", "All users. Type to select user or group." : "Erabiltzaile guztiak. Idatzi erabiltzaile edo taldea hautatzeko.", "(group)" : "(taldea)", "Saved" : "Gordeta", "Username" : "Erabiltzaile izena", "Password" : "Pasahitza", "Save" : "Gorde", "App key" : "Aplikazio gakoa", "App secret" : "App sekretua", "Client ID" : "Bezero ID", "Client secret" : "Bezeroaren Sekretua", "API key" : "APIaren gakoa", "Public key" : "Gako publikoa", "WebDAV" : "WebDAV", "URL" : "URL", "Remote subfolder" : "Urruneko azpikarpeta", "Secure https://" : "https:// segurua", "Google Drive" : "Google Drive", "Local" : "Bertakoa", "Location" : "Kokapena", "ownCloud" : "ownCloud", "Host" : "Ostalaria", "Root" : "Erroa", "Share" : "Partekatu", "SMB / CIFS using OC login" : "SMB / CIFS saioa hasteko OC erabiliz", "Username as share" : "Erabiltzaile izena elkarbanaketa bezala", "<b>Note:</b> " : "<b>Oharra:</b>", "<b>Note:</b> The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Oharra:</b> :PHPko cURL euskarria ez dago instalatuta edo gaitua. Ezinezko da %s muntatzea. Mesedez eskatu sistema administratzaleari instala dezan. ", "<b>Note:</b> \"%s\" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Oharra:</b>\"%s\" euskarria ez dago instalatuta Ezinezko da %s muntatzea. Mesedez eskatu sistema administratzaleari instala dezan. ", "No external storage configured" : "Ez da kanpo biltegiratzerik konfiguratu", "Name" : "Izena", "Storage type" : "Biltegiratze mota", "Never" : "Inoiz", "External Storage" : "Kanpoko biltegiratzea", "Folder name" : "Karpetaren izena", "Authentication" : "Autentifikazioa", "Configuration" : "Konfigurazioa", "Available for" : "Hauentzat eskuragarri", "Add storage" : "Gehitu biltegiratzea", "Delete" : "Ezabatu", "Allow users to mount the following external storage" : "Baimendu erabiltzaileak hurrengo kanpo biltegiratzeak muntatzen" }, "nplurals=2; plural=(n != 1);");
/** * Load app controllers * * @param {Object} options * @param {Function} cb */ var async = require('async'), _ = require('lodash'), buildDictionary = require('sails-build-dictionary'); module.exports = function (cb) { async.reduce(sails.config.paths.controllers, {}, function (prev, curr, callback) { buildDictionary.optional({ dirname: curr, filter: /(.+)Controller\.(js|coffee|litcoffee)$/, flattenDirectories: true, keepDirectoryPath: true, replaceExpr: /Controller/ }, function (err, controllers) { if (err) callback(err); callback(null, _.merge(prev, controllers)); }); }, cb); };
module.exports={A:{A:{"1":"A B","2":"K D hB","129":"G E"},B:{"1":"2 C d J M H I"},C:{"2":"0 1 2 3 4 6 7 8 9 eB DB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB BB CB FB YB XB"},D:{"1":"0 1 3 4 6 7 8 9 U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB BB CB FB RB MB LB kB JB NB OB PB","2":"2 F N K D G E A B C d J M H I O P Q R S T"},E:{"1":"5 D G E A B C UB VB WB p ZB","2":"F N K QB IB SB TB"},F:{"1":"0 1 5 6 C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z","129":"E B aB bB cB dB p AB fB"},G:{"1":"G KB lB mB nB oB pB qB rB sB tB","2":"IB gB EB iB jB"},H:{"1":"uB"},I:{"1":"4 zB 0B","2":"DB F vB wB xB yB EB"},J:{"2":"D A"},K:{"1":"5 L","2":"A B C p AB"},L:{"1":"JB"},M:{"2":"3"},N:{"1":"A B"},O:{"1":"1B"},P:{"1":"F 2B 3B 4B 5B 6B"},Q:{"1":"7B"},R:{"1":"8B"},S:{"2":"9B"}},B:2,C:"CSS widows & orphans"};
import React, { Component } from 'react' import { Button, Dimmer, Image, Segment } from 'semantic-ui-react' export default class DimmerExampleBlurringInverted extends Component { state = {} handleShow = () => this.setState({ active: true }) handleHide = () => this.setState({ active: false }) render() { const { active } = this.state return ( <div> <Dimmer.Dimmable as={Segment} blurring dimmed={active}> <Dimmer active={active} inverted onClickOutside={this.handleHide} /> <p> <Image src='/assets/images/wireframe/short-paragraph.png' /> </p> <p> <Image src='/assets/images/wireframe/short-paragraph.png' /> </p> </Dimmer.Dimmable> <Button.Group> <Button icon='plus' onClick={this.handleShow} /> <Button icon='minus' onClick={this.handleHide} /> </Button.Group> </div> ) } }
/*!-------------------------------------------------------------------- JAVASCRIPT "Outdated Browser" Version: 1.0.2 - 2014 author: Burocratik website: http://www.burocratik.com * @preserve -----------------------------------------------------------------------*/ var outdatedBrowser = function(options) { //Variable definition var outdated = document.getElementById("outdated"); var btnClose = document.getElementById("btnCloseUpdateBrowser"); var btnUpdate = document.getElementById("btnUpdateBrowser"); // Default settings this.defaultOpts = { bgColor: '#F25648', color: '#ffffff', lowerThan: 'transform' } if (options) { this.defaultOpts.bgColor = options.bgColor, this.defaultOpts.color = options.color; //assign css3 property to IE browser version if(options.lowerThan == 'IE8' || options.lowerThan == 'borderSpacing') { options.lowerThan = 'borderSpacing'; } else if (options.lowerThan == 'IE9' || options.lowerThan == 'boxShadow') { options.lowerThan = 'boxShadow'; } else if (options.lowerThan == 'IE10' || options.lowerThan == 'transform' || options.lowerThan == '' || typeof options.lowerThan === "undefined") { options.lowerThan = 'transform'; } else if (options.lowerThan == 'IE11' || options.lowerThan == 'borderImage') { options.lowerThan = 'borderImage'; } this.defaultOpts.lowerThan = options.lowerThan; bkgColor = this.defaultOpts.bgColor; txtColor = this.defaultOpts.color; cssProp = this.defaultOpts.lowerThan; } else { bkgColor = this.defaultOpts.bgColor; txtColor = this.defaultOpts.color; cssProp = this.defaultOpts.lowerThan; } //Define opacity and fadeIn/fadeOut functions var done = true; function function_opacity(opacity_value) { outdated.style.opacity = opacity_value / 100; outdated.style.filter = 'alpha(opacity=' + opacity_value + ')'; } function function_fade_out(opacity_value) { function_opacity(opacity_value); if (opacity_value == 1) { outdated.style.display = 'none'; done = true; } } function function_fade_in(opacity_value) { function_opacity(opacity_value); if (opacity_value == 1) { outdated.style.display = 'block'; } if (opacity_value == 100) { done = true; } } //check if element has a particular class function hasClass(element, cls) { return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1; } var supports = (function() { var div = document.createElement('div'), vendors = 'Khtml Ms O Moz Webkit'.split(' '), len = vendors.length; return function(prop) { if ( prop in div.style ) return true; prop = prop.replace(/^[a-z]/, function(val) { return val.toUpperCase(); }); while(len--) { if ( vendors[len] + prop in div.style ) { return true; } } return false; }; })(); //check for css3 property support (transform=default) if ( !supports(''+ cssProp +'') ) { if (done && outdated.style.opacity !== '1') { done = false; for (var i = 1; i <= 100; i++) { setTimeout((function (x) { return function () { function_fade_in(x) }; })(i), i * 10); } } //close button btnClose.onmousedown = function() { outdated.style.display = 'none'; return false; }; } //check settings attributes outdated.style.backgroundColor = bkgColor; //why to har to put !important on IE6 outdated.style.color = txtColor; outdated.children[0].style.color = txtColor; outdated.children[1].style.color = txtColor; //check settings attributes btnUpdate.style.color = txtColor; btnUpdate.style.borderColor = txtColor; btnClose.style.color = txtColor; //Override the update button color to match the background color btnUpdate.onmouseover = function() { this.style.color = bkgColor; this.style.backgroundColor = txtColor; }; btnUpdate.onmouseout = function() { this.style.color = txtColor; this.style.backgroundColor = bkgColor; }; }//end of function
var gulp = require('gulp'), jshint = require('gulp-jshint'), debug = require('gulp-debug'); function task(filesPaths, dest, filename) { return gulp.src(filesPaths) //.pipe(debug()) .pipe(jshint()) .pipe(jshint.reporter('default')); } module.exports = task;
module("wysihtml.dom.Sandbox", { teardown: function() { var iframe; while (iframe = document.querySelector("iframe.wysihtml-sandbox")) { iframe.parentNode.removeChild(iframe); } }, getCharset: function(doc) { var charset = doc.characterSet || doc.charset; if (/unicode|utf-8/.test(charset)) { return "utf-8"; } return charset; }, eval: function(iframeWindow, code) { try { return iframeWindow.execScript ? iframeWindow.execScript(code) : iframeWindow.eval(code); } catch(e) { return null; } }, isUnset: function(evalCode, iframeWindow) { var value = this.eval(iframeWindow, evalCode); return !value || value == wysihtml.EMPTY_FUNCTION; } }); asyncTest("Basic Test", function() { expect(8); var sandbox = new wysihtml.dom.Sandbox(function(param) { equal(param, sandbox, "The parameter passed into the readyCallback is the sandbox instance"); var iframes = document.querySelectorAll("iframe.wysihtml-sandbox"); equal(iframes.length, 1, "iFrame sandbox inserted into dom tree"); var iframe = iframes[iframes.length - 1], isIframeInvisible = iframe.width == 0 && iframe.height == 0 && iframe.frameBorder == 0; ok(isIframeInvisible, "iframe is not visible"); var isSandboxed = iframe.getAttribute("security") == "restricted"; ok(isSandboxed, "iFrame is sandboxed"); var isWindowObject = sandbox.getWindow().setInterval && sandbox.getWindow().clearInterval; ok(isWindowObject, "wysihtml.Sandbox.prototype.getWindow() works properly"); var isDocumentObject = sandbox.getDocument().appendChild && sandbox.getDocument().body; ok(isDocumentObject, "wysihtml.Sandbox.prototype.getDocument() works properly"); equal(sandbox.getIframe(), iframe, "wysihtml.Sandbox.prototype.getIframe() returns the iframe correctly"); equal(typeof(sandbox.getWindow().onerror), "function", "window.onerror is set"); start(); }); sandbox.insertInto(document.body); }); asyncTest("Security test #1", function() { expect(14); var that = this; var sandbox = new wysihtml.dom.Sandbox(function() { var iframeWindow = sandbox.getWindow(); var isSafari = wysihtml.browser.USER_AGENT.indexOf("Safari") !== -1 && wysihtml.browser.USER_AGENT.indexOf("Chrome") === 1; if (isSafari) { // This test fails in Safari 5, as it's impossible to unset a cookie there ok(true, "Cookie is NOT unset (but that's expected in Safari)"); } else { ok(that.isUnset("document.cookie", iframeWindow), "Cookie is unset"); } ok(that.isUnset("document.open", iframeWindow), "document.open is unset"); ok(that.isUnset("document.write", iframeWindow), "document.write is unset"); ok(that.isUnset("window.parent", iframeWindow), "window.parent is unset"); ok(that.isUnset("window.opener", iframeWindow), "window.opener is unset"); ok(that.isUnset("window.localStorage", iframeWindow), "localStorage is unset"); ok(that.isUnset("window.globalStorage", iframeWindow), "globalStorage is unset"); ok(that.isUnset("window.XMLHttpRequest", iframeWindow), "XMLHttpRequest is an empty function"); ok(that.isUnset("window.XDomainRequest", iframeWindow), "XDomainRequest is an empty function"); ok(that.isUnset("window.alert", iframeWindow), "alert is an empty function"); ok(that.isUnset("window.prompt", iframeWindow), "prompt is an empty function"); ok(that.isUnset("window.openDatabase", iframeWindow), "window.openDatabase is unset"); ok(that.isUnset("window.indexedDB", iframeWindow), "window.indexedDB is unset"); ok(that.isUnset("window.postMessage", iframeWindow), "window.openDatabase is unset"); start(); }); sandbox.insertInto(document.body); }); asyncTest("Security test #2", function() { expect(2); var sandbox = new wysihtml.dom.Sandbox(function() { var html = '<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" onerror="#{script}" onload="try { window.parent._hackedCookie=document.cookie; } catch(e){}; try { window.parent._hackedVariable=1; } catch(e) {}">'; sandbox.getDocument().body.innerHTML = html; setTimeout(function() { equal(window._hackedCookie || "", "", "Cookie can't be easily stolen"); equal(window._hackedVariable || 0, 0, "iFrame has no access to parent"); start(); }, 2000); }); sandbox.insertInto(document.body); }); asyncTest("Check charset & doctype", function() { expect(3); var that = this; var sandbox = new wysihtml.dom.Sandbox(function() { var iframeDocument = sandbox.getDocument(), isQuirksMode = iframeDocument.compatMode == "BackCompat"; ok(!isQuirksMode, "iFrame isn't in quirks mode"); equal(that.getCharset(iframeDocument), that.getCharset(document), "Charset correctly inherited by iframe"); iframeDocument.body.innerHTML = '<meta charset="iso-8859-1">&uuml;'; setTimeout(function() { equal(that.getCharset(iframeDocument), that.getCharset(document), "Charset isn't overwritten"); start(); }, 500); }); sandbox.insertInto(document.body); }); asyncTest("Check insertion of single stylesheet", function() { expect(1); new wysihtml.dom.Sandbox(function(sandbox) { var doc = sandbox.getDocument(); equal(doc.getElementsByTagName("link").length, 1, "Correct amount of stylesheets inserted into the dom tree"); start(); }, { stylesheets: "https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/blitzer/jquery-ui.css" }).insertInto(document.body); }); asyncTest("Check insertion of multiple stylesheets", function() { expect(1); new wysihtml.dom.Sandbox(function(sandbox) { var doc = sandbox.getDocument(); equal(doc.getElementsByTagName("link").length, 2, "Correct amount of stylesheets inserted into the dom tree"); start(); }, { stylesheets: [ "https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/blitzer/jquery-ui.css", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/excite-bike/jquery-ui.css" ] }).insertInto(document.body); }); asyncTest("Check X-UA-Compatible", function() { expect(1); new wysihtml.dom.Sandbox(function(sandbox) { var doc = sandbox.getDocument(), docMode = doc.documentMode; ok(doc.documentMode === document.documentMode, "iFrame is in in the same document mode as the parent site"); start(); }).insertInto(document.body); });
/* Kamino 3 Unit Test Suite | http://github.com/Cyril-sf/kamino.js */ (function (root) { var isLoader = typeof define == "function" && !!define.amd, isModule = typeof require == "function" && typeof exports == "object" && exports && !isLoader, isBrowser = "window" in root && root.window == root && typeof root.navigator != "undefined", isEngine = !isBrowser && !isModule && typeof root.load == "function", load = function load(module, path) { return root[module] || (isModule ? require(path) : isEngine ? (root.load(path.replace(/\.js$/, "") + ".js"), root[module]) : null); }, // Load Spec, Newton, and Kamino 3. Spec = load("Spec", "./../vendor/spec/lib/spec"), Newton = load("Newton", "./../vendor/spec/lib/newton"), Kamino = load("Kamino", "../lib/kamino"), // Create the test suite. testSuite = Kamino.testSuite = new Spec.Suite("Kamino 3 Unit Tests"); // Create and attach the logger event handler. testSuite.on("all", isBrowser ? Newton.createReport("suite") : Newton.createConsole(function (value) { if (typeof console != "undefined" && console.log) { console.log(value); } else if (typeof print == "function" && !isBrowser) { // In browsers, the global `print` function prints the current page. print(value); } else { throw value; } })); // Ensures that `Kamino.parse` throws an exception when parsing the given // `source` string. Spec.Test.prototype.parseError = function (source, message, callback) { return this.error(function () { Kamino.parse(source, callback); }, function (exception) { return exception.name == "SyntaxError"; }, message); }; // Ensures that `Kamino.parse` parses the given source string correctly. Spec.Test.prototype.parses = function (expected, source, message, callback) { var value; try { value = Kamino.parse(source, callback); } catch( exception) { value = exception.name; } return this.deepEqual(value, expected, message); }; // Ensures that `Kamino.stringify` throws an exception when serializing the given // `value` object. Spec.Test.prototype.serializeError = function (value, message, filter, width) { return this.error(function () { Kamino.stringify(value, filter, width); }, function (exception) { return exception instanceof KaminoException; }, message); }; // Ensures that `Kamino.stringify` serializes the given object correctly. Spec.Test.prototype.serializes = function (expected, value, message, filter, width) { var value; try { value = Kamino.stringify(value, filter, width); } catch( exception) { value = exception.name; } return this.strictEqual(value, expected, message); }; // Tests // ----- testSuite.addTest("`parse`: Empty Source Strings", function () { this.parseError("", "Empty Kamino source string"); this.parseError("\n\n\r\n", "Source string containing only line terminators"); this.parseError(" ", "Source string containing a single space character"); this.parseError(" ", "Source string containing multiple space characters"); this.done(4); }); testSuite.addTest("`parse`: Whitespace", function (test) { // The only valid Kamino whitespace characters are tabs, spaces, and line // terminators. All other Unicode category `Z` (`Zs`, `Zl`, and `Zp`) // characters are invalid (note that the `Zs` category includes the // space character). var characters = ["{\u00a0}", "{\u1680}", "{\u180e}", "{\u2000}", "{\u2001}", "{\u2002}", "{\u2003}", "{\u2004}", "{\u2005}", "{\u2006}", "{\u2007}", "{\u2008}", "{\u2009}", "{\u200a}", "{\u202f}", "{\u205f}", "{\u3000}", "{\u2028}", "{\u2029}"]; Spec.forEach(characters, function (value) { test.parseError(value, "Source string containing an invalid Unicode whitespace character"); }); this.parseError("{\u000b}", "Source string containing a vertical tab"); this.parseError("{\u000c}", "Source string containing a form feed"); this.parseError("{\ufeff}", "Source string containing a byte-order mark"); this.parses({}, "{\r\n}", "Source string containing a CRLF line ending"); this.parses({}, "{\n\n\r\n}", "Source string containing multiple line terminators"); this.parses({}, "{\t}", "Source string containing a tab character"); this.parses({}, "{ }", "Source string containing a space character"); this.done(26); }); testSuite.addTest("`parse`: Octal Values", function (test) { // `08` and `018` are invalid octal values. Spec.forEach(["00", "01", "02", "03", "04", "05", "06", "07", "010", "011", "08", "018"], function (value) { test.parseError(value, "Octal literal"); test.parseError("-" + value, "Negative octal literal"); test.parseError('"\\' + value + '"', "Octal escape sequence in a string"); test.parseError('"\\x' + value + '"', "Hex escape sequence in a string"); }); this.done(48); }); testSuite.addTest("`parse`: special numeric values", function (test) { this.parses(Infinity, "Infinity", "Infinity"); this.parses(NaN, "NaN", "Not a number"); this.parses(-Infinity, "NInfinity", "Negative Infinity"); this.done(3); }); testSuite.addTest("`parse`: Numeric Literals", function () { this.parses(100, "100", "Integer"); this.parses(-100, "-100", "Negative integer"); this.parses(10.5, "10.5", "Float"); this.parses(-3.141, "-3.141", "Negative float"); this.parses(0.625, "0.625", "Decimal"); this.parses(-0.03125, "-0.03125", "Negative decimal"); this.parses(1000, "1e3", "Exponential"); this.parses(100, "1e+2", "Positive exponential"); this.parses(-0.01, "-1e-2", "Negative exponential"); this.parses(3125, "0.03125e+5", "Decimalized exponential"); this.parses(100, "1E2", "Case-insensitive exponential delimiter"); this.parseError("+1", "Leading `+`"); this.parseError("1.", "Trailing decimal point"); this.parseError(".1", "Leading decimal point"); this.parseError("1e", "Missing exponent"); this.parseError("1e-", "Missing signed exponent"); this.parseError("--1", "Leading `--`"); this.parseError("1-+", "Trailing `-+`"); this.parseError("0xaf", "Hex literal"); // The native `Kamino.parse` implementation in IE 9 allows this syntax, but // the feature tests should detect the broken implementation. this.parseError("- 5", "Invalid negative sign"); this.done(20); }); testSuite.addTest("`parse`: String Literals", function (test) { var expected = 49, controlCharacters = ["\u0001", "\u0002", "\u0003", "\u0004", "\u0005", "\u0006", "\u0007", "\b", "\t", "\n", "\u000b", "\f", "\r", "\u000e", "\u000f", "\u0010", "\u0011", "\u0012", "\u0013", "\u0014", "\u0015", "\u0016", "\u0017", "\u0018", "\u0019", "\u001a", "\u001b", "\u001c", "\u001d", "\u001e", "\u001f"]; // Opera 7 discards null characters in strings. if ("\0".length) { expected += 1; controlCharacters.push("\u0000"); } this.parses("value", '"value"', "Double-quoted string literal"); this.parses("", '""', "Empty string literal"); this.parses("\u2028", '"\\u2028"', "String containing an escaped Unicode line separator"); this.parses("\u2029", '"\\u2029"', "String containing an escaped Unicode paragraph separator"); this.parses("\ud834\udf06", '"\\ud834\\udf06"', "String containing an escaped Unicode surrogate pair"); this.parses("\ud834\udf06", '"\ud834\udf06"', "String containing an unescaped Unicode surrogate pair"); this.parses("\u0001", '"\\u0001"', "String containing an escaped ASCII control character"); this.parses("\b", '"\\b"', "String containing an escaped backspace"); this.parses("\f", '"\\f"', "String containing an escaped form feed"); this.parses("\n", '"\\n"', "String containing an escaped line feed"); this.parses("\r", '"\\r"', "String containing an escaped carriage return"); this.parses("\t", '"\\t"', "String containing an escaped tab"); this.parses("hello/world", '"hello\\/world"', "String containing an escaped solidus"); this.parses("hello\\world", '"hello\\\\world"', "String containing an escaped reverse solidus"); this.parses("hello\"world", '"hello\\"world"', "String containing an escaped double-quote character"); this.parseError("'hello'", "Single-quoted string literal"); this.parseError('"\\x61"', "String containing a hex escape sequence"); this.parseError('"hello \r\n world"', "String containing an unescaped CRLF line ending"); Spec.forEach(controlCharacters, function (value) { test.parseError('"' + value + '"', "String containing an unescaped ASCII control character"); }); this.done(expected); }); testSuite.addTest("`parse`: Date Literals", function() { this.parses(new Date(Date.UTC(1994, 6, 3)), '%"Sun, 03 Jul 1994 00:00:00 UTC"', "Dates should be parses according to the simplified date time string format"); this.done(1); }); testSuite.addTest("`parse`: RegExp Literals", function () { this.parses(new RegExp("w+"), "^\"w+\"\"\"", "Regular expressions with no modifiers"); this.parses(new RegExp("w+", "i"), "^\"w+\"\"i\"", "Regular expressions with case-incensitive modifier"); this.parses(new RegExp("w+", "g"), "^\"w+\"\"g\"", "Regular expressions with global matching modifier"); this.parses(new RegExp("w+", "m"), "^\"w+\"\"m\"", "Regular expressions with multiline matching modifier"); // this.parses(new RegExp("\w+"), "R10/\\w+/", "Regular expressions with a non default last index"); this.done(4); }); testSuite.addTest("`parse`: Array Literals", function () { this.parseError("[1, 2, 3,]", "Trailing comma in array literal"); this.parses([1, 2, [3, [4, 5]], 6, [true, false], [null], [[]]], "[1, 2, [3, [4, 5]], 6, [true, false], [null], [[]]]", "Nested arrays"); this.parses([{}], "[{}]", "Array containing empty object literal"); this.parses([100, true, false, null, {"a": ["hello"], "b": ["world"]}, [0.01]], "[1e2, true, false, null, {\"a\": [\"hello\"], \"b\": [\"world\"]}, [1e-2]]", "Mixed array"); this.done(4); }); testSuite.addTest("`parse`: Object Literals", function () { this.parses({"hello": "world"}, "{\"hello\": \"world\"}", "Object literal containing one member"); this.parses({"hello": "world", "foo": ["bar", true], "fox": {"quick": true, "purple": false}}, "{\"hello\": \"world\", \"foo\": [\"bar\", true], \"fox\": {\"quick\": true, \"purple\": false}}", "Object literal containing multiple members"); this.parseError("{key: 1}", "Unquoted identifier used as a property name"); this.parseError("{false: 1}", "`false` used as a property name"); this.parseError("{true: 1}", "`true` used as a property name"); this.parseError("{null: 1}", "`null` used as a property name"); this.parseError("{'key': 1}", "Single-quoted string used as a property name"); this.parseError("{1: 2, 3: 4}", "Number used as a property name"); this.parseError("{\"hello\": \"world\", \"foo\": \"bar\",}", "Trailing comma in object literal"); this.done(9); }); testSuite.addTest("`parse`: object references", function () { message = Kamino.parse("{\"article\":{\"users\":[{\"name\":\"John\"}],\"comment\":{\"author\":&3}}}"); this.strictEqual(message.article.users[0], message.article.comment.author, ""); this.strictEqual(message.article.comment.author.name, "John"); message = Kamino.parse("{\"article\":{\"users\":[{\"name\":\"John\"}],\"comment\":{\"author\":&3,\"article\":&1}}}"); this.strictEqual(message.article.users[0], message.article.comment.author); this.strictEqual(message.article.comment.author.name, "John"); this.strictEqual(message.article, message.article.comment.article); this.done(5); }); // JavaScript expressions should never be evaluated, as Kamino 3 does not use // `eval`. testSuite.addTest("`parse`: Invalid Expressions", function (test) { Spec.forEach(["1 + 1", "1 * 2", "var value = 123;", "{});value = 123;({}", "call()", "1, 2, 3, \"value\""], function (expression) { test.parseError(expression, "Source string containing a JavaScript expression"); }); this.done(6); }); testSuite.addTest("`stringify` and `parse`: Optional Arguments", function () { this.parses({"a": 1, "b": 16}, '{"a": 1, "b": "10000"}', "Callback function provided", function (key, value) { return typeof value == "string" ? parseInt(value, 2) : value; }); this.serializes("{\n \"bar\": 456\n}", {"foo": 123, "bar": 456}, "Object; optional `filter` and `whitespace` arguments", ["bar"], 2); // Test adapted from the Opera Kamino test suite via Ken Snyder. // See http://testsuites.opera.com/Kamino/correctness/scripts/045.js this.serializes('{"PI":3.141592653589793}', Math, "List of non-enumerable property names specified as the `filter` argument", ["PI"]); this.equal(3, Kamino.parse("[1, 2, 3]", function (key, value) { if (typeof value == "object" && value) { return value; } }).length, "Issue #10: `walk` should not use `splice` when removing an array element"); this.done(4); }); testSuite.addTest("`stringify`", function () { var expected = 24, value, pattern; // Special values. this.serializes("null", null, "`null` is represented literally"); this.serializes(undefined, undefined, "`undefined` is represented literally"); this.serializes("Infinity", 1 / 0, "`Infinity` is serialized as `Infinity`"); this.serializes("NaN", 0 / 0, "`NaN` is serialized as `NaN`"); this.serializes("NInfinity", -1 / 0, "`-Infinity` is serialized as `NInfinity`"); this.serializes("true", true, "Boolean primitives are represented literally"); this.serializes("false", new Boolean(false), "Boolean objects are represented literally"); this.serializes('"\\\\\\"How\\bquickly\\tdaft\\njumping\\fzebras\\rvex\\""', new String('\\"How\bquickly\tdaft\njumping\fzebras\rvex"'), "All control characters in strings are escaped"); this.serializes("[false,1,\"Kit\"]", [new Boolean, new Number(1), new String("Kit")], "Arrays are serialized recursively"); this.serializes("[null]", [void 0], "`[undefined]` is serialized as `[null]`"); // Property enumeration is implementation-dependent. value = { "jdalton": ["John-David", 29], "kitcambridge": ["Kit", 18], "mathias": ["Mathias", 23] }; this.parses(value, Kamino.stringify(value), "Objects are serialized recursively"); // Complex cyclic structures. value = { "foo": { "b": { "foo": { "c": { "foo": null} } } } }; this.serializes('{"foo":{"b":{"foo":{"c":{"foo":null}}}}}', value, "Nested objects containing identically-named properties should serialize correctly"); // Sparse arrays. value = []; value[5] = 1; this.serializes("[null,null,null,null,null,1]", value, "Sparse arrays should serialize correctly"); // Dates. this.serializes('%"Sun, 03 Jul 1994 00:00:00 UTC"', new Date(Date.UTC(1994, 6, 3)), "Dates should be serialized according to the simplified date time string format"); // Opera 7 normalizes dates with invalid time values to represent the // current date. value = new Date("Kit"); if (!isFinite(value)) { expected += 1; this.serializes("null", value, "Invalid dates should serialize as `null`"); } // Regular Expressions. this.serializes('^"w+"""', new RegExp("\w+"), "Regular expressions with no modifiers"); this.serializes('^"w+""i"', new RegExp("\w+", "i"), "Regular expressions with no modifiers"); this.serializes('^"w+""g"', new RegExp("\w+", "g"), "Regular expressions with no modifiers"); this.serializes('^"w+""m"', new RegExp("\w+", "m"), "Regular expressions with no modifiers"); // Additional arguments. this.serializes("[\n 1,\n 2,\n 3,\n [\n 4,\n 5\n ]\n]", [1, 2, 3, [4, 5]], "Nested arrays; optional `whitespace` argument", null, " "); this.serializes("[]", [], "Empty array; optional string `whitespace` argument", null, " "); this.serializes("{}", {}, "Empty object; optional numeric `whitespace` argument", null, 2); this.serializes("[\n 1\n]", [1], "Single-element array; optional numeric `whitespace` argument", null, 2); this.serializes("{\n \"foo\": 123\n}", { "foo": 123 }, "Single-member object; optional string `whitespace` argument", null, " "); this.serializes("{\n \"foo\": {\n \"bar\": [\n 123\n ]\n }\n}", {"foo": {"bar": [123]}}, "Nested objects; optional numeric `whitespace` argument", null, 2); this.done(expected); }); testSuite.addTest("`stringify`: object references", function () { var user = {name: "John"}, comment = {author: user}, article = {users: [user], comment: comment}, message = {article: article}; this.serializes("{\"article\":{\"users\":[{\"name\":\"John\"}],\"comment\":{\"author\":&3}}}", message, "An object with references can be serialized"); message.article.comment.article = message.article; this.serializes("{\"article\":{\"users\":[{\"name\":\"John\"}],\"comment\":{\"author\":&3,\"article\":&1}}}", message, "An object with circular references can be serialized"); this.done(2); }); testSuite.addTest("`stringify`: Invalid Expressions", function (test) { var myFn = new Function(), myError = new Error(), myElement = window.document.createElement('div'); Spec.forEach([myFn, myError, myElement], function(expression) { test.serializeError(expression); }); this.done(3); }); testSuite.addTest("`stringify`: when `Element` is not defined (web workers), it should not generate errors", function (test) { var ElementKlass = window['Element']; window['Element'] = undefined; this.serializes("null", null, "`null` is represented literally"); window['Element'] = ElementKlass; this.done(1); }); testSuite.addTest("`clone`", function() { var person = { firstName: "Cyril", lastName: "Fluck" }; var blog = { administrator: person, author: person }; this.strictEqual(blog.administrator, blog.author, "Object references are equal"); // true var kaminoClone = Kamino.clone(blog); this.strictEqual(kaminoClone.administrator, kaminoClone.author, "Object references are preserved when an object is cloned"); blog.administrator.firstName = "John"; blog.administrator.lastName = "Doe"; this.notStrictEqual(kaminoClone.administrator, blog.administrator, "Objects are cloned"); this.done(3); }); /* * The following tests are adapted from the ECMAScript 5 Conformance Suite. * Copyright 2009, Microsoft Corporation. Distributed under the New BSD License. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Microsoft nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ testSuite.addTest("ECMAScript 5 Conformance", function () { var value = { "a1": { "b1": [1, 2, 3, 4], "b2": { "c1": 1, "c2": 2 } }, "a2": "a2" }; // Section 15.12.1.1: The Kamino Grammar. // ------------------------------------ // Tests 15.12.1.1-0-1 thru 15.12.1.1-0-8. this.parseError("12\t\r\n 34", "Valid whitespace characters may not separate two discrete tokens"); this.parseError("\u000b1234", "The vertical tab is not a valid whitespace character"); this.parseError("\u000c1234", "The form feed is not a valid whitespace character"); this.parseError("\u00a01234", "The non-breaking space is not a valid whitespace character"); this.parseError("\u200b1234", "The zero-width space is not a valid whitespace character"); this.parseError("\ufeff1234", "The byte order mark (zero-width non-breaking space) is not a valid whitespace character"); this.parseError("\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u30001234", "Other Unicode category `Z` characters are not valid whitespace characters"); this.parseError("\u2028\u20291234", "The line (U+2028) and paragraph (U+2029) separators are not valid whitespace characters"); // Test 15.12.1.1-0-9. this.parses({ "property": {}, "prop2": [true, null, 123.456] }, '\t\r \n{\t\r \n' + '"property"\t\r \n:\t\r \n{\t\r \n}\t\r \n,\t\r \n' + '"prop2"\t\r \n:\t\r \n' + '[\t\r \ntrue\t\r \n,\t\r \nnull\t\r \n,123.456\t\r \n]' + '\t\r \n}\t\r \n', "Valid whitespace characters may precede and follow all tokens"); // Tests 15.12.1.1-g1-1 thru 15.12.1.1-g1-4. this.parses(1234, "\t1234", "Leading tab characters should be ignored"); this.parseError("12\t34", "A tab character may not separate two disparate tokens"); this.parses(1234, "\r1234", "Leading carriage returns should be ignored"); this.parseError("12\r34", "A carriage return may not separate two disparate tokens"); this.parses(1234, "\n1234", "Leading line feeds should be ignored"); this.parseError("12\n34", "A line feed may not separate two disparate tokens"); this.parses(1234, " 1234", "Leading space characters should be ignored"); this.parseError("12 34", "A space character may not separate two disparate tokens"); // Tests 15.12.1.1-g2-1 thru 15.12.1.1-g2-5. this.parses("abc", '"abc"', "Strings must be enclosed in double quotes"); this.parseError("'abc'", "Single-quoted strings are not permitted"); // Note: the original test 15.12.1.1-g2-3 (`"\u0022abc\u0022"`) is incorrect, // as the JavaScript interpreter will always convert `\u0022` to `"`. this.parseError("\\u0022abc\\u0022", "Unicode-escaped double quote delimiters are not permitted"); this.parseError('"ab'+"c'", "Strings must terminate with a double quote character"); this.parses("", '""', "Strings may be empty"); // Tests 15.12.1.1-g4-1 thru 15.12.1.1-g4-4. this.parseError('"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007"', "Unescaped control characters in the range [U+0000, U+0007] are not permitted within strings"); this.parseError('"\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u000f"', "Unescaped control characters in the range [U+0008, U+000F] are not permitted within strings"); this.parseError('"\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017"', "Unescaped control characters in the range [U+0010, U+0017] are not permitted within strings"); this.parseError('"\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"', "Unescaped control characters in the range [U+0018, U+001F] are not permitted within strings"); // Tests 15.12.1.1-g5-1 thru 15.12.1.1-g5-3. this.parses("X", '"\\u0058"', "Unicode escape sequences are permitted within strings"); this.parseError('"\\u005"', "Unicode escape sequences may not comprise fewer than four hexdigits"); this.parseError('"\\u0X50"', "Unicode escape sequences may not contain non-hex characters"); // Tests 15.12.1.1-g6-1 thru 15.12.1.1-g6-7. this.parses("/", '"\\/"', "Escaped solidus"); this.parses("\\", '"\\\\"', "Escaped reverse solidus"); this.parses("\b", '"\\b"', "Escaped backspace"); this.parses("\f", '"\\f"', "Escaped form feed"); this.parses("\n", '"\\n"', "Escaped line feed"); this.parses("\r", '"\\r"', "Escaped carriage return"); this.parses("\t", '"\\t"', "Escaped tab"); // Section 15.12.3: `Kamino.stringify()`. // ------------------------------------ // Test 15.12.3-11-1 thru 5.12.3-11-15. this.serializes(void 0, void 0, "`Kamino.stringify(undefined)` should return `undefined`"); this.serializes('"replacement"', void 0, "The `Kamino.stringify` callback function can be called on a top-level `undefined` value", function (key, value) { return "replacement"; }); this.serializes('"a string"', "a string", "`Kamino.stringify` should serialize top-level string primitives"); this.serializes("123", 123, "`Kamino.stringify` should serialize top-level number primitives"); this.serializes("true", true, "`Kamino.stringify` should serialize top-level Boolean primitives"); this.serializes("null", null, "`Kamino.stringify` should serialize top-level `null` values"); this.serializes("42", new Number(42), "`Kamino.stringify` should serialize top-level number objects"); this.serializes('"wrapped"', new String("wrapped"), "`Kamino.stringify` should serialize top-level string objects"); this.serializes("false", new Boolean(false), "`Kamino.stringify` should serialize top-level Boolean objects"); this.serializes(void 0, 42, "The `Kamino.stringify` callback function may return `undefined` when called on a top-level number primitive", function () { return void 0; }); this.serializes(void 0, { "prop": 1 }, "The `Kamino.stringify` callback function may return `undefined` when called on a top-level object", function () { return void 0; }); this.serializes("[4,2]", 42, "The `Kamino.stringify` callback function may return an array when called on a top-level number primitive", function (key, value) { return value == 42 ? [4, 2] : value; }); this.serializes('{"forty":2}', 42, "The `Kamino.stringify` callback function may return an object literal when called on a top-level number primitive", function (key, value) { return value == 42 ? { "forty": 2 } : value; }); // Test 15.12.3-4-1. this.serializes("[42]", [42], "`Kamino.stringify` should ignore `filter` arguments that are not functions or arrays", {}); // Test 15.12.3-5-a-i-1 and 15.12.3-5-b-i-1. this.equal(Kamino.stringify(value, null, new Number(5)), Kamino.stringify(value, null, 5), "Optional `width` argument: Number object and primitive width values should produce identical results"); this.equal(Kamino.stringify(value, null, new String("xxx")), Kamino.stringify(value, null, "xxx"), "Optional `width` argument: String object and primitive width values should produce identical results"); // Test 15.12.3-6-a-1 and 15.12.3-6-a-2. this.equal(Kamino.stringify(value, null, 10), Kamino.stringify(value, null, 100), "Optional `width` argument: The maximum numeric width value should be 10"); this.equal(Kamino.stringify(value, null, 5.99999), Kamino.stringify(value, null, 5), "Optional `width` argument: Numeric values should be converted to integers"); // Test 15.12.3-6-b-1 and 15.12.3-6-b-4. this.equal(Kamino.stringify(value, null, 0.999999), Kamino.stringify(value), "Optional `width` argument: Numeric width values between 0 and 1 should be ignored"); this.equal(Kamino.stringify(value, null, 0), Kamino.stringify(value), "Optional `width` argument: Zero should be ignored"); this.equal(Kamino.stringify(value, null, -5), Kamino.stringify(value), "Optional `width` argument: Negative numeric values should be ignored"); this.equal(Kamino.stringify(value, null, 5), Kamino.stringify(value, null, " "), "Optional `width` argument: Numeric width values in the range [1, 10] should produce identical results to that of string values containing `width` spaces"); // Test 15.12.3-7-a-1. this.equal(Kamino.stringify(value, null, "0123456789xxxxxxxxx"), Kamino.stringify(value, null, "0123456789"), "Optional `width` argument: String width values longer than 10 characters should be truncated"); // Test 15.12.3-8-a-1 thru 15.12.3-8-a-5. this.equal(Kamino.stringify(value, null, ""), Kamino.stringify(value), "Empty string `width` arguments should be ignored"); this.equal(Kamino.stringify(value, null, true), Kamino.stringify(value), "Boolean primitive `width` arguments should be ignored"); this.equal(Kamino.stringify(value, null, null), Kamino.stringify(value), "`null` `width` arguments should be ignored"); this.equal(Kamino.stringify(value, null, new Boolean(false)), Kamino.stringify(value), "Boolean object `width` arguments should be ignored"); this.equal(Kamino.stringify(value, null, value), Kamino.stringify(value), "Object literal `width` arguments should be ignored"); // Test 15.12.3@2-2-b-i-1. this.serializes('["fortytwo objects"]', [{ "prop": 42, "toJSON": function () { return "fortytwo objects"; } }], "An object literal with a custom `toJSON` method nested within an array may return a string primitive for serialization"); // Test 15.12.3@2-2-b-i-2. this.serializes('[42]', [{ "prop": 42, "toJSON": function () { return new Number(42); } }], "An object literal with a custom `toJSON` method nested within an array may return a number object for serialization"); // Test 15.12.3@2-2-b-i-3. this.serializes('[true]', [{ "prop": 42, "toJSON": function () { return new Boolean(true); } }], "An object literal with a custom `toJSON` method nested within an array may return a Boolean object for serialization"); // Test 15.12.3@2-3-a-1. this.serializes('["fortytwo"]', [42], "The `Kamino.stringify` callback function may return a string object when called on an array", function (key, value) { return value === 42 ? new String("fortytwo") : value; }); // Test 15.12.3@2-3-a-2. this.serializes('[84]', [42], "The `Kamino.stringify` callback function may return a number object when called on an array", function (key, value) { return value === 42 ? new Number(84) : value; }); // Test 15.12.3@2-3-a-3. this.serializes('[false]', [42], "The `Kamino.stringify` callback function may return a Boolean object when called on an array", function (key, value) { return value === 42 ? new Boolean(false) : value; }); this.done(70); }); // This test may fail in certain implementations. testSuite.addTest("Anticipated ECMAScript 6 Additions", function () { var expected = 0, value; try { value = {}; // IE 8 only allows properties to be defined on DOM elements. Credits: // John-David Dalton and Juriy Zaytsev. if (Object.defineProperty(value, value, value), "value" in Object.getOwnPropertyDescriptor(value, value)) { expected += 1; value = [0, 1, 2, 3]; Object.prototype[3] = 3; Object.defineProperty(value, 1, { "get": function () { Object.defineProperty(value, 4, { "value": 4 }); delete value[2]; delete value[3]; value[5] = 5; return 1; } }); // Test by Jeff Walden and Allen Wirfs-Brock. this.serializes('{"0":{"1":{"3":{"3":3}},"3":3},"3":3}', { 0: { 1: { 3: { 4: { 5: { 2: "omitted" } } } } } }, "Issue #12: `parse` should process property name arrays sequentially", value); } } catch (exception) {} // Clean up. delete Object.prototype[3]; this.done(expected); }); testSuite.shuffle(); if (isLoader) { define(function () { return testSuite; }); } else if (!isBrowser && (!isModule || (typeof module == "object" && module == require.main))) { testSuite.run(); } })(this);
const webpack = require('webpack'); const chalk = require('chalk'); const env = require('dotenv').config().parsed; const _ = require('lodash'); const constants = require('./constants'); const helpers = require('./helpers'); const envMap = _.mapValues(env, v => JSON.stringify(v)); if (!envMap.APP_ENV) { envMap.APP_ENV = '"development"'; console.log('APP_ENV is not set in your .env, it will default to "development"'); } else { const color = constants.ENV_COLOR[env.APP_ENV] || 'bgMagenta'; console.log('APP_ENV is ' + chalk[color]('%s'), envMap.APP_ENV); } module.exports = { performance: { hints: false }, resolve: { extensions: ['.js', '.ts'], modules: ['node_modules', helpers.root('src')] }, plugins: [ new webpack.DefinePlugin({ 'process.env': envMap }), new webpack.ProvidePlugin({ jQuery: 'jquery', $: 'jquery', jquery: 'jquery' }), // new webpack.ContextReplacementPlugin( // // The (\\|\/) piece accounts for path separators in *nix and Windows // constants.CONTEXT_REPLACE_REGEX, // helpers.root('./src') // location of your src // ) ] };
/* Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'autoembed', 'bg', { embeddingInProgress: 'Опит за вграждане на поставения URL адрес...', embeddingFailed: 'Този URL адрес не може да бъде вграден автоматично.' } );
import { commonPayment } from '../api'; import _ from 'underscore'; import m from 'mithril'; import prop from 'mithril/stream'; import models from '../models'; import h from '../h'; const subscriptions = prop([]), vm = commonPayment.filtersVM({ project_id: 'eq' }); const subscriptionsLoader = (uuID) => { vm.project_id(uuID); vm.order({ created_at: 'desc' }); return commonPayment.loaderWithToken(models.userSubscription.getPageOptions(vm.parameters())); }; const fetchSubscriptions = uuID => subscriptionsLoader(uuID).load().then(subscriptions); const projectSubscriptionsVM = { subscriptions, fetchSubscriptions, subscriptionsLoader }; export default projectSubscriptionsVM;
var _ = require('lodash'); module.exports = generateSequenceInfo; /** * Generate info for a button sequence puzzle * @returns {Object} Object with 4 display values and 6 button labels for game * interface, 4 button labels and 2 divisors for manual generation, and the * puzzle solution */ function generateSequenceInfo() { var orderedButtons = generateButtons(); var buttons = _.shuffle(orderedButtons); var fizzBuzzButtons = _.take(orderedButtons, 4); var sequenceSolution = generateSequenceSolution(fizzBuzzButtons); var divisors = generateDivisors(); var displays = generateDisplays(divisors, fizzBuzzButtons, sequenceSolution); var sequenceInfo = { type: 'sequence', displays: displays, buttons: buttons, fizzBuzzButtons: fizzBuzzButtons, divisors: divisors, solution: sequenceSolution }; return sequenceInfo; //////////// function generateButtons() { var labelList = ['Arrange', 'Begin', 'Block', 'Change', 'Chat', 'Click', 'Close', 'Compare', 'Connect', 'Control', 'Convert', 'Convey', 'Copy', 'Customize', 'Cut', 'Define', 'Delete', 'Design', 'Download', 'Drag', 'Edit', 'Emit', 'Enhance', 'Equip', 'Excel', 'Exit', 'Export', 'File', 'Fill', 'Find', 'Fit', 'Flip', 'Format', 'Forward', 'Freeze', 'Group', 'Help', 'Hide', 'Hold', 'Input', 'Insert', 'Listen', 'Load', 'Merge', 'Move', 'Off', 'Omit', 'On', 'Open', 'Perform', 'Place', 'Plug-in', 'Permit', 'Prefer', 'Press', 'Print', 'Process', 'Protect', 'Range', 'Read', 'Record', 'Refer', 'Release', 'Reload', 'Repeat', 'Replace', 'Retrieve', 'Run', 'Save', 'Scan', 'Scroll', 'See', 'Select', 'Send', 'Share', 'Show', 'Smell', 'Solve', 'Sort', 'Spell', 'Split', 'Store', 'Submit', 'Talk', 'Taste', 'Transmit', 'Transfer', 'Undo', 'Ungroup', 'Update', 'View', 'Watch', 'Write', 'Zoom']; return _.sample(labelList, 6); } function generateSequenceSolution(fizzBuzzButtons) { var solution = _(4) .times(_.partial(_.sample, fizzBuzzButtons, 1)) .flatten() .value(); return solution; } function generateDivisors() { var divisors = _([2, 3, 5, 7]) .sample(2) .sortBy() .value(); return divisors; } // Generate 4 display values satisfying the button sequence solution. function generateDisplays(divisors, fizzBuzzButtons, sequenceSolution) { var displayCandidates = _(1) .range(1000) .groupBy(_.partial(fizzBuzz, _, divisors, fizzBuzzButtons)) .mapValues(_.partial(_.sample, _, 4)) .value(); var displays = _.map(sequenceSolution, _.partial(pickDisplay, _, displayCandidates)); return displays; //////////// function fizzBuzz(num, divisors, fizzBuzzButtons) { if (num % divisors[0] === 0) { if (num % divisors[1] === 0) { return fizzBuzzButtons[0]; } else { return fizzBuzzButtons[1]; } } else if (num % divisors[1] === 0) { return fizzBuzzButtons[2]; } else { return fizzBuzzButtons[3]; } } // To ensure unique display values, pick from different index in each // candidate list. function pickDisplay(targetButton, displayCandidates, index) { var display = displayCandidates[targetButton][index]; return _.padLeft(display, 3, '0'); } } }
var _ = require('underscore'); var Q = require('q'); // horrible hack to get localStorage Backbone plugin var Backbone = (!require('../util').isBrowser()) ? require('backbone') : window.Backbone; var util = require('../util'); var intl = require('../intl'); var Main = require('../app'); var Errors = require('../util/errors'); var Visualization = require('../visuals/visualization').Visualization; var ParseWaterfall = require('../level/parseWaterfall').ParseWaterfall; var DisabledMap = require('../level/disabledMap').DisabledMap; var Command = require('../models/commandModel').Command; var GitShim = require('../git/gitShim').GitShim; var Views = require('../views'); var ModalTerminal = Views.ModalTerminal; var ModalAlert = Views.ModalAlert; var BuilderViews = require('../views/builderViews'); var MultiView = require('../views/multiView').MultiView; var Sandbox = Backbone.View.extend({ // tag name here is purely vestigial. I made this a view // simply to use inheritance and have a nice event system in place tagName: 'div', initialize: function(options) { options = options || {}; this.options = options; this.initVisualization(options); this.initCommandCollection(options); this.initParseWaterfall(options); this.initGitShim(options); this.initUndoStack(options); if (!options.wait) { this.takeControl(); } }, getDefaultVisEl: function() { return $('#mainVisSpace')[0]; }, getAnimationTime: function() { return 700 * 1.5; }, initVisualization: function(options) { this.mainVis = new Visualization({ el: options.el || this.getDefaultVisEl() }); }, initUndoStack: function(options) { this.undoStack = []; }, initCommandCollection: function(options) { // don't add it to just any collection -- adding to the // CommandUI collection will put in history this.commandCollection = Main.getCommandUI().commandCollection; }, initParseWaterfall: function(options) { this.parseWaterfall = new ParseWaterfall(); }, initGitShim: function(options) { this.gitShim = new GitShim({ beforeCB: _.bind(this.beforeCommandCB, this) }); }, takeControl: function() { // we will be handling commands that are submitted, mainly to add the sanadbox // functionality (which is included by default in ParseWaterfall()) Main.getEventBaton().stealBaton('commandSubmitted', this.commandSubmitted, this); // we obviously take care of sandbox commands Main.getEventBaton().stealBaton('processSandboxCommand', this.processSandboxCommand, this); // a few things to help transition between levels and sandbox Main.getEventBaton().stealBaton('levelExited', this.levelExited, this); this.insertGitShim(); }, releaseControl: function() { // we will be handling commands that are submitted, mainly to add the sanadbox // functionality (which is included by default in ParseWaterfall()) Main.getEventBaton().releaseBaton('commandSubmitted', this.commandSubmitted, this); // we obviously take care of sandbox commands Main.getEventBaton().releaseBaton('processSandboxCommand', this.processSandboxCommand, this); // a few things to help transition between levels and sandbox Main.getEventBaton().releaseBaton('levelExited', this.levelExited, this); this.releaseGitShim(); }, releaseGitShim: function() { if (this.gitShim) { this.gitShim.removeShim(); } }, insertGitShim: function() { // and our git shim goes in after the git engine is ready so it doesn't steal the baton // too early if (this.gitShim) { this.mainVis.customEvents.on('gitEngineReady', function() { this.gitShim.insertShim(); },this); } }, beforeCommandCB: function(command) { this.pushUndo(); }, pushUndo: function() { // go ahead and push the three onto the stack this.undoStack.push(this.mainVis.gitEngine.printTree()); }, undo: function(command, deferred) { var toRestore = this.undoStack.pop(); if (!toRestore) { command.set('error', new Errors.GitError({ msg: intl.str('undo-stack-empty') })); deferred.resolve(); return; } this.mainVis.reset(toRestore); setTimeout(function() { command.finishWith(deferred); }, this.mainVis.getAnimationTime()); }, commandSubmitted: function(value) { // allow other things to see this command (aka command history on terminal) Main.getEvents().trigger('commandSubmittedPassive', value); util.splitTextCommand(value, function(command) { this.commandCollection.add(new Command({ rawStr: command, parseWaterfall: this.parseWaterfall })); }, this); }, startLevel: function(command, deferred) { var regexResults = command.get('regexResults') || []; var desiredID = regexResults[1] || ''; var levelJSON = Main.getLevelArbiter().getLevel(desiredID); // handle the case where that level is not found... if (!levelJSON) { command.addWarning( intl.str( 'level-no-id', { id: desiredID } ) ); Main.getEventBaton().trigger('commandSubmitted', 'levels'); command.set('status', 'error'); deferred.resolve(); return; } // we are good to go!! lets prep a bit visually this.hide(); this.clear(); // we don't even need a reference to this, // everything will be handled via event baton :DDDDDDDDD var whenLevelOpen = Q.defer(); var Level = require('../level').Level; this.currentLevel = new Level({ level: levelJSON, deferred: whenLevelOpen, command: command }); whenLevelOpen.promise.then(function() { command.finishWith(deferred); }); }, buildLevel: function(command, deferred) { this.hide(); this.clear(); var whenBuilderOpen = Q.defer(); var LevelBuilder = require('../level/builder').LevelBuilder; var regexResults = command.get('regexResults') || []; var toEdit = regexResults[1] || false; this.levelBuilder = new LevelBuilder({ deferred: whenBuilderOpen, editLevel: toEdit }); whenBuilderOpen.promise.then(function() { command.finishWith(deferred); }); }, exitLevel: function(command, deferred) { command.addWarning( intl.str('level-cant-exit') ); command.set('status', 'error'); deferred.resolve(); }, showLevels: function(command, deferred) { var whenClosed = Q.defer(); Main.getLevelDropdown().show(whenClosed, command); whenClosed.promise.done(function() { command.finishWith(deferred); }); }, resetSolved: function(command, deferred) { Main.getLevelArbiter().resetSolvedMap(); command.addWarning( intl.str('solved-map-reset') ); command.finishWith(deferred); }, processSandboxCommand: function(command, deferred) { // I'm tempted to do camcel case conversion, but there are // some exceptions to the rule var commandMap = { 'reset solved': this.resetSolved, 'undo': this.undo, 'help general': this.helpDialog, 'help': this.helpDialog, 'reset': this.reset, 'delay': this.delay, 'clear': this.clear, 'exit level': this.exitLevel, 'level': this.startLevel, 'sandbox': this.exitLevel, 'levels': this.showLevels, 'mobileAlert': this.mobileAlert, 'build level': this.buildLevel, 'export tree': this.exportTree, 'import tree': this.importTree, 'importTreeNow': this.importTreeNow, 'import level': this.importLevel, 'importLevelNow': this.importLevelNow, }; var method = commandMap[command.get('method')]; if (!method) { throw new Error('no method for that wut'); } method.apply(this, [command, deferred]); }, hide: function() { this.mainVis.hide(); }, levelExited: function() { this.show(); }, show: function() { this.mainVis.show(); }, importLevelNow: function(command, deferred) { var options = command.get('regexResults') || []; if (options.length < 2) { command.set('error', new Errors.GitError({ msg: intl.str('git-error-options') })); command.finishWith(deferred); return; } var string = options.input.replace(/importLevelNow\s+/g, ''); var Level = require('../level').Level; try { var levelJSON = JSON.parse(unescape(string)); var whenLevelOpen = Q.defer(); this.currentLevel = new Level({ level: levelJSON, deferred: whenLevelOpen, command: command }); this.hide(); whenLevelOpen.promise.then(function() { command.finishWith(deferred); }); } catch(e) { command.set('error', new Errors.GitError({ msg: 'Something went wrong ' + String(e) })); } command.finishWith(deferred); }, importTreeNow: function(command, deferred) { var options = command.get('regexResults') || []; if (options.length < 2) { command.set('error', new Errors.GitError({ msg: intl.str('git-error-options') })); command.finishWith(deferred); } var string = options.input.replace(/importTreeNow\s+/g, ''); try { this.mainVis.gitEngine.loadTreeFromString(string); } catch (e) { command.set('error', new Errors.GitError({ msg: String(e) })); } command.finishWith(deferred); }, importTree: function(command, deferred) { var jsonGrabber = new BuilderViews.MarkdownPresenter({ previewText: intl.str('paste-json'), fillerText: ' ' }); jsonGrabber.deferred.promise .then(_.bind(function(treeJSON) { try { this.mainVis.gitEngine.loadTree(JSON.parse(treeJSON)); } catch(e) { this.mainVis.reset(); new MultiView({ childViews: [{ type: 'ModalAlert', options: { markdowns: [ '## Error!', '', 'Something is wrong with that JSON! Here is the error:', '', String(e) ] } }] }); } }, this)) .fail(function() { }) .done(function() { command.finishWith(deferred); }); }, importLevel: function(command, deferred) { var jsonGrabber = new BuilderViews.MarkdownPresenter({ previewText: intl.str('paste-json'), fillerText: ' ' }); jsonGrabber.deferred.promise .then(_.bind(function(inputText) { var Level = require('../level').Level; try { var levelJSON = JSON.parse(inputText); var whenLevelOpen = Q.defer(); this.currentLevel = new Level({ level: levelJSON, deferred: whenLevelOpen, command: command }); this.hide(); whenLevelOpen.promise.then(function() { command.finishWith(deferred); }); } catch(e) { new MultiView({ childViews: [{ type: 'ModalAlert', options: { markdowns: [ '## Error!', '', 'Something is wrong with that level JSON, this happened:', '', String(e) ] } }] }); command.finishWith(deferred); } }, this)) .fail(function() { command.finishWith(deferred); }) .done(); }, exportTree: function(command, deferred) { var treeJSON = JSON.stringify(this.mainVis.gitEngine.exportTree(), null, 2); var showJSON = new MultiView({ childViews: [{ type: 'MarkdownPresenter', options: { previewText: intl.str('share-tree'), fillerText: treeJSON, noConfirmCancel: true } }] }); showJSON.getPromise() .then(function() { command.finishWith(deferred); }) .done(); }, clear: function(command, deferred) { Main.getEvents().trigger('clearOldCommands'); if (command && deferred) { command.finishWith(deferred); } }, mobileAlert: function(command, deferred) { alert(intl.str('mobile-alert')); command.finishWith(deferred); }, delay: function(command, deferred) { var amount = parseInt(command.get('regexResults')[1], 10); setTimeout(function() { command.finishWith(deferred); }, amount); }, reset: function(command, deferred) { this.mainVis.reset(); this.initUndoStack(); setTimeout(function() { command.finishWith(deferred); }, this.mainVis.getAnimationTime()); }, helpDialog: function(command, deferred) { var helpDialog = new MultiView({ childViews: intl.getDialog(require('../dialogs/sandbox')) }); helpDialog.getPromise().then(_.bind(function() { // the view has been closed, lets go ahead and resolve our command command.finishWith(deferred); }, this)) .done(); } }); exports.Sandbox = Sandbox;
var Lab = require('lab'); var Options = require('../lib/options'); var lab = exports.lab = Lab.script(); var after = lab.after; var before = lab.before; var describe = lab.experiment; var expect = Lab.expect; var it = lab.test; describe('Options', function () { it('populates defaults when given undefined', function (done) { Options.validate(undefined, function (err, value) { expect(err).to.not.exist; expect(value).to.deep.equal({ nodes: [{ host: '127.0.0.1', port: 8087 }], connectTimeout: 1000, idleTimeout: 30000, maxLifetime: Infinity, minConnections: 0, maxConnections: 10, parseValues: true }); done(); }); }); it('populates defaults when given an empty object', function (done) { Options.validate({}, function (err, value) { expect(err).to.not.exist; expect(value).to.deep.equal({ nodes: [{ host: '127.0.0.1', port: 8087 }], connectTimeout: 1000, idleTimeout: 30000, maxLifetime: Infinity, minConnections: 0, maxConnections: 10, parseValues: true }); done(); }); }); it('throws when options are invalid', function (done) { expect(function () { Options.validate({ port: 'bacon' }); }).to.throw(Error); done(); }); it('does not allow host/port combo when specifying nodes', function (done) { expect(function () { Options.validate({ host: '127.0.0.1', port: 8087, nodes: [{ host: '127.0.0.1', port: 8087 }] }); }).to.throw(Error); done(); }); });
// ========================================================================== // Project: Ember Runtime // Copyright: ©2006-2011 Strobe Inc. and contributors. // ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ========================================================================== var oldString; module('Ember.String.loc', { setup: function() { oldString = Ember.STRINGS; Ember.STRINGS = { '_Hello World': 'Bonjour le monde', '_Hello %@ %@': 'Bonjour %@ %@', '_Hello %@# %@#': 'Bonjour %@2 %@1' }; }, teardown: function() { Ember.STRINGS = oldString; } }); test("'_Hello World'.loc() => 'Bonjour le monde'", function() { equal(Ember.String.loc('_Hello World'), 'Bonjour le monde'); if (Ember.EXTEND_PROTOTYPES) { equal('_Hello World'.loc(), 'Bonjour le monde'); } }); test("'_Hello %@ %@'.loc('John', 'Doe') => 'Bonjour John Doe'", function() { equal(Ember.String.loc('_Hello %@ %@', ['John', 'Doe']), 'Bonjour John Doe'); if (Ember.EXTEND_PROTOTYPES) { equal('_Hello %@ %@'.loc('John', 'Doe'), 'Bonjour John Doe'); } }); test("'_Hello %@# %@#'.loc('John', 'Doe') => 'Bonjour Doe John'", function() { equal(Ember.String.loc('_Hello %@# %@#', ['John', 'Doe']), 'Bonjour Doe John'); if (Ember.EXTEND_PROTOTYPES) { equal('_Hello %@# %@#'.loc('John', 'Doe'), 'Bonjour Doe John'); } }); test("'_Not In Strings'.loc() => '_Not In Strings'", function() { equal(Ember.String.loc('_Not In Strings'), '_Not In Strings'); if (Ember.EXTEND_PROTOTYPES) { equal('_Not In Strings'.loc(), '_Not In Strings'); } });
var fs = require('fs'); var StorageApi = require('asposestoragecloud'); var ImagingApi = require('../lib/ImagingApi'); var assert = require('assert'); var AppSID = 'XXX'; //sepcify App SID var AppKey = 'XXX'; //sepcify App Key var config = {'appSid':AppSID,'apiKey':AppKey , 'debug' : true}; var data_path = '../../../Data/'; var storageApi = new StorageApi(config); var imagingApi = new ImagingApi(config); var nodeunit = require('nodeunit'); exports.testPostImageBmp = function(test){ test.expect(1); var name = 'sample.bmp'; var bitsPerPixel = 24; var horizontalResolution = 300; var verticalResolution = 300; var file = data_path + name; console.log('file:', file); imagingApi.PostImageBmp(bitsPerPixel, horizontalResolution, verticalResolution, null, null, file, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostCropImage = function(test){ test.expect(1); var fileName = "aspose"; var name = fileName + ".jpg"; var format = "png"; var x = 30; var y = 40; var width = 100; var height = 100; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { imagingApi.PostCropImage(format, x, y, width, height, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testPostImageJpg = function(test){ test.expect(1); var name = "aspose.jpg"; var quality = 100; var compressionType = "progressive"; imagingApi.PostImageJpg(quality, compressionType, null, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostImagePng = function(test){ test.expect(1); var name = "aspose_imaging_for_cloud.png"; var fromScratch = true; imagingApi.PostImagePng(fromScratch, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostImagePsd = function(test){ test.expect(1); var name = "sample.psd"; var channelsCount = 3; var compressionMethod = "rle"; imagingApi.PostImagePsd(channelsCount, compressionMethod, null, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostChangeImageScale = function(test){ test.expect(1); var fileName = "aspose_imaging_for_cloud"; var name = fileName + ".png"; var format = "jpg"; var newWidth = 200; var newHeight = 200; imagingApi.PostChangeImageScale(format, newWidth, newHeight, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostImageRotateFlip = function(test){ test.expect(1); var fileName = "aspose"; var name = fileName + ".jpg"; var format = "png"; var method = "Rotate180FlipX"; imagingApi.PostImageRotateFlip(format, method, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostImageSaveAs = function(test){ test.expect(1); var fileName = "aspose"; var name = fileName + ".jpg"; var format = "png"; imagingApi.PostImageSaveAs(format, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostProcessTiff = function(test){ test.expect(1); var name = "demo.tif"; var compression = "ccittfax3"; var resolutionUnit = "inch"; var bitDepth = 1; imagingApi.PostProcessTiff(compression, resolutionUnit, bitDepth, null, null, null, null, data_path+name, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testPostTiffAppend = function(test){ test.expect(3); var name = "sample.tif"; var appendFile = "TestDemo.tif"; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); storageApi.PutCreate(name, null, null, data_path + appendFile , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.PostTiffAppend(name, appendFile, null, null, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }); }; exports.testGetTiffToFax = function(test){ test.expect(1); var name = "TestDemo.tif"; imagingApi.GetTiffToFax(name, null, null, null, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }; exports.testGetImageBmp = function(test){ test.expect(2); var name = "sample.bmp"; var bitsPerPixel = 24; var horizontalResolution = 300; var verticalResolution = 300; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageBmp(name, bitsPerPixel, horizontalResolution, verticalResolution, null, null, null, null, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetCropImage = function(test){ test.expect(2); var fileName = "aspose"; var name = fileName + ".jpg"; var format = "png"; var x = 30; var y = 40; var width = 100; var height = 100; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetCropImage(name, format, x, y, width, height, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetImageFrame = function(test){ test.expect(2); var name = "sample-multi.tif"; var frameId = 1; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageFrameProperties(name, frameId, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetImageFrameProperties = function(test){ test.expect(3); var name = "TestDemo.tif"; var frameId = 0; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageFrameProperties(name, frameId, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.ok(responseMessage.body !== null && typeof responseMessage.body.BitsPerPixel !== 'undefined', "response body assertion should pass"); test.done(); }); }); }; exports.testGetImageGif = function(test){ test.expect(2); var name = "sample.gif"; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageGif(name, null, null, null, null, null, null, null, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetImageJpg = function(test){ test.expect(2); var name = "aspose.jpg"; var quality = 100; var compressionType = "progressive"; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageJpg(name, quality, compressionType, null, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetImagePng = function(test){ test.expect(2); var name = "aspose_imaging_for_cloud.png"; var fromScratch = true; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImagePng(name, fromScratch, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetImageProperties = function(test){ test.expect(3); var name = "demo.tif"; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageProperties(name, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.ok(responseMessage.body !== null && typeof responseMessage.body.BitsPerPixel !== 'undefined', "response body assertion should pass"); test.done(); }); }); }; exports.testGetImagePsd = function(test){ test.expect(2); var name = "sample.psd"; var channelsCount = 3; var compressionMethod = "rle"; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImagePsd(name, channelsCount, compressionMethod, null, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetChangeImageScale = function(test){ test.expect(2); var fileName = "aspose_imaging_for_cloud"; var name = fileName + ".png"; var format = "jpg"; var newWidth = 200; var newHeight = 200; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetChangeImageScale(name, format, newWidth, newHeight, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetImageRotateFlip = function(test){ test.expect(2); var fileName = "aspose"; var name = fileName + ".jpg"; var format = "png"; var method = "Rotate180FlipX"; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageRotateFlip(name, format, method, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetImageSaveAs = function(test){ test.expect(2); var fileName = "aspose"; var name = fileName + ".jpg"; var format = "png"; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetImageSaveAs(name, format, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); }; exports.testGetUpdatedImage = function(test){ test.expect(2); var fileName = "TestDemo"; var name = fileName + ".tif"; var format = null; var x = 96; var y = 96; var newWidth = 300; var newHeight = 300; var rectWidth = 200; var rectHeight = 200; var rotateFlipMethod = null; var storage = null; var folder= null; storageApi.PutCreate(name, null, null, data_path + name , function(responseMessage) { test.equal(responseMessage.status, 'OK', ''); imagingApi.GetUpdatedImage(name, format, newWidth, newHeight, x, y, rectWidth, rectHeight, rotateFlipMethod, null, folder, storage, function(responseMessage) { if(config.debug){console.log('status:', responseMessage.status);} if(config.debug){console.log('body:', responseMessage.body);} test.equal(responseMessage.status, 'OK', ''); test.done(); }); }); };
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17.5 15v-2h1.1l.9 2H21l-.9-2.1h.9V9h-5v4.86L17.14 15h.36zm0-4.5h2v1h-2v-1zm-4.5 0v.36l1.5 1.5V10.5c0-.8-.7-1.5-1.5-1.5h-1.86l1.5 1.5H13zM2.51 2.49L1.45 3.55 6.9 9h-.4v2h-2V9H3v6h1.5v-2.5h2V15H8v-4.9l1.5 1.5V15h3.4l7.6 7.6 1.06-1.06z" /> , 'HdrOffSharp');
const _curry2 = require('ramda/src/internal/_curry2') const _map = require('ramda/src/internal/_map') const keys = require('ramda/src/keys') // mapObjIndexed: ((v, k, {k: v}) → v') → {k: v} → {k: v'} // mapObjIndexedReturnArray: ((v, k, {k: v}) → v') → {k: v} → [v'] /* * @example * * const xyz = { x: 1, y: 2, z: 3 }; * const prependKeyAndDouble = (num, key, obj) => key + (num * 2); * * mapObjIndexedReturnArray(prependKeyAndDouble, xyz); //=> ['x2', 'y4', 'z6'] */ const mapObjIndexedReturnArray = _curry2((fn, obj) => _map(key => fn(obj[key], key, obj), keys(obj)), ) module.exports = mapObjIndexedReturnArray
module.exports = function(grunt, options) { return { imports: { files: { '<%= build %>/css/styles.css': '<%= src %>/less/imports.less' } } }; };
module.exports = component var fs = require('fs') var path = require('path') var template = fs.readFileSync(path.join(__dirname, 'template.html')) var dependencies = fs.readFileSync(path.join(__dirname, 'dependencies.html')) var style = fs.readFileSync(path.join(__dirname, 'styles.css')) var definition = fs.readFileSync(path.join(__dirname, 'definition.js')) function component(args) { return { html: ` ${dependencies} <dom-module id="${args.role}-cmp"> <template> <style> ${style} </style> ${template} </template> <script> ${(definition + '').replace(/:role/, args.role + '-cmp')} </script> </dom-module> ` } }
/* global jQuery, select2 */ (function ($) { 'use strict' if (window.self !== window.top) return false var STYLESHEET = 'lib/locator/findcity.css' var CITY_DATA var CITY_DATA_URL = 'https://gist.githubusercontent.com/randymeech/1fb759d34521b43d373d/raw/3d2d7944ae32d819a17d60a44c6702b4406e6c91/cities' function _loadExternalStylesheet () { var el = document.createElement('link') el.setAttribute('rel', 'stylesheet') el.setAttribute('type', 'text/css') el.setAttribute('href', STYLESHEET) document.head.appendChild(el) } _loadExternalStylesheet() $.get(CITY_DATA_URL, function (data) { CITY_DATA = JSON.parse(data); // Process data CITY_DATA = CITY_DATA.map(function (item) { return { name: item.n, lat: item.l.split('/')[0], lng: item.l.split('/')[1], zoom: item.z } }) // Sort CITY_DATA.sort(function (a, b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; }); $(document).ready(function () { var $select = $('.js-citylocate-select2'); CITY_DATA.forEach(function (item) { $select.append('<option value="' + item.name + '" data-lat="' + item.lat + '" data-lng="' + item.lng + '" data-zoom="' + item.zoom + '">' + item.name + '</option>') }) $select.select2({ placeholder: 'Search' }); $select.on('select2:select', function (e) { /* global map */ var el = e.params.data.element var lat = el.dataset.lat var lng = el.dataset.lng var zoom = (el.dataset.zoom === 'undefined') ? null : el.dataset.zoom; // console.log(el, lat, lng, zoom) if (zoom) { map.setView([lat, lng], zoom); } else { map.setView([lat, lng]); } }) }); }) })(jQuery);
/** * @fileoverview Enforce anchor elements to contain accessible content. * @author Lisa Ring & Niklas Holmberg */ // ---------------------------------------------------------------------------- // Rule Definition // ---------------------------------------------------------------------------- import { elementType, hasProp } from 'jsx-ast-utils'; import isHiddenFromScreenReader from '../util/isHiddenFromScreenReader'; const errorMessage = 'Anchors must have content and the content must be accessible by a screen reader.'; const anchors = [ 'a', 'Link', ]; module.exports = { meta: { docs: {}, schema: [ { oneOf: [ { type: 'string' }, { type: 'array', items: { type: 'string', }, minItems: 1, uniqueItems: true, }, ], }, ], }, create: context => ({ JSXOpeningElement: node => { const typeCheck = anchors.concat(context.options[0]); const nodeType = elementType(node); // Only check anchor elements and custom types. if (typeCheck.indexOf(nodeType) === -1) { return; } const isAccessible = node.parent.children.some(child => { switch (child.type) { case 'Literal': return Boolean(child.value); case 'JSXElement': return !isHiddenFromScreenReader( elementType(child.openingElement), child.openingElement.attributes ); case 'JSXExpressionContainer': if (child.expression.type === 'Identifier') { return child.expression.name !== 'undefined'; } return true; default: return false; } }) || hasProp(node.attributes, 'dangerouslySetInnerHTML'); if (isAccessible) { return; } context.report({ node, message: errorMessage, }); }, }), };
// Splits a batch of items up into pages. import {ITEMS_PER_PAGE, NUM_PAGE_BUTTONS} from './AppSettings.js' class PageBatch { constructor(pagesInBatch, itemPerPage) { this.pagesInBatch = pagesInBatch || NUM_PAGE_BUTTONS; this.itemPerPage = itemPerPage || ITEMS_PER_PAGE; this.pageToItems = {} this.hasMore = false; } clearData() { this.pageToItems = {} this.hasMore = false; } setItems(batchPageNum, items, hasMore) { this.hasMore = hasMore; this.pageToItems = {} let pageNum = (batchPageNum - 1)* this.pagesInBatch; for (let i = 0; i < this.pagesInBatch; i++) { let idx = (i * this.itemPerPage); let endIdx = idx + this.itemPerPage; pageNum += 1; let pageItems = []; if (endIdx >= items.length) { pageItems = items.slice(idx) } else { pageItems = items.slice(idx, endIdx) } this.pageToItems[pageNum] = pageItems; } } getItems(pageNum) { return this.pageToItems[pageNum]; } hasPage(pageNum) { return pageNum in this.pageToItems; } isPageEmpty(pageNum) { return this.getItems(pageNum).length == 0; } getBatchPageNum(page) { if (page == -1) { return page; } return parseInt((page - 1)/ this.pagesInBatch) + 1; } getItemsPerBatch() { return this.pagesInBatch * this.itemPerPage; } getPageNums() { return Object.keys(this.pageToItems); } getStartPage() { return this.getPageNums()[0]; } getEndPage() { let pageNums = this.getPageNums(); let lastPage = pageNums[0]; for (let i = 1; i < pageNums.length; i++) { let somePage = pageNums[i]; if (!this.isPageEmpty(somePage)) { lastPage = somePage; } } return lastPage; } canNext(page) { if (page == -1) { return false; } let nextPage = page + 1; if (this.hasPage(nextPage + 1)) { if (this.isPageEmpty(nextPage)) { return false; } else { return true; } } else { return this.hasMore; } } getStartAndEndPages(page) { let numPages = this.pagesInBatch; let startPage = parseInt((page - 1)/ numPages) * numPages + 1; let endPage = startPage + numPages - 1; return { startPage: startPage, endPage: endPage } } } export default PageBatch;
(function() { 'use strict'; var Tooltip = function(element, options) { this.$trigger = $(element); this.options = options || {}; this.id = this.generateId(); this.visible = false; }; Tooltip.prototype.init = function() { // On event in, show tooltip this.$trigger.on('mouseenter focusin', $.proxy(this.show, this)); // On event out, hide tooltip this.$trigger.on('mouseleave focusout', $.proxy(this.hide, this)); }; Tooltip.prototype.generateId = function() { return 'tooltip' + Math.floor((Math.random() * 1000) + 1) + Date.now().toString().slice(7); }; Tooltip.prototype.show = function(e) { if (this.visible) { return; } // Create tooltip var $tooltip = $($.parseHTML(this.options.template)); $tooltip .attr('id', this.id) .addClass('tooltip-' + this.options.placement) .addClass(this.options.state ? 'tooltip-' + this.options.state : null); // Show event var showEvent = $.Event('show.lt.tooltip', { relatedTarget: $tooltip }); this.$trigger.trigger(showEvent); // Allow event to be prevented if (showEvent.isDefaultPrevented()) { return; } // Show tooltip $tooltip .appendTo(document.body) .offset(this.getOffset($tooltip)); this.visible = true; this.$trigger.attr('aria-labelledby', this.id); // Get title this.getTitle($tooltip).then( function(options) { if (typeof options === 'object') { this.options = $.extend(this.options, options); } else { this.options.title = options.toString(); } // Set content if (this.options.html) { $tooltip .find('.tooltip-content') .html(this.options.title); } else { $tooltip .find('.tooltip-content') .text(this.options.title); } // Update classes and re-center $tooltip .addClass(this.options.state ? 'tooltip-' + this.options.state : null) .addClass('tooltip-' + this.options.placement) .offset(this.getOffset($tooltip)); this.options.onShow.call(this, this.$trigger, $tooltip); }.bind(this), function(err, options) { $tooltip .find('.tooltip-content') .text(err && err.message ? err.message : 'Error'); $tooltip .addClass('tooltip-error') .offset(this.getOffset($tooltip)); this.options.onShow.call(this, this.$trigger, $tooltip); }.bind(this) ); // Shown event var shownEvent = $.Event('shown.lt.tooltip', { relatedTarget: $tooltip }); this.$trigger.trigger(shownEvent); }; Tooltip.prototype.getTitle = function($tooltip) { var deferred = $.Deferred(); if (typeof this.options.title === 'string') { deferred.resolve(this.options.title); } else if (typeof this.options.title === 'function') { $.when(this.options.title.call(this, $tooltip, this.$trigger)).then(function(result) { deferred.resolve(result); }, function(err) { deferred.reject(err); }); } else if (typeof this.options.title === 'object') { $.when(this.options.title).then(function(result) { deferred.resolve(result); }, function(err) { deferred.reject(err); }); } else { deferred.resolve(this.$trigger.attr('title')); } return deferred; }; Tooltip.prototype.getOffset = function($tooltip) { var coords = this.$trigger.offset(); var position = this.options.placement; var top = coords.top; var left = coords.left; var height = this.$trigger.outerHeight(); var width = this.$trigger.outerWidth(); var tooltipHeight = $tooltip.outerHeight(); var tooltipWidth = $tooltip.outerWidth(); var result = { top: top, left: left }; if (position === 'top' || position === 'bottom') { result.left = left + Math.floor(width / 2) - Math.floor(tooltipWidth / 2); } if (position === 'right' || position === 'left') { result.top = top + Math.floor(height / 2) - Math.floor(tooltipHeight / 2); } if (position === 'top') { result.top = top - tooltipHeight; } else if (position === 'right') { result.left = left + width; } else if (position === 'bottom') { result.top = top + height; } else if (position === 'left') { result.left = left - tooltipWidth; } return result; }; Tooltip.prototype.hide = function(e) { if (!this.visible) { return; } var $tooltip = $('#' + this.id); // Hide event var hideEvent = $.Event('hide.lt.tooltip', { relatedTarget: $tooltip }); this.$trigger.trigger(hideEvent); // Allow event to be prevented if (hideEvent.isDefaultPrevented()) { return; } // Set state and remove tooltip this.visible = false; $tooltip.remove(); this.$trigger.attr('aria-labelledby', null); this.options.onHide.call(this, this.$trigger); // Hidden event var hiddenEvent = $.Event('hidden.lt.tooltip', { relatedTarget: $tooltip }); this.$trigger.trigger(hiddenEvent); }; // Define jQuery plugin function Plugin(method) { return this.each(function() { var $this = $(this); var settings = $.extend({}, Plugin.defaults, $this.data(), typeof method === 'object' && method); var data = $this.data('lt.tooltip'); if (!data) { data = new Tooltip(this, settings); $this.data('lt.tooltip', data); } if (typeof method === 'string') { data[method](); } else { data.init(); } }); } Plugin.defaults = { onShow: function() {}, onHide: function() {}, html: false, state: null, placement: 'top', template: '<div class="tooltip" role="tooltip"><div class="tooltip-content">Loading...</div></div>' }; $.fn.tooltip = Plugin; })(jQuery);
export default function hasChildren(tree) { return tree.children !== undefined && tree.children.length > 0; }
/** * Tools * Pokemon Showdown - http://pokemonshowdown.com/ * * Handles getting data about pokemon, items, etc. * * This file is used by the main process (to validate teams) * as well as the individual simulator processes (to get * information about pokemon, items, etc to simulate). * * @license MIT license */ module.exports = (function () { var dataTypes = ['FormatsData', 'Learnsets', 'Pokedex', 'Movedex', 'Statuses', 'TypeChart', 'Scripts', 'Items', 'Abilities', 'Formats', 'Aliases']; var dataFiles = { 'Pokedex': 'pokedex.js', 'Movedex': 'moves.js', 'Statuses': 'statuses.js', 'TypeChart': 'typechart.js', 'Scripts': 'scripts.js', 'Items': 'items.js', 'Abilities': 'abilities.js', 'Formats': 'formats.js', 'FormatsData': 'formats-data.js', 'Learnsets': 'learnsets.js', 'Aliases': 'aliases.js' }; function Tools(mod) { if (!mod) { mod = 'base'; this.isBase = true; } this.currentMod = mod; Data[mod] = { mod: mod }; if (mod === 'base') { dataTypes.forEach(function(dataType) { try { var path = './data/' + dataFiles[dataType]; if (fs.existsSync(path)) { Data[mod][dataType] = require(path)['Battle' + dataType]; } } catch (e) { console.log(e.stack); } if (!Data[mod][dataType]) Data[mod][dataType] = {}; }, this); try { var path = './config/formats.js'; if (fs.existsSync(path)) { var configFormats = require(path).Formats; for (var i=0; i<configFormats.length; i++) { var id = toId(configFormats[i].name); configFormats[i].effectType = 'Format'; Data[mod].Formats[id] = configFormats[i]; } } } catch (e) { console.log(e.stack); } } else { dataTypes.forEach(function(dataType) { try { var path = './mods/' + mod + '/' + dataFiles[dataType]; if (fs.existsSync(path)) { Data[mod][dataType] = require(path)['Battle' + dataType]; } } catch (e) { console.log(e.stack); } if (!Data[mod][dataType]) Data[mod][dataType] = {}; for (var i in Data.base[dataType]) { if (Data[mod][dataType][i] === null) { // null means don't inherit delete Data[mod][dataType][i]; } else if (!(i in Data[mod][dataType])) { // If it doesn't exist it's inherited from the base data if (dataType === 'Pokedex') { // Pokedex entries can be modified too many different ways Data[mod][dataType][i] = Object.clone(Data.base[dataType][i], true); } else { Data[mod][dataType][i] = Data.base[dataType][i]; } } else if (Data[mod][dataType][i] && Data[mod][dataType][i].inherit) { // {inherit: true} can be used to modify only parts of the base data, // instead of overwriting entirely delete Data[mod][dataType][i].inherit; Object.merge(Data[mod][dataType][i], Data.base[dataType][i], true, false); } } }); } this.data = Data[mod]; } var moddedTools = {}; Tools.prototype.mod = function(mod) { if (!moddedTools[mod]) { mod = this.getFormat(mod).mod; } if (!mod) mod = 'base'; return moddedTools[mod]; }; Tools.prototype.modData = function(dataType, id) { if (this.isBase) return this.data[dataType][id]; if (this.data[dataType][id] !== moddedTools.base.data[dataType][id]) return this.data[dataType][id]; return this.data[dataType][id] = Object.clone(this.data[dataType][id], true); }; Tools.prototype.effectToString = function() { return this.name; }; Tools.prototype.getImmunity = function(type, target) { for (var i=0; i<target.types.length; i++) { if (this.data.TypeChart[target.types[i]] && this.data.TypeChart[target.types[i]].damageTaken && this.data.TypeChart[target.types[i]].damageTaken[type] === 3) { return false; } } return true; }; Tools.prototype.getEffectiveness = function(type, target) { var totalTypeMod = 0; for (var i=0; i<target.types.length; i++) { if (!this.data.TypeChart[target.types[i]]) continue; var typeMod = this.data.TypeChart[target.types[i]].damageTaken[type]; if (typeMod === 1) { // super-effective totalTypeMod++; } if (typeMod === 2) { // resist totalTypeMod--; } // in case of weird situations like Gravity, immunity is // handled elsewhere } return totalTypeMod; }; Tools.prototype.getTemplate = function(template) { if (!template || typeof template === 'string') { var name = (template||'').trim(); var id = toId(name); if (this.data.Aliases[id]) { name = this.data.Aliases[id]; id = toId(name); } template = {}; if (id && this.data.Pokedex[id]) { template = this.data.Pokedex[id]; if (template.cached) return template; template.cached = true; template.exists = true; } name = template.species || template.name || name; if (this.data.FormatsData[id]) { Object.merge(template, this.data.FormatsData[id]); } if (this.data.Learnsets[id]) { Object.merge(template, this.data.Learnsets[id]); } if (!template.id) template.id = id; if (!template.name) template.name = name; if (!template.speciesid) template.speciesid = id; if (!template.species) template.species = name; if (!template.baseSpecies) template.baseSpecies = name; if (!template.forme) template.forme = ''; if (!template.formeLetter) template.formeLetter = ''; if (!template.spriteid) template.spriteid = toId(template.baseSpecies)+(template.baseSpecies!==name?'-'+toId(template.forme):''); if (!template.prevo) template.prevo = ''; if (!template.evos) template.evos = []; if (!template.nfe) template.nfe = !!template.evos.length; if (!template.gender) template.gender = ''; if (!template.genderRatio && template.gender === 'M') template.genderRatio = {M:1,F:0}; if (!template.genderRatio && template.gender === 'F') template.genderRatio = {M:0,F:1}; if (!template.genderRatio && template.gender === 'N') template.genderRatio = {M:0,F:0}; if (!template.genderRatio) template.genderRatio = {M:0.5,F:0.5}; if (!template.tier) template.tier = 'Illegal'; if (!template.gen) { if (template.num >= 494) template.gen = 5; else if (template.num >= 387) template.gen = 4; else if (template.num >= 252) template.gen = 3; else if (template.num >= 152) template.gen = 2; else if (template.num >= 1) template.gen = 1; else template.gen = 0; } } return template; }; Tools.prototype.getMove = function(move) { if (!move || typeof move === 'string') { var name = (move||'').trim(); var id = toId(name); if (this.data.Aliases[id]) { name = this.data.Aliases[id]; id = toId(name); } move = {}; if (id.substr(0,11) === 'hiddenpower') { var matches = /([a-z]*)([0-9]*)/.exec(id); id = matches[1]; } if (id && this.data.Movedex[id]) { move = this.data.Movedex[id]; if (move.cached) return move; move.cached = true; move.exists = true; } if (!move.id) move.id = id; if (!move.name) move.name = name; if (!move.fullname) move.fullname = 'move: '+move.name; move.toString = this.effectToString; if (!move.critRatio) move.critRatio = 1; if (!move.baseType) move.baseType = move.type; if (!move.effectType) move.effectType = 'Move'; if (!move.secondaries && move.secondary) move.secondaries = [move.secondary]; if (!move.gen) { if (move.num >= 468) move.gen = 5; else if (move.num >= 355) move.gen = 4; else if (move.num >= 252) move.gen = 3; else if (move.num >= 166) move.gen = 2; else if (move.num >= 1) move.gen = 1; else move.gen = 0; } if (!move.priority) move.priority = 0; } return move; }; /** * Ensure we're working on a copy of a move (and make a copy if we aren't) * * Remember: "ensure" - by default, it won't make a copy of a copy: * moveCopy === Tools.getMoveCopy(moveCopy) * * If you really want to, use: * moveCopyCopy = Tools.getMoveCopy(moveCopy.id) * * @param move Move ID, move object, or movecopy object describing move to copy * @return movecopy object */ Tools.prototype.getMoveCopy = function(move) { if (move && move.isCopy) return move; move = this.getMove(move); var moveCopy = Object.clone(move, true); moveCopy.isCopy = true; return moveCopy; }; Tools.prototype.getEffect = function(effect) { if (!effect || typeof effect === 'string') { var name = (effect||'').trim(); var id = toId(name); effect = {}; if (id && this.data.Statuses[id]) { effect = this.data.Statuses[id]; effect.name = effect.name || this.data.Statuses[id].name; } else if (id && this.data.Movedex[id] && this.data.Movedex[id].effect) { effect = this.data.Movedex[id].effect; effect.name = effect.name || this.data.Movedex[id].name; } else if (id && this.data.Abilities[id] && this.data.Abilities[id].effect) { effect = this.data.Abilities[id].effect; effect.name = effect.name || this.data.Abilities[id].name; } else if (id && this.data.Items[id] && this.data.Items[id].effect) { effect = this.data.Items[id].effect; effect.name = effect.name || this.data.Items[id].name; } else if (id && this.data.Formats[id]) { effect = this.data.Formats[id]; effect.name = effect.name || this.data.Formats[id].name; if (!effect.mod) effect.mod = this.currentMod; if (!effect.effectType) effect.effectType = 'Format'; } else if (id === 'recoil') { effect = { effectType: 'Recoil' }; } else if (id === 'drain') { effect = { effectType: 'Drain' }; } if (!effect.id) effect.id = id; if (!effect.name) effect.name = name; if (!effect.fullname) effect.fullname = effect.name; effect.toString = this.effectToString; if (!effect.category) effect.category = 'Effect'; if (!effect.effectType) effect.effectType = 'Effect'; } return effect; }; Tools.prototype.getFormat = function(effect) { if (!effect || typeof effect === 'string') { var name = (effect||'').trim(); var id = toId(name); effect = {}; if (id && this.data.Formats[id]) { effect = this.data.Formats[id]; if (effect.cached) return effect; effect.cached = true; effect.name = effect.name || this.data.Formats[id].name; if (!effect.mod) effect.mod = this.currentMod; if (!effect.effectType) effect.effectType = 'Format'; } if (!effect.id) effect.id = id; if (!effect.name) effect.name = name; if (!effect.fullname) effect.fullname = effect.name; effect.toString = this.effectToString; if (!effect.category) effect.category = 'Effect'; if (!effect.effectType) effect.effectType = 'Effect'; this.getBanlistTable(effect); } return effect; }; Tools.prototype.getItem = function(item) { if (!item || typeof item === 'string') { var name = (item||'').trim(); var id = toId(name); if (this.data.Aliases[id]) { name = this.data.Aliases[id]; id = toId(name); } item = {}; if (id && this.data.Items[id]) { item = this.data.Items[id]; if (item.cached) return item; item.cached = true; item.exists = true; } if (!item.id) item.id = id; if (!item.name) item.name = name; if (!item.fullname) item.fullname = 'item: '+item.name; item.toString = this.effectToString; if (!item.category) item.category = 'Effect'; if (!item.effectType) item.effectType = 'Item'; if (item.isBerry) item.fling = { basePower: 10 }; if (!item.gen) { if (item.num >= 537) item.gen = 5; else if (item.num >= 377) item.gen = 4; // Due to difference in storing items, gen 2 items must be specified specifically else item.gen = 3; } } return item; }; Tools.prototype.getAbility = function(ability) { if (!ability || typeof ability === 'string') { var name = (ability||'').trim(); var id = toId(name); ability = {}; if (id && this.data.Abilities[id]) { ability = this.data.Abilities[id]; if (ability.cached) return ability; ability.cached = true; ability.exists = true; } if (!ability.id) ability.id = id; if (!ability.name) ability.name = name; if (!ability.fullname) ability.fullname = 'ability: '+ability.name; ability.toString = this.effectToString; if (!ability.category) ability.category = 'Effect'; if (!ability.effectType) ability.effectType = 'Ability'; if (!ability.gen) { if (ability.num >= 124) ability.gen = 5; else if (ability.num >= 77) ability.gen = 4; else if (ability.num >= 1) ability.gen = 3; else ability.gen = 0; } } return ability; }; Tools.prototype.getType = function(type) { if (!type || typeof type === 'string') { var id = toId(type); id = id.substr(0,1).toUpperCase() + id.substr(1); type = {}; if (id && this.data.TypeChart[id]) { type = this.data.TypeChart[id]; if (type.cached) return type; type.cached = true; type.exists = true; type.isType = true; type.effectType = 'Type'; } if (!type.id) type.id = id; if (!type.effectType) { // man, this is really meta type.effectType = 'EffectType'; } } return type; }; var BattleNatures = { Adamant: {plus:'atk', minus:'spa'}, Bashful: {}, Bold: {plus:'def', minus:'atk'}, Brave: {plus:'atk', minus:'spe'}, Calm: {plus:'spd', minus:'atk'}, Careful: {plus:'spd', minus:'spa'}, Docile: {}, Gentle: {plus:'spd', minus:'def'}, Hardy: {}, Hasty: {plus:'spe', minus:'def'}, Impish: {plus:'def', minus:'spa'}, Jolly: {plus:'spe', minus:'spa'}, Lax: {plus:'def', minus:'spd'}, Lonely: {plus:'atk', minus:'def'}, Mild: {plus:'spa', minus:'def'}, Modest: {plus:'spa', minus:'atk'}, Naive: {plus:'spe', minus:'spd'}, Naughty: {plus:'atk', minus:'spd'}, Quiet: {plus:'spa', minus:'spe'}, Quirky: {}, Rash: {plus:'spa', minus:'spd'}, Relaxed: {plus:'def', minus:'spe'}, Sassy: {plus:'spd', minus:'spe'}, Serious: {}, Timid: {plus:'spe', minus:'atk'} }; Tools.prototype.getNature = function(nature) { if (typeof nature === 'string') nature = BattleNatures[nature]; if (!nature) nature = {}; return nature; }; Tools.prototype.natureModify = function(stats, nature) { if (typeof nature === 'string') nature = BattleNatures[nature]; if (!nature) return stats; if (nature.plus) stats[nature.plus] *= 1.1; if (nature.minus) stats[nature.minus] *= 0.9; return stats; }; Tools.prototype.checkLearnset = function(move, template, lsetData) { move = toId(move); template = this.getTemplate(template); lsetData = lsetData || {}; var set = (lsetData.set || (lsetData.set={})); var format = (lsetData.format || (lsetData.format={})); var alreadyChecked = {}; var level = set.level || 100; var limit1 = true; var sketch = false; // This is a pretty complicated algorithm // Abstractly, what it does is construct the union of sets of all // possible ways this pokemon could be obtained, and then intersect // it with a the pokemon's existing set of all possible ways it could // be obtained. If this intersection is non-empty, the move is legal. // We apply several optimizations to this algorithm. The most // important is that with, for instance, a TM move, that Pokemon // could have been obtained from any gen at or before that TM's gen. // Instead of adding every possible source before or during that gen, // we keep track of a maximum gen variable, intended to mean "any // source at or before this gen is possible." // set of possible sources of a pokemon with this move, represented as an array var sources = []; // the equivalent of adding "every source at or before this gen" to sources var sourcesBefore = 0; do { alreadyChecked[template.speciesid] = true; if (template.learnset) { if (template.learnset[move] || template.learnset['sketch']) { var lset = template.learnset[move]; if (!lset) { lset = template.learnset['sketch']; sketch = true; } if (typeof lset === 'string') lset = [lset]; for (var i=0, len=lset.length; i<len; i++) { var learned = lset[i]; if (learned.substr(0,2) in {'4L':1,'5L':1}) { // gen 4 or 5 level-up moves if (level >= parseInt(learned.substr(2),10)) { // Chatter and Struggle cannot be sketched if (sketch && (move === 'chatter' || move === 'struggle')) return true; // we're past the required level to learn it return false; } if (!template.gender || template.gender === 'F') { // available as egg move learned = learned.substr(0,1)+'Eany'; } else { // this move is unavailable, skip it continue; } } if (learned.substr(1,1) in {L:1,M:1,T:1}) { if (learned.substr(0,1) === '5') { // current-gen TM or tutor moves: // always available return false; } // past-gen level-up, TM, or tutor moves: // available as long as the source gen was or was before this gen limit1 = false; sourcesBefore = Math.max(sourcesBefore, parseInt(learned.substr(0,1),10)); } else if (learned.substr(1,1) in {E:1,S:1,D:1}) { // egg, event, or DW moves: // only if that was the source if (learned.substr(1,1) === 'E') { // it's an egg move, so we add each pokemon that can be bred with to its sources var eggGroups = template.eggGroups; if (!eggGroups) continue; if (eggGroups[0] === 'No Eggs') eggGroups = this.getTemplate(template.evos[0]).eggGroups; var atLeastOne = false; var fromSelf = (learned.substr(1) === 'Eany'); learned = learned.substr(0,2); for (var templateid in this.data.Pokedex) { var dexEntry = this.getTemplate(templateid); if ( // CAP pokemon can't breed !dexEntry.isNonstandard && // can't breed mons from future gens dexEntry.gen <= parseInt(learned.substr(0,1),10) && // genderless pokemon can't pass egg moves dexEntry.gender !== 'N') { if ( // chainbreeding fromSelf || // otherwise parent must be able to learn the move !alreadyChecked[dexEntry.speciesid] && dexEntry.learnset && (dexEntry.learnset[move]||dexEntry.learnset['sketch'])) { if (dexEntry.eggGroups.intersect(eggGroups).length) { // we can breed with it atLeastOne = true; sources.push(learned+dexEntry.id); } } } } // chainbreeding with itself from earlier gen if (!atLeastOne) sources.push(learned+template.id); } else if (learned.substr(1,1) === 'S') { sources.push(learned+' '+template.id); } else { sources.push(learned); } } } } if (format.mimicGlitch && template.gen < 5) { // include the Mimic Glitch when checking this mon's learnset var glitchMoves = {metronome:1, copycat:1, transform:1, mimic:1, assist:1}; var getGlitch = false; for (var i in glitchMoves) { if (template.learnset[i]) { if (i === 'mimic' && this.getAbility(set.ability).gen == 4 && !template.prevo) { // doesn't get the glitch } else { getGlitch = true; break; } } } if (getGlitch) { sourcesBefore = Math.max(sourcesBefore, 4); if (this.getMove(move).gen < 5) { limit1 = false; } } } } // also check to see if the mon's prevo or freely switchable formes can learn this move if (template.prevo) { template = this.getTemplate(template.prevo); } else if (template.speciesid === 'shaymin') { template = this.getTemplate('shayminsky'); } else if (template.baseSpecies !== template.species && template.baseSpecies !== 'Kyurem') { template = this.getTemplate(template.baseSpecies); } else { template = null; } } while (template && template.species && !alreadyChecked[template.speciesid]); if (limit1 && sketch) { // limit 1 sketch move if (lsetData.sketchMove) { return {type:'oversketched', maxSketches: 1}; } lsetData.sketchMove = move; } // Now that we have our list of possible sources, intersect it with the current list if (!sourcesBefore && !sources.length) { return true; } if (!sources.length) sources = null; if (sourcesBefore || lsetData.sourcesBefore) { // having sourcesBefore is the equivalent of having everything before that gen // in sources, so we fill the other array in preparation for intersection if (sourcesBefore && lsetData.sources) { if (!sources) sources = []; for (var i=0, len=lsetData.sources.length; i<len; i++) { var learned = lsetData.sources[i]; if (parseInt(learned.substr(0,1),10) <= sourcesBefore) { sources.push(learned); } } if (!lsetData.sourcesBefore) sourcesBefore = 0; } if (lsetData.sourcesBefore && sources) { if (!lsetData.sources) lsetData.sources = []; for (var i=0, len=sources.length; i<len; i++) { var learned = sources[i]; if (parseInt(learned.substr(0,1),10) <= lsetData.sourcesBefore) { lsetData.sources.push(learned); } } if (!sourcesBefore) delete lsetData.sourcesBefore; } } if (sources) { if (lsetData.sources) { var intersectSources = lsetData.sources.intersect(sources); if (!intersectSources.length && !(sourcesBefore && lsetData.sourcesBefore)) { return {type:'incompatible'}; } lsetData.sources = intersectSources; } else { lsetData.sources = sources.unique(); } } if (sourcesBefore) { lsetData.sourcesBefore = Math.min(sourcesBefore, lsetData.sourcesBefore||5); } return false; }; Tools.prototype.getBanlistTable = function(format, subformat, depth) { var banlistTable; if (!depth) depth = 0; if (depth>8) return; // avoid infinite recursion if (format.banlistTable && !subformat) { banlistTable = format.banlistTable; } else { if (!format.banlistTable) format.banlistTable = {}; if (!format.setBanTable) format.setBanTable = []; if (!format.teamBanTable) format.teamBanTable = []; banlistTable = format.banlistTable; if (!subformat) subformat = format; if (subformat.banlist) { for (var i=0; i<subformat.banlist.length; i++) { // don't revalidate what we already validate if (banlistTable[toId(subformat.banlist[i])]) continue; banlistTable[subformat.banlist[i]] = subformat.name || true; banlistTable[toId(subformat.banlist[i])] = subformat.name || true; var plusPos = subformat.banlist[i].indexOf('+'); if (plusPos && plusPos > 0) { var plusPlusPos = subformat.banlist[i].indexOf('++'); if (plusPlusPos && plusPlusPos > 0) { var complexList = subformat.banlist[i].split('++'); for (var j=0; j<complexList.length; j++) { complexList[j] = toId(complexList[j]); } format.teamBanTable.push(complexList); } else { var complexList = subformat.banlist[i].split('+'); for (var j=0; j<complexList.length; j++) { complexList[j] = toId(complexList[j]); } format.setBanTable.push(complexList); } } } } if (subformat.ruleset) { for (var i=0; i<subformat.ruleset.length; i++) { // don't revalidate what we already validate if (banlistTable['Rule:'+toId(subformat.ruleset[i])]) continue; banlistTable['Rule:'+toId(subformat.ruleset[i])] = subformat.ruleset[i]; if (format.ruleset.indexOf(subformat.ruleset[i]) === -1) format.ruleset.push(subformat.ruleset[i]); var subsubformat = this.getFormat(subformat.ruleset[i]); if (subsubformat.ruleset || subsubformat.banlist) { this.getBanlistTable(format, subsubformat, depth+1); } } } } return banlistTable; }; Tools.prototype.validateTeam = function(team, format, forceThisMod) { format = this.getFormat(format); if (!forceThisMod && this.isBase && format.mod !== this.currentMod) { return this.mod(format).validateTeam(team, format, true); } var problems = []; this.getBanlistTable(format); if (format.team === 'random' || format.team === 'cc') { return false; } if (!team || !Array.isArray(team)) { if (format.canUseRandomTeam) { return false; } return ["You sent invalid team data. If you're not using a custom client, please report this as a bug."]; } if (!team.length) { return ["Your team has no pokemon."]; } if (team.length>6) { return ["Your team has more than 6 pokemon."]; } var teamHas = {}; for (var i=0; i<team.length; i++) { var setProblems = this.validateSet(team[i], format, teamHas); if (setProblems) { problems = problems.concat(setProblems); } } for (var i=0; i<format.teamBanTable.length; i++) { var bannedCombo = ''; for (var j=0; j<format.teamBanTable[i].length; j++) { if (!teamHas[format.teamBanTable[i][j]]) { bannedCombo = false; break; } if (j == 0) { bannedCombo += format.teamBanTable[i][j]; } else { bannedCombo += ' and '+format.teamBanTable[i][j]; } } if (bannedCombo) { clause = format.name ? " by "+format.name : ''; problems.push("Your team has the combination of "+bannedCombo+", which is banned"+clause+"."); } } if (format.ruleset) { for (var i=0; i<format.ruleset.length; i++) { var subformat = this.getFormat(format.ruleset[i]); if (subformat.validateTeam) { problems = problems.concat(subformat.validateTeam.call(this, team, format)||[]); } } } if (format.validateTeam) { problems = problems.concat(format.validateTeam.call(this, team, format)||[]); } if (!problems.length) return false; return problems; }; Tools.prototype.validateSet = function(set, format, teamHas, forceThisMod) { format = this.getFormat(format); if (!forceThisMod && this.isBase && format.mod !== this.currentMod) { return this.mod(format).validateSet(set, format, teamHas, true); } var problems = []; if (!set) { return ["This is not a Pokemon."]; } var template = this.getTemplate(string(set.species)); if (!template.exists) { return ["The Pokemon '"+set.species+"' does not exist."]; } set.species = template.species; set.name = toName(set.name); var item = this.getItem(string(set.item)); set.item = item.name; var ability = this.getAbility(string(set.ability)); set.ability = ability.name; if (!Array.isArray(set.moves)) set.moves = []; var maxLevel = format.maxLevel || 100; var maxForcedLevel = format.maxForcedLevel || maxLevel; if (!set.level) { set.level = (format.defaultLevel || maxLevel); } if (format.forcedLevel) { set.forcedLevel = format.forcedLevel; } else if (set.level >= maxForcedLevel) { set.forcedLevel = maxForcedLevel; } if (set.level > maxLevel || set.level == set.forcedLevel || set.level == set.maxForcedLevel) { set.level = maxLevel; } set.species = set.species || set.name || 'Bulbasaur'; set.name = set.name || set.species; var name = set.species; if (set.species !== set.name) name = set.name + " ("+set.species+")"; var isDW = false; var lsetData = {set:set, format:format}; var setHas = {}; if (!template || !template.abilities) { set.species = 'Bulbasaur'; template = this.getTemplate('Bulbasaur'); } var banlistTable = this.getBanlistTable(format); var check = toId(set.species); var clause = ''; setHas[check] = true; if (banlistTable[check]) { clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : ''; problems.push(set.species+' is banned'+clause+'.'); } check = toId(set.ability); setHas[check] = true; if (banlistTable[check]) { clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : ''; problems.push(name+"'s ability "+set.ability+" is banned"+clause+"."); } check = toId(set.item); setHas[check] = true; if (banlistTable[check]) { clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : ''; problems.push(name+"'s item "+set.item+" is banned"+clause+"."); } if (banlistTable['Unreleased'] && item.isUnreleased) { problems.push(name+"'s item "+set.item+" is unreleased."); } setHas[toId(set.ability)] = true; if (banlistTable['illegal']) { var totalEV = 0; for (var k in set.evs) { if (typeof set.evs[k] !== 'number') { set.evs[k] = 0; } totalEV += set.evs[k]; } if (totalEV > 510) { problems.push(name+" has more than 510 total EVs."); } // Don't check abilities for metagames with All Abilities if (this.gen <= 2) { set.ability = ''; } else if (!banlistTable['ignoreillegalabilities']) { if (!ability.name) { problems.push(name+" needs to have an ability."); } else if (ability.name !== template.abilities['0'] && ability.name !== template.abilities['1'] && ability.name !== template.abilities['DW']) { problems.push(name+" can't have "+set.ability+"."); } if (ability.name === template.abilities['DW']) { isDW = true; if (!template.dreamWorldRelease && banlistTable['Unreleased']) { problems.push(name+"'s Dream World ability is unreleased."); } else if (set.level < 10 && (template.maleOnlyDreamWorld || template.gender === 'N')) { problems.push(name+" must be at least level 10 with its DW ability."); } if (template.maleOnlyDreamWorld) { set.gender = 'M'; lsetData.sources = ['5D']; } } } } if (set.moves && Array.isArray(set.moves)) { set.moves = set.moves.filter(function(val){ return val; }); } if (!set.moves || !set.moves.length) { problems.push(name+" has no moves."); } else { // A limit is imposed here to prevent too much engine strain or // too much layout deformation - to be exact, this is the Debug // Mode limitation. // The usual limit of 4 moves is handled elsewhere - currently // in the cartridge-compliant set validator: formats.js:pokemon set.moves = set.moves.slice(0,24); for (var i=0; i<set.moves.length; i++) { if (!set.moves[i]) continue; var move = this.getMove(string(set.moves[i])); set.moves[i] = move.name; check = move.id; setHas[check] = true; if (banlistTable[check]) { clause = typeof banlistTable[check] === 'string' ? " by "+ banlistTable[check] : ''; problems.push(name+"'s move "+set.moves[i]+" is banned"+clause+"."); } if (banlistTable['illegal']) { var problem = this.checkLearnset(move, template, lsetData); if (problem) { var problemString = name+" can't learn "+move.name; if (problem.type === 'incompatible') { if (isDW) { problemString = problemString.concat(" because it's incompatible with its ability or another move."); } else { problemString = problemString.concat(" because it's incompatible with another move."); } } else if (problem.type === 'oversketched') { problemString = problemString.concat(" because it can only sketch "+problem.maxSketches+" move"+(problem.maxSketches>1?"s":"")+"."); } else { problemString = problemString.concat("."); } problems.push(problemString); } } } if (lsetData.sources && lsetData.sources.length === 1 && !lsetData.sourcesBefore) { // we're restricted to a single source var source = lsetData.sources[0]; if (source.substr(1,1) === 'S') { // it's an event var eventData = null; var splitSource = source.substr(2).split(' '); var eventTemplate = this.getTemplate(splitSource[1]); if (eventTemplate.eventPokemon) eventData = eventTemplate.eventPokemon[parseInt(splitSource[0],10)]; if (eventData) { if (eventData.nature && eventData.nature !== set.nature) { problems.push(name+" must come from a specific event that gives it a "+eventData.nature+" nature."); } if (eventData.shiny) { set.shiny = true; } if (eventData.generation < 5) eventData.isDW = false; if (eventData.isDW !== undefined && eventData.isDW !== isDW) { problems.push(name+" must come from a specific event that "+(isDW?"gives":"doesn't give")+" it its DW ability."); } if (eventData.abilities && eventData.abilities.indexOf(ability.id) < 0) { problems.push(name+" must come from a specific event that gives it "+eventData.abilities.join(" or ")+"."); } if (eventData.gender) { set.gender = eventData.gender; } if (eventData.level && set.level < eventData.level) { problems.push(name+" must come from a specific event that makes it at least level "+eventData.level+"."); } } isDW = false; } } if (isDW && template.gender) { if (!lsetData.sources && lsetData.sourcesBefore < 5) { problems.push(name+" has a DW ability - it can't have moves only learned before gen 5."); } else if (lsetData.sources) { var compatibleSource = false; for (var i=0,len=lsetData.sources.length; i<len; i++) { if (lsetData.sources[i].substr(0,2) === '5E' || (lsetData.sources[i].substr(0,2) === '5D' && set.level >= 10)) { compatibleSource = true; break; } } if (!compatibleSource) { problems.push(name+" has moves incompatible with its DW ability."); } } } if (set.level < template.evoLevel) { // FIXME: Event pokemon given at a level under what it normally can be attained at gives a false positive problems.push(name+" must be at least level "+template.evoLevel+"."); } if (!lsetData.sources && lsetData.sourcesBefore <= 3 && this.getAbility(set.ability).gen === 4 && !template.prevo) { problems.push(name+" has a gen 4 ability and isn't evolved - it can't use anything from gen 3."); } } setHas[toId(template.tier)] = true; if (banlistTable[template.tier]) { problems.push(name+" is in "+template.tier+", which is banned."); } if (teamHas) { for (var i in setHas) { teamHas[i] = true; } } for (var i=0; i<format.setBanTable.length; i++) { var bannedCombo = ''; for (var j=0; j<format.setBanTable[i].length; j++) { if (!setHas[format.setBanTable[i][j]]) { bannedCombo = false; break; } if (j == 0) { bannedCombo += format.setBanTable[i][j]; } else { bannedCombo += ' and '+format.setBanTable[i][j]; } } if (bannedCombo) { clause = format.name ? " by "+format.name : ''; problems.push(name+" has the combination of "+bannedCombo+", which is banned"+clause+"."); } } if (format.ruleset) { for (var i=0; i<format.ruleset.length; i++) { var subformat = this.getFormat(format.ruleset[i]); if (subformat.validateSet) { problems = problems.concat(subformat.validateSet.call(this, set, format)||[]); } } } if (format.validateSet) { problems = problems.concat(format.validateSet.call(this, set, format)||[]); } if (!problems.length) return false; return problems; }; /** * Install our Tools functions into the battle object */ Tools.prototype.install = function(battle) { for (var i in this.data.Scripts) { battle[i] = this.data.Scripts[i]; } }; Tools.construct = function(mod) { var tools = new Tools(mod); // Scripts override Tools. var ret = Object.create(tools); tools.install(ret); if (ret.init) { ret.init(); } return ret; }; moddedTools.base = Tools.construct(); try { var dirs = fs.readdirSync('./mods/'); dirs.forEach(function(dir) { moddedTools[dir] = Tools.construct(dir); }); } catch (e) {} moddedTools.base.__proto__.moddedTools = moddedTools; return moddedTools.base; })();
console.log('kn7 init...'); $('#portfolio_link').on('click', function(e) { $(this).siblings('span').click(); }); $('#projects_link').on('click', function(e) { $(this).siblings('span').click(); });
// Functions related to rendering and attaching DOM elements var TT = TT || {}; TT.View = (function () { var pub = {}; pub.MIN_COLUMN_WIDTH = 220; pub.Templates = {}; // client-side templating is abstracted away pub.render = function (name, data) { if (!pub.Templates[name]) { pub.Templates[name] = new Hogan.Template(HoganTemplates[name]); } return pub.Templates[name].render(data); }; pub.attach = function (html, target, method) { // Valid methods are appendTo, prependTo, insertAfter, insertBefore // since they return the new element, not the target method = method || 'appendTo'; return $(html)[method](target); }; pub.drawPageLayout = function () { return pub.attach(pub.render('layout'), 'body'); }; var containerWidthTimeout; pub.updateColumnDimensions = function () { var $window = $(window); var $columns = $('#columns .column'); var $container = $('#columns'); if ($columns.length === 0) { $('#columns').width('90%'); return false; } // Calculate column height. var heightOffset = 26; var columnHeight = $window.height() - ($('.column-bucket').offset().top + heightOffset); $('.column-bucket').height(columnHeight); // Tally empty columns. var emptyColumnCount = 0; $columns.each(function () { var $column = $(this); var name = $column.data('name'); if ($column.find('.story').length === 0 && name !== 'Labels') { $column.addClass('empty-column'); emptyColumnCount++; } else { $column.removeClass('empty-column'); } }); // Calculate column width. var columnCount = $columns.length; var windowMargin = 14; var columnMargin = 6; var emptyColumnWidth = 100 + columnMargin; var calculatedColumnWidth = 0; var availableWidth = $window.width() - windowMargin; if (emptyColumnCount === columnCount) { $container.removeClass('not-all-empty'); } else { $container.addClass('not-all-empty'); } if (emptyColumnCount > 0 && emptyColumnCount !== columnCount) { // Revise available width and recalculate availableWidth -= (emptyColumnWidth * emptyColumnCount); calculatedColumnWidth = availableWidth / (columnCount - emptyColumnCount); } else { calculatedColumnWidth = availableWidth / columnCount; } var finalColumnWidth = Math.max(pub.MIN_COLUMN_WIDTH, calculatedColumnWidth - columnMargin); $columns.width(finalColumnWidth); // Set column container width. var times = 20; clearTimeout(containerWidthTimeout); function setContainerWidth() { var containerWidth = 0; $columns.each(function () { containerWidth += $(this).width() + columnMargin; }); $container.css({ minWidth: containerWidth }); if (times--) { containerWidthTimeout = setTimeout(setContainerWidth, 20); } } pub.setSortableColumnHeight(columnHeight); setContainerWidth(); }; pub.setSortableColumnHeight = function (columnHeight) { $('#columns .bucket-content').each(function () { var parent = $(this).parent(); var height = columnHeight - parent.find('.bucket-template').outerHeight() - 4; $(this).css({ minHeight: height }); }); }; pub.drawColumnListNav = function () { $('#columnList .column-list-nav').remove(); var html = pub.render('columnListNav', { columns: TT.Model.Layout.get() }); return pub.attach(html, '#columnList'); }; pub.drawColumns = function () { $('#columns .column').remove(); TT.Model.Layout.each(function (index, column) { if (column.active) { pub.drawColumn(column.name); } }); }; pub.drawColumn = function (name) { var column = TT.Model.Column.get({ name: name }); var html = pub.render('column', column); var element = pub.attachColumn(column, html); pub.drawColumnTemplate(column); return element; }; pub.attachColumn = function (column, html) { var activeColumns = TT.Model.Layout.find({ active: true }); if (activeColumns[0].name === column.name) { return pub.attach(html, '#columns', 'prependTo'); } var precedingColumn; $.each(activeColumns, function (index, activeColumn) { if (activeColumn.name === column.name) { precedingColumn = $('#columns .column[data-name="' + activeColumns[index - 1].name + '"]')[0]; } }); if (precedingColumn) { return pub.attach(html, precedingColumn, 'insertAfter'); } return pub.attach(html, '#columns'); }; pub.setColumnState = function (name, state) { TT.Model.Column.update({ name: name }, { active: state }); TT.Model.Layout.update({ name: name }, { active: state }); TT.Model.Layout.clientSave(); }; pub.addColumn = function (name) { pub.setColumnState(name, true); pub.drawColumn(name); pub.drawStoriesInColumn(TT.Model.Column.get({ name: name })); pub.afterColumnUpdate(); }; pub.removeColumn = function (name) { $('#columns .column[data-name="' + name + '"]').remove(); pub.setColumnState(name, false); pub.afterColumnUpdate(); }; pub.afterColumnUpdate = function () { pub.updateColumnDimensions(); pub.drawColumnListNav(); pub.refreshColumnStoryCount(); TT.DragAndDrop.initStorySorting(); }; pub.drawColumnTemplates = function () { $('#columns .column-template').remove(); TT.Model.Layout.each(function (index, column) { if (column.active) { var actualColumn = TT.Model.Column.get({ name: column.name }); pub.drawColumnTemplate(actualColumn); } }); }; pub.drawColumnTemplate = function (column) { if (column.template) { var html = '<div class="column-template">' + column.template() + '</div>'; var element = pub.attach(html, '#columns .' + column.class_name + ' .bucket-template'); if (column.afterTemplateRender) { column.afterTemplateRender(); } return element; } }; pub.refreshColumnStoryCount = function () { TT.Model.Column.each(function (index, column) { var $counter = $('#columnList .column-selector[data-name="' + column.name + '"] span.column-story-count'); if (column.storyCount === 0) { $counter.hide(); } else { $counter.show().html(column.storyCount); } }); }; pub.refreshLayout = function () { pub.drawColumns(); pub.drawStories(); }; pub.drawProjectList = function (projects) { $('#projects .projects').remove(); var html = pub.render('projectList', { projects: projects }); return pub.attach(html, '#projects'); }; pub.clearStories = function () { $('#columns .story').remove(); }; pub.drawStories = function () { pub.setProjectActiveState(); pub.setProjectDisabilityState(); pub.clearStories(); TT.Model.Column.each(function (index, column) { pub.drawStoriesInColumn(column); }); pub.afterColumnUpdate(); pub.drawColumnTemplates(); }; pub.drawStoriesInColumn = function (column) { column.storyCount = 0; TT.Model.Story.each(function (index, story) { if (column.filter && column.filter(story) && TT.Model.Project.isActive({ id: story.project_id }) && TT.Model.Story.isNotFiltered(story)) { column.storyCount++; if (column.active) { pub.drawStory(story, column); } } }); }; pub.setProjectActiveState = function () { var projectList = []; $('#projects .project').each(function () { var id = $(this).data('project-id'); var isActive = !$(this).hasClass('inactive'); TT.Model.Project.update({ id: id }, { active: isActive }); if (isActive) { projectList.push(id); } }); TT.Utils.localStorage('projectList', projectList); }; pub.setProjectDisabilityState = function () { var projectList = []; $('#projects .project').each(function () { var id = $(this).data('project-id'); var isDisabled = $(this).hasClass('disabled'); TT.Model.Project.update({ id: id }, { disabled: isDisabled, status: isDisabled ? 'on' : '' }); if (isDisabled) { projectList.push(id); } }); TT.Utils.localStorage('projectDisabledList', projectList); }; pub.restoreStoryState = function (element, story) { if (story.expanded) { element.toggleClass('expanded-story'); pub.drawStoryDetails(element); var state = TT.Utils.getStoryState(story.id); // TODO: clean this up if (state.description) { element.find('.description').click(); element.find('.description-container textarea').val(state.description).height(state.descriptionHeight).focus(); } if (state.note) { element.find('.add-note').click(); element.find('.notes textarea').val(state.note).height(state.noteHeight).focus(); } if (state.name) { element.find('.title').click(); element.find('.title-container textarea').val(state.name).height(state.nameHeight).focus(); } } }; pub.drawStory = function (story, column) { return pub.drawStoryHelper(story, '.' + column.class_name + ' .bucket-content'); }; pub.redrawStory = function (story) { $('#columns .story-' + story.id).each(function () { pub.drawStoryHelper(story, this, 'insertAfter'); $(this).remove(); }); pub.redrawFloatingStory(story); }; pub.redrawFloatingStory = function (story) { var container = $('.floating-story'); if (container.length > 0) { container.find('.story').remove(); TT.View.drawStoryHelper(story, container); var storyElement = container.find('.story'); storyElement.addClass('expanded-story'); TT.View.drawStoryDetails(storyElement); } }; pub.drawStoryHelper = function (story, target, insertMethod) { var label_backup = story.labels; story.labels = pub.labels_without_metadata(story.labels); var html = pub.render('story', story); story.labels = label_backup; var element = pub.attach(html, target, insertMethod); var specialLabels = ['blocked', 'orange', 'yellow', 'green', 'blue']; $.each(specialLabels, function (i, label) { if (TT.Model.Story.hasTag(story, label)) { element.addClass(TT.Utils.cssify(label)); } }); pub.restoreStoryState(element, story); return element; }; pub.labels_without_metadata = function (labels) { var output = []; $.each(labels, function (index, label) { if (!/^\[.+\=.+\]$/.test(label)) { output[output.length] = label; } }); return output; }; pub.drawStoryDetails = function (storyElement) { var story = TT.Model.Story.get({ id: storyElement.data('id') }); if (!story.formatted) { story.formatted_description = story.description ? TT.Utils.marked(story.description) : '<span class="ghost">Click to add a description</span>'; story.notes = TT.Model.Story.compileNotes(story); story.formatted = true; } TT.Event.trigger('beforeStoryDetailsRender', story); var html = pub.render('storyDetails', story); return pub.attach(html, storyElement); }; pub.drawFilter = function (filter) { var html = pub.render('filter', filter); var element = pub.attach(html, '#filters', 'prependTo'); if (filter.active === false) { element.addClass('inactive'); } return element; }; pub.drawResetDialog = function () { TT.Dialog.open(pub.render('resetDialog')); }; pub.drawAccountSettingsForm = function () { TT.Dialog.open(pub.render('accountSettings')); var id; $('#pivotal-token-input').val($.cookie('pivotalToken')).focus().bind('keyup paste', function () { var me = this; clearTimeout(id); id = setTimeout(function () { var token = $.trim($(me).val()); if (token && token !== TT.Utils.getToken()) { $(me).addClass('updating'); $.cookie('pivotalToken', token, { expires: 365 }); $.ajax({ url: '/projects', success: function (projects) { $(me).removeClass('updating'); if (projects) { $(me).addClass('valid').removeClass('invalid'); TT.Utils.localStorage('projects', projects); TT.Init.addProjects(projects); } else { $(me).addClass('invalid').removeClass('valid'); } } }); } }, 100); }); $('#pivotal-username').val($.cookie('pivotalUsername')); $('#pivotal-username').focus(TT.UI.openPivotalUsernameAutocomplete); }; pub.message = function (str, options) { options = $.extend({ type: 'info', timeout: 3000 }, options || {}); var html = pub.render('message', { str: str, type: options.type }); var element = pub.attach(html, '#messages').click(function () { $(this).fadeOut(250, function () { $(this).remove(); }); return false; }); if (options.timeout) { setTimeout(function () { element.fadeOut(1000, function () { element.remove(); }); }, options.timeout); } return element; }; return pub; }());
// Flags: --expose-internals 'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); const h2 = require('http2'); const { kSocket } = require('internal/http2/util'); const Countdown = require('../common/countdown'); { const server = h2.createServer(); server.listen(0, common.mustCall(() => { const destroyCallbacks = [ (client) => client.destroy(), (client) => client[kSocket].destroy() ]; const countdown = new Countdown(destroyCallbacks.length, () => { server.close(); }); destroyCallbacks.forEach((destroyCallback) => { const client = h2.connect(`http://localhost:${server.address().port}`); client.on('connect', common.mustCall(() => { const socket = client[kSocket]; assert(socket, 'client session has associated socket'); assert( !client.destroyed, 'client has not been destroyed before destroy is called' ); assert( !socket.destroyed, 'socket has not been destroyed before destroy is called' ); destroyCallback(client); client.on('close', common.mustCall(() => { assert(client.destroyed); })); countdown.dec(); })); }); })); } // Test destroy before client operations { const server = h2.createServer(); server.listen(0, common.mustCall(() => { const client = h2.connect(`http://localhost:${server.address().port}`); const socket = client[kSocket]; socket.on('close', common.mustCall(() => { assert(socket.destroyed); })); const req = client.request(); req.on('error', common.expectsError({ code: 'ERR_HTTP2_STREAM_CANCEL', name: 'Error', message: 'The pending stream has been canceled' })); client.destroy(); req.on('response', common.mustNotCall()); const sessionError = { name: 'Error', code: 'ERR_HTTP2_INVALID_SESSION', message: 'The session has been destroyed' }; assert.throws(() => client.setNextStreamID(), sessionError); assert.throws(() => client.ping(), sessionError); assert.throws(() => client.settings({}), sessionError); assert.throws(() => client.goaway(), sessionError); assert.throws(() => client.request(), sessionError); client.close(); // Should be a non-op at this point // Wait for setImmediate call from destroy() to complete // so that state.destroyed is set to true setImmediate(() => { assert.throws(() => client.setNextStreamID(), sessionError); assert.throws(() => client.ping(), sessionError); assert.throws(() => client.settings({}), sessionError); assert.throws(() => client.goaway(), sessionError); assert.throws(() => client.request(), sessionError); client.close(); // Should be a non-op at this point }); req.resume(); req.on('end', common.mustNotCall()); req.on('close', common.mustCall(() => server.close())); })); } // Test destroy before goaway { const server = h2.createServer(); server.on('stream', common.mustCall((stream) => { stream.session.destroy(); })); server.listen(0, common.mustCall(() => { const client = h2.connect(`http://localhost:${server.address().port}`); client.on('close', () => { server.close(); // Calling destroy in here should not matter client.destroy(); }); client.request(); })); } // Test destroy before connect { const server = h2.createServer(); server.on('stream', common.mustNotCall()); server.listen(0, common.mustCall(() => { const client = h2.connect(`http://localhost:${server.address().port}`); server.on('connection', common.mustCall(() => { server.close(); client.close(); })); const req = client.request(); req.destroy(); })); } // Test close before connect { const server = h2.createServer(); server.on('stream', common.mustNotCall()); server.listen(0, common.mustCall(() => { const client = h2.connect(`http://localhost:${server.address().port}`); client.on('close', common.mustCall()); const socket = client[kSocket]; socket.on('close', common.mustCall(() => { assert(socket.destroyed); })); const req = client.request(); // Should throw goaway error req.on('error', common.expectsError({ code: 'ERR_HTTP2_GOAWAY_SESSION', name: 'Error', message: 'New streams cannot be created after receiving a GOAWAY' })); client.close(); req.resume(); req.on('end', common.mustCall()); req.on('close', common.mustCall(() => server.close())); })); }
/** * * AutoReloadOverlayBlocker * * */ import { createContext } from 'react'; const AutoReloadOverlayBlocker = createContext(); export default AutoReloadOverlayBlocker;
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var inherits = require('util').inherits; var errors = require('tchannel/errors'); var EventEmitter = require('tchannel/lib/event_emitter'); var states = require('./states.js'); var StateMachine = require('./state_machine.js'); // Each circuit uses the circuits collection as the "nextHandler" for // "shouldRequest" to consult. Peers use this hook to weight peers both by // healthy and other factors, but the circuit only needs to know about health // before forwarding. function AlwaysShouldRequestHandler() { } AlwaysShouldRequestHandler.prototype.shouldRequest = function shouldRequest() { return true; }; var alwaysShouldRequestHandler = new AlwaysShouldRequestHandler(); function CircuitStateChange(circuit, oldState, state) { var self = this; self.circuit = circuit; self.oldState = oldState; self.state = state; } // circuit = circuits : Circuits // .circuitsByServiceName[serviceName] : ServiceCircuits // .circuitsByCallerName[callerName] : EndpointCircuits // .circuitsByEndpointName[endpointName] function EndpointCircuits(root) { var self = this; self.root = root; self.circuitsByEndpointName = {}; } EndpointCircuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) { var self = this; var circuit = self.circuitsByEndpointName['$' + endpointName]; if (!circuit) { circuit = new Circuit(callerName, serviceName, endpointName); circuit.stateOptions = new states.StateOptions(circuit, self.root.stateOptions); circuit.stateChangedEvent.on(function circuitStateChanged(newStates) { self.root.emitCircuitStateChange(circuit, newStates); }); circuit.setState(states.HealthyState); self.circuitsByEndpointName['$' + endpointName] = circuit; } return circuit; }; EndpointCircuits.prototype.collectCircuitTuples = function collectCircuitTuples(tuples) { var self = this; var endpointNames = Object.keys(self.circuitsByEndpointName); for (var index = 0; index < endpointNames.length; index++) { var endpointName = endpointNames[index]; var circuit = self.circuitsByEndpointName[endpointName]; tuples.push([circuit.callerName, circuit.serviceName, circuit.endpointName]); } }; function ServiceCircuits(root) { var self = this; self.root = root; self.circuitsByCallerName = {}; } ServiceCircuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) { var self = this; var circuits = self.circuitsByCallerName['$' + callerName]; if (!circuits) { circuits = new EndpointCircuits(self.root); self.circuitsByCallerName['$' + callerName] = circuits; } return circuits.getCircuit(callerName, serviceName, endpointName); }; ServiceCircuits.prototype.collectCircuitTuples = function collectCircuitTuples(tuples) { var self = this; var callerNames = Object.keys(self.circuitsByCallerName); for (var index = 0; index < callerNames.length; index++) { var callerName = callerNames[index]; var circuit = self.circuitsByCallerName[callerName]; circuit.collectCircuitTuples(tuples); } }; function Circuits(options) { var self = this; EventEmitter.call(self); self.circuitStateChangeEvent = self.defineEvent('circuitStateChange'); self.circuitsByServiceName = {}; self.config = options.config || {}; self.stateOptions = new states.StateOptions(null, { timeHeap: options.timeHeap, timers: options.timers, random: options.random, nextHandler: alwaysShouldRequestHandler, period: self.config.period, maxErrorRate: self.config.maxErrorRate, minRequests: self.config.minRequests, probation: self.config.probation }); self.egressNodes = options.egressNodes; } inherits(Circuits, EventEmitter); Circuits.prototype.getCircuit = function getCircuit(callerName, serviceName, endpointName) { var self = this; var circuits = self.circuitsByServiceName['$' + serviceName]; if (!circuits) { circuits = new ServiceCircuits(self); self.circuitsByServiceName['$' + serviceName] = circuits; } return circuits.getCircuit(callerName, serviceName, endpointName); }; Circuits.prototype.getCircuitTuples = function getCircuitTuples() { var self = this; var tuples = []; var serviceNames = Object.keys(self.circuitsByServiceName); for (var index = 0; index < serviceNames.length; index++) { var serviceName = serviceNames[index]; self.circuitsByServiceName[serviceName].collectCircuitTuples(tuples); } return tuples; }; Circuits.prototype.monitorRequest = function monitorRequest(req, buildRes) { var self = this; // Default the caller name. // All callers that fail to specifiy a cn share a circuit for each sn:en // and fail together. var callerName = req.headers.cn || 'no-cn'; var serviceName = req.serviceName; if (!serviceName) { buildRes().sendError('BadRequest', 'All requests must have a service name'); return null; } var arg1 = String(req.arg1); var circuit = self.getCircuit(callerName, serviceName, arg1); if (!circuit.state.shouldRequest()) { buildRes().sendError('Declined', 'Service is not healthy'); return null; } return circuit.monitorRequest(req, buildRes); }; // Called upon membership change to collect services that the corresponding // exit node is no longer responsible for. Circuits.prototype.updateServices = function updateServices() { var self = this; var serviceNames = Object.keys(self.circuitsByServiceName); for (var index = 0; index < serviceNames.length; index++) { var serviceName = serviceNames[index]; if (!self.egressNodes.isExitFor(serviceName)) { delete self.circuitsByServiceName[serviceName]; } } }; Circuits.prototype.emitCircuitStateChange = function emitCircuitStateChange(circuit, newStates) { var self = this; self.circuitStateChangeEvent.emit( self.root, new CircuitStateChange(circuit, newStates[0], newStates[1]) ); }; function Circuit(callerName, serviceName, endpointName) { var self = this; EventEmitter.call(self); StateMachine.call(self); self.stateChangedEvent = self.defineEvent('stateChanged'); self.callerName = callerName || 'no-cn'; self.serviceName = serviceName; self.endpointName = endpointName; self.stateOptions = null; } inherits(Circuit, EventEmitter); Circuit.prototype.setState = StateMachine.prototype.setState; Circuit.prototype.monitorRequest = function monitorRequest(req, buildRes) { var self = this; self.state.onRequest(req); req.errorEvent.on(onError); function monitorBuildRes(options) { var res = buildRes(options); self.monitorResponse(res); return res; } function onError(err) { self.state.onRequestError(err); } return monitorBuildRes; }; Circuit.prototype.monitorResponse = function monitorResponse(res) { var self = this; res.errorEvent.on(onError); res.finishEvent.on(onFinish); function onError(err) { self.state.onRequestError(err); } function onFinish() { // TODO distingiush res.ok? // note that incoming requests do not have responseEvent and clear out // their response upon finish. if (errors.isUnhealthy(res.codeString)) { self.state.onRequestUnhealthy(); } else { self.state.onRequestHealthy(); } } }; Circuit.prototype.extendLogInfo = function extendLogInfo(info) { var self = this; info.callerName = self.callerName; info.serviceName = self.serviceName; info.endpointName = self.endpointName; return info; }; module.exports = Circuits;
/** * @fileoverview * Shuffl card plug-in for a card graphing tabular data. * * This plugin is initially based on the shuffl-card-datatable plugin, except * that the display area is rendered using 'flot' rather than as an HTML table. * * @author Graham Klyne * @version $Id: shuffl-card-datagraph.js 828 2010-06-14 15:26:11Z [email protected] $ * * Coypyright (C) 2009, University of Oxford * * Licensed under the MIT License. You may obtain a copy of the License at: * * http://www.opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ---------------------------------------------------------------- // Globals and data // ---------------------------------------------------------------- /** * Check shuffl namespace */ if (typeof shuffl == "undefined") { alert("shuffl-card-datagraph.js: shuffl-base.js must be loaded first"); } if (typeof shuffl.card == "undefined") { alert("shuffl-card-datagraph.js: shuffl-cardhandlers.js must be loaded before this"); } /** * Create namespace for this card type */ shuffl.card.datagraph = {}; /** * Template for initializing a card model, and * creating new card object for serialization. */ shuffl.card.datagraph.datamap = { 'shuffl:title': { def: '@id' } , 'shuffl:tags': { def: '@tags', type: 'array' } , 'shuffl:source_id': { def: undefined } , 'shuffl:labels': { def: undefined } , 'shuffl:axes': { def: undefined } , 'shuffl:series': { def: undefined } , 'shuffl:dataminy': { def: undefined } , 'shuffl:datamaxy': { def: undefined } , 'shuffl:x1axis': { def: 'lin' } , 'shuffl:y1axis': { def: 'lin' } , 'shuffl:y2axis': { def: 'lin' } }; /* * Default data... */ shuffl.card.datagraph.table = [ [] ]; /** * jQuery base element for building new cards (used by shuffl.makeCard) */ shuffl.card.datagraph.blank = jQuery( "<div class='shuffl-card-setsize' style='z-index:10;'>\n"+ " <chead>\n"+ " <chandle><c></c></chandle>" + " <ctitle>card title</ctitle>\n"+ " </chead>\n"+ " <crow>\n"+ " <cbody>\n"+ " <div style='width:98%; height:98%;'/>\n"+ " </cbody>\n"+ " </crow>\n"+ " <crow style='width: 100%; white-space: nowrap;'>\n"+ " <span style='display: inline-block; width: 14%;'>x1: <cx1axis/></span>\n"+ " <span style='display: inline-block; width: 14%;'>y1: <cy1axis/></span>\n"+ " <span style='display: inline-block; width: 14%;'>y2: <cy2axis/></span>\n"+ " <span style='display: inline-block; width: 25%;'>min Y: <cdataminy style='display: inline-block;'>-1.0</cdataminy></span>\n"+ " <span style='display: inline-block; width: 25%;'>max Y: <cdatamaxy style='display: inline-block;'> 1.0</cdatamaxy></span>\n"+ " </crow>\n"+ " <cfoot>\n"+ " <cident>card_ZZZ_ident</cident>:<cclass>card_ZZZ class</cclass>\n"+ " (<ctags>card_ZZZ tags</ctags>)\n"+ " </cfoot>"+ "</div>"); /** * Creates and return a new card instance. * * @param cardtype type identifier for the new card element * @param cardcss CSS class name(s) for the new card element * @param cardid local card identifier - a local name for the card, * which may be combined with a base URI to form a URI * for the card. * @param carddata an object or string containing additional data used in * constructing the body of the card. This is either a * string or an object structure with fields * 'shuffl:title', 'shuffl:tags', 'shuffl:labels', etc. * @return a jQuery object representing the new card. */ shuffl.card.datagraph.newCard = function (cardtype, cardcss, cardid, carddata) { ////log.debug("shuffl.card.datagraph.newCard: "+cardtype+", "+cardcss+", "+cardid); ////log.debug("- data: "+jQuery.toJSON(carddata)); // Initialize the card object var card = shuffl.card.datagraph.blank.clone(); card.data('shuffl:type' , cardtype); card.data('shuffl:id', cardid); card.data("shuffl:tojson", shuffl.card.datagraph.serialize); card.attr('id', cardid); card.addClass(cardcss); card.find("cident").text(cardid); // Set card id text card.find("cclass").text(cardtype); // Set card class/type text card.data("resizeAlso", "cbody"); card.resizable(); // Set up function to (re)draw the card when placed or resized var redraw = shuffl.card.datagraph.redraw(card); card.data("redrawFunc", redraw); // Set up card as drop-target for data table shuffl.dropTarget(card, '.shuffl-series', 'shuffl:source'); // Set up model listener and user input handlers shuffl.bindLineEditable(card, "shuffl:title", "ctitle"); shuffl.bindLineEditable(card, "shuffl:tags", "ctags"); shuffl.bindOptionClickCycle( card, "shuffl:x1axis", "cx1axis", ["lin", "log"], redraw); shuffl.bindOptionClickCycle( card, "shuffl:y1axis", "cy1axis", ["lin", "log"], redraw); shuffl.bindOptionClickCycle( card, "shuffl:y2axis", "cy2axis", ["lin", "log"], redraw); shuffl.bindFloatEditable( card, "shuffl:dataminy", "cdataminy", 2, redraw); shuffl.bindFloatEditable( card, "shuffl:datamaxy", "cdatamaxy", 2, redraw); card.modelBind("shuffl:labels", redraw); card.modelBind("shuffl:axes", redraw); card.modelBind("shuffl:series", shuffl.card.datagraph.setseriesdata(card)); card.modelBind("shuffl:table", shuffl.card.datagraph.setgraphdata(card)); // Handle source drop, including subscription to changes in the source data card.modelBind("shuffl:source", function (_event, data) { var oldsub = card.data("updatesubs"); if (oldsub) { var oldsrc = data.oldval; oldsrc.modelUnbind("shuffl:title", oldsub); oldsrc.modelUnbind("shuffl:labels", oldsub); oldsrc.modelUnbind("shuffl:axes", oldsub); oldsrc.modelUnbind("shuffl:series", oldsub); }; var src = data.newval; var newsub = shuffl.card.datagraph.updatedata(card, src); newsub(); src.modelBind("shuffl:title", newsub); src.modelBind("shuffl:labels", newsub); src.modelBind("shuffl:axes", newsub); src.modelBind("shuffl:series", newsub); card.data("updatesubs", newsub); card.data("shuffl:source_id", src.data('shuffl:id')); }); // Initialize the model shuffl.initModel(card, carddata, shuffl.card.datagraph.datamap, {id: cardid, tags: [cardtype]} ); // If card is linked, complete setting link when all cards have been loaded // (shuffl.LoadWorkspace triggers an event when all cards have been loaded) var cardsrcid = card.model('shuffl:source_id'); if (cardsrcid) { card.one("shuffl:AllCardsLoaded", function () { var src = jQuery(document.getElementById(cardsrcid)); if (src.length == 1) { card.model("shuffl:source", src.eq(0)); }; }); }; if (!card.model('shuffl:series')) { card.model("shuffl:table", shuffl.card.datagraph.table); }; return card; }; /** * Returns a function to set graphing data from an assigned table, where the * first row of the table is graph labels, the first column contains X-values, * and the remaining columns contain Y-values for each graph. */ shuffl.card.datagraph.setgraphdata = function (card) { function setgraphvalues(_event, data) { ////log.debug("- data "+jQuery.toJSON(data)); card.data("shuffl:table", null); shuffl.modelSetSeries(card)(_event, data); }; return setgraphvalues; }; /** * Returns a function to handle new graph data assigned to a series, which * is an array, each element of which is a list of [x,y] pairs. * * Minimum and maximum Y values are recalculated, and a redraw is scheduled. */ shuffl.card.datagraph.setseriesdata = function (card) { function setseriesvalues(_event, data) { var series = data.newval; if (series && series.length) { ////log.debug("- series "+jQuery.toJSON(series)); var ymin = series[0][0][1]; var ymax = series[0][0][1]; ////log.debug("- ymin "+ymin+", ymax "+ymax); for (var i = 0 ; i < series.length ; i++) { var graph = series[i]; for (var j = 0 ; j < graph.length ; j++) { var y = graph[j][1]; if (isFinite(y)) { ymin = Math.min(ymin, y); ymax = Math.max(ymax, graph[j][1]); }; }; }; ////log.debug("- ymin "+ymin+", ymax "+ymax); card.model("shuffl:dataminy", ymin); card.model("shuffl:datamaxy", ymax); shuffl.card.datagraph.redraw(card)(); }; }; return setseriesvalues; }; /** * Return function to update graph data from the supplied drop source */ shuffl.card.datagraph.updatedata = function (card, src) { function update(_event, _data) { var srctitle = src.model("shuffl:title"); if (srctitle) { var title = card.model("shuffl:title").replace(/ \([^)]+\)$/,""); card.model("shuffl:title", title+" ("+src.model("shuffl:title")+")"); } card.data("shuffl:labels", src.model("shuffl:labels")); card.data("shuffl:axes", src.model("shuffl:axes")); card.model("shuffl:series", src.model("shuffl:series")); }; return update; }; /** * Return function to redraw the graph in a supplied datagraph card * following an update to the card model. */ shuffl.card.datagraph.redraw = function (card) { function drawgraph(_event, _data) { // Redraw after 50ms shuffl.redrawAfter(card, shuffl.card.datagraph.draw, 50.0); card.data('shuffl:datamod', true); }; return drawgraph; }; /** * Variable transform Log10 */ shuffl.card.datagraph.log10transform = { transform: function (x) { if (typeof x != "number" || x<=0.0) { return null; }; return Math.LOG10E*Math.log(x); } , inverseTransform: function (x) { return Math.exp(x/Math.LOG10E); } }; /** * Log10 transform tick generator */ shuffl.card.datagraph.log10tickgenerator = function (axis) { function label(log) { return (log == 0 ? "1" : (log > 0 ? "1E+"+log : "1E"+log)); }; var log10 = shuffl.card.datagraph.log10transform; var minlog = Math.floor(log10.transform(axis.min)+1.0E-8 || -10); var maxlog = Math.ceil(log10.transform(axis.max)-1.0E-8 || 0); var ticks = []; for (var l = minlog ; l < maxlog ; l++) { var t = log10.inverseTransform(l); ticks.push([t,label(l)]); for (var f = 2.0 ; f <= 8.0 ; f += 2.0) ticks.push([t*f,""]); }; ticks.push([log10.inverseTransform(maxlog),label(maxlog)]); return ticks; }; /** * Function to draw the graph in a supplied datagraph card */ shuffl.card.datagraph.draw = function (card) { var ymin = card.model('shuffl:dataminy'); var ymax = card.model('shuffl:datamaxy'); var x1axis = card.model('shuffl:x1axis'); var y1axis = card.model('shuffl:y1axis'); var y2axis = card.model('shuffl:y2axis'); var labels = card.model('shuffl:labels'); var axes = card.model('shuffl:axes'); var series = card.model('shuffl:series'); var cbody = card.find("cbody"); var gelem = cbody.find("div"); ////log.debug("shuffl.card.datagraph.draw "+cbody.width()+", "+cbody.height()); ////log.debug("shuffl.card.datagraph.draw "+gelem.width()+", "+gelem.height()); if (labels && series && gelem.width() && gelem.height()) { ////log.debug("- plot graphs "+ymin+", "+ymax); var data = []; for (var i = 0 ; i < labels.length ; i++) { var yaxis = ( axes[i][1] == 'y2' ? 2 : 1 ); data.push( { data: series[i] , label: labels[i] , xaxis: 1 , yaxis: yaxis }); } var options = { series: { lines: { show: true } , points: { show: false, fill: false } } , xaxis: { labelWidth: 40 } , yaxis: {} , y2axis: {} }; if (isFinite(ymin) && isFinite(ymax) && (ymin<ymax)) { options.yaxis = { min: ymin, max: ymax }; } if (x1axis == 'log') { jQuery.extend(options.xaxis, shuffl.card.datagraph.log10transform); options.xaxis.ticks = shuffl.card.datagraph.log10tickgenerator; } if (y1axis == 'log') { jQuery.extend(options.yaxis, shuffl.card.datagraph.log10transform); options.yaxis.ticks = shuffl.card.datagraph.log10tickgenerator; } if (y2axis == 'log') { jQuery.extend(options.y2axis, shuffl.card.datagraph.log10transform); options.y2axis.ticks = shuffl.card.datagraph.log10tickgenerator; } var plot = jQuery.plot(gelem, data, options); }; }; /** * Serializes a tabular data card to JSON for storage * * @param card a jQuery object corresponding to the card * @return an object containing the card data */ shuffl.card.datagraph.serialize = function (card) { return shuffl.serializeModel(card, shuffl.card.datagraph.datamap); }; /** * Add new card type factories */ shuffl.addCardFactory("shuffl-datagraph-yellow", "stock-yellow", shuffl.card.datagraph.newCard); shuffl.addCardFactory("shuffl-datagraph-blue", "stock-blue", shuffl.card.datagraph.newCard); shuffl.addCardFactory("shuffl-datagraph-green", "stock-green", shuffl.card.datagraph.newCard); shuffl.addCardFactory("shuffl-datagraph-orange", "stock-orange", shuffl.card.datagraph.newCard); shuffl.addCardFactory("shuffl-datagraph-pink", "stock-pink", shuffl.card.datagraph.newCard); shuffl.addCardFactory("shuffl-datagraph-purple", "stock-purple", shuffl.card.datagraph.newCard); // End.
'use strict'; var test = require('../../'); test('first', function (t) { t.plan(1); t.ok(true); }); test('second', function (t) { t.plan(2); t.ok(true); });
var UserList = React.createClass({displayName: 'UserList', getInitialState: function() { return {data: []}; }, componentDidMount: function() { $.ajax({ url: this.props.url, dataType: 'json', success: function(data) { this.setState({ data: data }); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, handleListItemClicked: function(user_id){ var user = _.find(this.state.data, {user_id: user_id}) this.refs.userView.setState({user:user}) }, render: function() { var self = this var users = this.state.data.map(function (user) { return ( <UserListItem user={user} onListItemClicked={self.handleListItemClicked}/> ) }) return ( <div className="userPage"> <div className="userList six columns"> {users} </div> <div className="userView six columns"> <UserView ref="userView"/> </div> </div> ) } })
export { default } from './ProtectedRoute';
import curry from './curry' export default curry(_drop) /** * Remove the first n elements from a list. * * @arg n {Number} The number of elements to remove. * @arg list {Array} The list to remove the elements from. */ function _drop (n, list) { return list.slice(n) }
/*global define*/ 'use strict'; // Dependecies define([ 'jquery', 'jquery-ui', 'pubsub', 'underscore' ], function( jQuery, jQuery_ui, PubSub, _ ) { /* This modules changes every UI input/button/element. Every action triggered by the other modules, it actually takes place in here. * TO AVOID INFITE LOOPING, INPUTS CHANGE SLIDERS FROM THIS MODULE, BUT SLIDERS SHOULD CHANGE INPUTS LOCALLY FROM, THEIR HANDLER. * TO SUM UP, IN ORDER FOR THE SYSTEM TO MOVE A SLIDER, IT HAS TO CHANGE THE INPUT FROM THIS MODULE. * To dogde another inifite loop, we're using the allowPublish variable. If we run into a condition we cannot pass during the 'taking action' part, then we're blocking the publishing of this event. */ // Variables var $selector = undefined; var allowPublish = false; // Modules References var $messages = undefined; var $tooltipGenerator = undefined; var $stringEditor = undefined; var $menu = undefined; var html = undefined; var events = undefined; // Contructor // function setUIValue(argument) { // Acquire Module References // if (!(_.isUndefined(argument.messages))) $messages = argument.messages; else return false; if (!(_.isUndefined(argument.stringEditor))) $stringEditor = argument.stringEditor; else return false; if (!(_.isUndefined(argument.tooltipGenerator))) $tooltipGenerator = argument.tooltipGenerator; else return false; if (!(_.isUndefined(argument.menu))) $menu = argument.menu; else return false; if (!(_.isUndefined(argument.html))) html = argument.html; else return false; // Get Event List from Menu // events = $menu.events; }; // Sets UI Value - Selector is optional // function takeAction(index,value,selector){ // If setting a new value fails, block publish // var success = true; switch(index){ // Menu Ribbon case 'xyzAxes':{ if (value === true) html.menu.toggles.xyzAxes.parent().addClass('lightThemeActive'); else html.menu.toggles.xyzAxes.parent().removeClass('lightThemeActive'); $menu.showCanvasXYZLabels(value); break; } case 'abcAxes':{ if (value === true) html.menu.toggles.abcAxes.parent().addClass('lightThemeActive'); else html.menu.toggles.abcAxes.parent().removeClass('lightThemeActive'); $menu.showCanvasABCLabels(value); break; } case 'edges':{ if (value === true) { html.lattice.visual.edgeCheckbox.iCheck('check'); html.menu.toggles.edges.parent().addClass('lightThemeActive'); } else { html.lattice.visual.edgeCheckbox.iCheck('uncheck'); html.menu.toggles.edges.parent().removeClass('lightThemeActive'); } break; } case 'faces':{ if (value === true) { html.lattice.visual.faceCheckbox.iCheck('check'); html.menu.toggles.faces.parent().addClass('lightThemeActive'); } else { html.lattice.visual.faceCheckbox.iCheck('uncheck'); html.menu.toggles.faces.parent().removeClass('lightThemeActive'); } break; } case 'latticePoints':{ if (value === true) html.menu.toggles.latticePoints.parent().addClass('lightThemeActive'); else html.menu.toggles.latticePoints.parent().removeClass('lightThemeActive'); break; } case 'planes':{ if (value === true) { html.pnd.tables.planes.find('.planeButton').find('img').attr('src','Images/hidden-icon-sm.png'); html.menu.toggles.planes.parent().addClass('lightThemeActive'); } else { html.pnd.tables.planes.find('.planeButton').find('img').attr('src','Images/visible-icon-sm.png'); html.menu.toggles.planes.parent().removeClass('lightThemeActive'); } publishAction('planes',value); break; } case 'directions':{ if (value === true) { html.pnd.tables.directions.find('.directionButton').find('img').attr('src','Images/hidden-icon-sm.png'); html.menu.toggles.directions.parent().addClass('lightThemeActive'); } else { html.pnd.tables.directions.find('.directionButton').find('img').attr('src','Images/visible-icon-sm.png'); html.menu.toggles.directions.parent().removeClass('lightThemeActive'); } publishAction('directions',value); break; } case 'atomToggle':{ if (value === true) html.menu.toggles.atomToggle.parent().addClass('lightThemeActive'); else html.menu.toggles.atomToggle.parent().removeClass('lightThemeActive'); break; } case 'atomRadius':{ if (value === true) { html.menu.other.atomRadiusSliderContainer.show('slow'); html.menu.toggles.atomRadius.parent().addClass('lightThemeActive'); } else { html.menu.other.atomRadiusSliderContainer.hide('slow'); html.menu.toggles.atomRadius.parent().removeClass('lightThemeActive'); } break; } case 'unitCellViewport':{ if (value === true) html.menu.toggles.unitCellViewport.parent().addClass('lightThemeActive'); else html.menu.toggles.unitCellViewport.parent().removeClass('lightThemeActive'); $menu.viewport(value); break; } case 'labelToggle':{ if (value === true) html.menu.toggles.labelToggle.parent().addClass('lightThemeActive'); else html.menu.toggles.labelToggle.parent().removeClass('lightThemeActive'); break; } case 'highlightTangency':{ if (value === true) html.menu.toggles.highlightTangency.parent().addClass('lightThemeActive'); else html.menu.toggles.highlightTangency.parent().removeClass('lightThemeActive'); break; } case 'atomRadiusSlider':{ html.menu.other.atomRadiusSlider.slider('value',value); break; } case 'fullScreen':{ if (value === true) html.menu.toggles.fullScreen.parent().addClass('lightThemeActive'); else html.menu.toggles.fullScreen.parent().removeClass('lightThemeActive'); break; } // Lattice Tab case 'latticePadlock':{ if (value === true) { if (!(html.lattice.padlocks.lattice.children().addClass('active'))) html.lattice.padlocks.lattice.find('a').button('toggle'); html.lattice.padlocks.lattice.children().addClass('active'); } else { if (html.lattice.padlocks.lattice.children().addClass('active')) html.lattice.padlocks.lattice.find('a').button('toggle'); html.lattice.padlocks.lattice.children().removeClass('active'); } break; } case 'motifPadlock':{ if (value === true) { if (!(html.lattice.padlocks.motif.children().addClass('active'))) html.lattice.padlocks.motif.find('a').button('toggle'); html.lattice.padlocks.motif.children().addClass('active'); } else { if (html.lattice.padlocks.motif.children().addClass('active')) html.lattice.padlocks.motif.find('a').button('toggle'); html.lattice.padlocks.motif.children().removeClass('active'); } break; } case 'selectedLattice':{ html.lattice.other.selected.html(value); break; } case 'gridCheckButton':{ if (value === true) html.lattice.visual.edgeCheckbox.addClass('active'); else html.lattice.visual.edgeCheckbox.removeClass('active'); takeAction('edges',value); break; } case 'faceCheckButton':{ if (value === true) html.lattice.visual.faceCheckbox.addClass('active'); else html.lattice.visual.faceCheckbox.removeClass('active'); takeAction('faces',value); break; } case 'cylinderColor':{ html.lattice.visual.edgeColorPicker.children().css('background','#'+value); break; } case 'cellEdgeColor':{ html.lattice.visual.edgeColorPicker.spectrum('set',value); html.lattice.visual.edgeColorPicker.children().css('background',value); break; } case 'cellFaceColor':{ html.lattice.visual.faceColorPicker.spectrum('set',value); html.lattice.visual.faceColorPicker.children().css('background',value); break; } case 'faceColor':{ html.lattice.visual.faceColorPicker.children().css('background','#'+value); break; } case 'repeatX':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.lattice.parameters.repeatX.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.lattice.parameters.repeatX.val(''); success = false; } break; } case 'repeatY':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.lattice.parameters.repeatY.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.lattice.parameters.repeatY.val(''); success = false; } break; } case 'repeatZ':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.lattice.parameters.repeatZ.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.lattice.parameters.repeatZ.val(''); success = false; } break; } case 'radius':{ var newVal = $stringEditor.inputIsInteger(value); if (newVal !== false) { takeAction('radiusSlider',newVal); html.lattice.visual.radius.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.lattice.visual.radius.val(''); success = false; } break; } case 'radiusSlider':{ html.lattice.visual.radiusSlider.slider('value',value); break; } case 'faceOpacity':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) { takeAction('faceOpacitySlider',newVal); html.lattice.visual.opacity.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.lattice.visual.opacity.val(''); success = false; } break; } case 'faceOpacitySlider':{ html.lattice.visual.opacitySlider.slider('value',value); break; } case 'alpha':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('alphaSlider',newVal); html.lattice.parameters.alpha.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.lattice.parameters.alpha.val(''); success = false; } break; } case 'alphaSlider':{ html.lattice.sliders.alpha.slider('value',value); break; } case 'beta':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('betaSlider',newVal); html.lattice.parameters.beta.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.lattice.parameters.beta.val(''); success = false; } break; } case 'betaSlider':{ html.lattice.sliders.beta.slider('value',value); break; } case 'gamma':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('gammaSlider',newVal); html.lattice.parameters.gamma.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.lattice.parameters.gamma.val(''); success = false; } break; } case 'gammaSlider':{ html.lattice.sliders.gamma.slider('value',value); break; } case 'scaleX':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('scaleXSlider',newVal); html.lattice.parameters.scaleX.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.lattice.parameters.scaleX.val(''); success = false; } break; } case 'scaleXMotif':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('scaleXSlider',newVal); selector.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': 'scaleX', 'placement': 'top', 'message': $messages.getMessage(20) }); selector.val(''); success = false; } break; } // Requires Selector // case 'scaleXSlider':{ html.lattice.sliders.scaleX.slider('value',value); break; } case 'scaleY':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('scaleYSlider',newVal); html.lattice.parameters.scaleY.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.lattice.parameters.scaleY.val(''); success = false; } break; } case 'scaleYMotif':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('scaleYSlider',newVal); selector.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': 'scaleY', 'placement': 'top', 'message': $messages.getMessage(20) }); selector.val(''); success = false; } break; } // Requires Selector // case 'scaleYSlider':{ html.lattice.sliders.scaleY.slider('value',value.toString()); break; } case 'scaleZ':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('scaleZSlider',newVal); html.lattice.parameters.scaleZ.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.lattice.parameters.scaleZ.val(''); success = false; } break; } case 'scaleZMotif':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { takeAction('scaleZSlider',newVal); selector.val(newVal); } else { $tooltipGenerator.showTooltip({ 'target': 'scaleZ', 'placement': 'top', 'message': $messages.getMessage(20) }); selector.val(''); success = false; } break; } // Requires Selector // case 'scaleZSlider':{ html.lattice.sliders.scaleZ.slider('value',value); break; } // PnD Tab case 'planeColor':{ html.pnd.planeParameters.planeColor.spectrum('set',value); html.pnd.planeParameters.planeColor.children().css('background',value); break; } case 'planeOpacity':{ html.pnd.planeParameters.planeOpacity.selectpicker('val',value); break; } case 'planeName':{ html.pnd.planeParameters.planeName.val(value); break; } case 'millerH':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.planeParameters.millerH.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.planeParameters.millerH.val(''); success = false; } break; } case 'millerK':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.planeParameters.millerK.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.planeParameters.millerK.val(''); success = false; } break; } case 'millerL':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.planeParameters.millerL.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.planeParameters.millerL.val(''); success = false; } break; } case 'millerI':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.planeParameters.millerI.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.planeParameters.millerI.val(''); success = false; } break; } case 'directionColor':{ html.pnd.directionParameters.directionColor.spectrum('set',value); html.pnd.directionParameters.directionColor.children().css('background',value); break; } case 'dirRadius':{ html.pnd.directionParameters.dirRadius.selectpicker('val',value); break; } case 'directionName':{ html.pnd.directionParameters.directionName.val(value); break; } case 'millerU':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.directionParameters.millerU.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.directionParameters.millerU.val(''); success = false; } break; } case 'millerV':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.directionParameters.millerV.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.directionParameters.millerV.val(''); success = false; } break; } case 'millerW':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.directionParameters.millerW.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.directionParameters.millerW.val(''); success = false; } break; } case 'millerT':{ var newVal = $stringEditor.inputIsInteger(value.toString()); if (newVal !== false) html.pnd.directionParameters.millerT.val(newVal); else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(19) }); html.pnd.directionParameters.millerT.val(''); success = false; } break; } case 'planeVisibility':{ if (value === false) { selector.find('.planeButton').find('img').attr('src','Images/hidden-icon-sm.png'); selector.find('.planeButton').removeClass('visible'); } else { selector.find('.planeButton').find('img').attr('src','Images/visible-icon-sm.png'); selector.find('.planeButton').addClass('visible'); } break; } // Requires Selector // case 'planeParallel':{ if (value === false) selector.find('.parallel').removeClass('active'); else selector.find('.parallel').addClass('active'); break; } // Requires Selector // case 'planeInterception':{ if (value === false) selector.find('.interception').removeClass('active'); else selector.find('.interception').addClass('active'); break; } // Requires Selector // case 'directionVisibility':{ if (value === false) { selector.find('.directionButton').find('img').attr('src','Images/hidden-icon-sm.png'); selector.find('.directionButton').removeClass('visible'); } else { selector.find('.directionButton').find('img').attr('src','Images/visible-icon-sm.png'); selector.find('.directionButton').addClass('visible'); } break; } // Requires Selector // // Motif Tab case 'atomName':{ if (value.atomName === '-') html.motif.other.nameContainer.hide('slow'); else { var newAtom = 'ch-' + value.atonName; var newAtomName = $stringEditor.capitalizeFirstLetter(value.atomName); html.motif.other.nameContainer.find('a').attr('class','ch'); if (value.ionicIndex !== '0' && value.ionicIndex !== '3b') html.motif.other.nameContainer.find('a').html('<span style="font-size:17px;">'+newAtomName+'<sup>'+value.ionicIndex+'</sup></span>'); else html.motif.other.nameContainer.find('a').html(newAtomName); html.motif.other.nameContainer.find('a').css('background',value.atomColor); html.motif.other.nameContainer.show('slow'); } break; } case 'elementContainer':{ html.motif.other.nameContainer.find('a').removeAttr('class'); html.motif.other.nameContainer.find('a').attr('class',selector.attr('class')); if ( value !== '0' && (value !== '3b')) html.motif.other.nameContainer.find('a').html('<span style="font-size:17px;">'+selector.html()+'<sup>'+value+'</sup></span>'); else html.motif.other.nameContainer.find('a').html(selector.html()); html.motif.other.nameContainer.show('slow'); break; } // Requires Selectors // case 'atomPosX':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { html.motif.motifInputs.atomPosX.val(newVal); takeAction('atomPosXSlider',value); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.motif.motifInputs.atomPosX.val(''); success = false; } break; } case 'atomPosXSlider':{ html.motif.motifInputsSliders.atomPosX.slider('value',value); break; } case 'atomPosY':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { html.motif.motifInputs.atomPosY.val(newVal); takeAction('atomPosYSlider',value); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.motif.motifInputs.atomPosY.val(''); success = false; } break; } case 'atomPosYSlider':{ html.motif.motifInputsSliders.atomPosY.slider('value',value); break; } case 'atomPosZ':{ var newVal = $stringEditor.inputIsNumber(value.toString()); if (newVal !== false) { html.motif.motifInputs.atomPosZ.val(newVal); takeAction('atomPosZSlider',value); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(20) }); html.motif.motifInputs.atomPosZ.val(''); success = false; } break; } case 'atomPosZSlider':{ html.motif.motifInputsSliders.atomPosZ.slider('value',value); break; } case 'cellVolume':{ var newVal = $stringEditor.inputIsNumber(value.toString()); var tangency = $menu.getTangency(); if (newVal !== false){ if (tangency.tangency === true){ if (newVal > 90) { html.motif.other.cellVolume.val(newVal); takeAction('cellVolumeSlider',newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(22) }); takeAction('cellVolumeSlider',90); html.motif.other.cellVolume.val(90); success = false; } } else if (newVal > 0) { html.motif.other.cellVolume.val(newVal); takeAction('cellVolumeSlider',newVal); } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(22) }); takeAction('cellVolumeSlider',0); html.motif.other.cellVolume.val(0); success = false; } } else { $tooltipGenerator.showTooltip({ 'target': index, 'placement': 'top', 'message': $messages.getMessage(22) }); takeAction('cellVolumeSlider',100); html.motif.other.cellVolume.val(100); success = false; } break; } case 'cellVolumeSlider':{ html.motif.other.cellVolumeSlider.slider('value',value); break; } case 'tangency':{ if (value === false) html.motif.panel.tangency.parent().removeClass('purpleThemeActive'); else html.motif.panel.tangency.parent().addClass('purpleThemeActive'); break; } case 'atomPositioningXYZ':{ var tempValue = undefined; if ((_.isUndefined(value.toggle))) { takeAction('atomPositioningXYZ',{value:!value,toggle:true}); tempValue = value; } else tempValue = value.value; if (tempValue === true){ html.motif.panel.atomPositioningXYZ.addClass('buttonPressed'); html.motif.panel.atomPositioningXYZ.removeClass('btn-light'); html.motif.panel.atomPositioningXYZ.addClass('btn-purple'); html.motif.motifInputsLabels.xa.html('a'); html.motif.motifInputsLabels.yb.html('b'); html.motif.motifInputsLabels.zc.html('c'); } else{ html.motif.panel.atomPositioningXYZ.removeClass('buttonPressed'); html.motif.panel.atomPositioningXYZ.removeClass('btn-purple'); html.motif.panel.atomPositioningXYZ.addClass('btn-light'); } break; } case 'atomPositioningABC':{ var tempValue = undefined; if ((_.isUndefined(value.toggle))) { takeAction('atomPositioningABC',{value:!value,toggle:true}); tempValue = value; } else tempValue = value.value; if (tempValue === true){ html.motif.panel.atomPositioningABC.addClass('buttonPressed'); html.motif.panel.atomPositioningABC.removeClass('btn-light'); html.motif.panel.atomPositioningABC.addClass('btn-purple'); html.motif.motifInputsLabels.xa.html('x'); html.motif.motifInputsLabels.yb.html('y'); html.motif.motifInputsLabels.zc.html('z'); } else{ html.motif.panel.atomPositioningABC.removeClass('buttonPressed'); html.motif.panel.atomPositioningABC.removeClass('btn-purple'); html.motif.panel.atomPositioningABC.addClass('btn-light'); } break; } case 'atomPositioningAuto':{ ////////////////////////// } case 'lockCameras':{ if (value === true) { html.motif.other.lockCameras.addClass('active'); html.motif.other.lockCameras.find('img').attr('src','Images/lockCamerasActive.png'); } else { html.motif.other.lockCameras.removeClass('active'); html.motif.other.lockCameras.find('img').attr('src','Images/lockCameras.png'); } break; } case 'motifVisibilityInUC':{ if (value === true) { html.motif.other.motifVisibilityInUC.addClass('active'); html.motif.other.motifVisibilityInUC.find('img').attr('src','Images/motif-icon-white.png'); } else { html.motif.other.motifVisibilityInUC.removeClass('active'); html.motif.other.motifVisibilityInUC.find('img').attr('src','Images/motif-icon.png'); } break; } case 'swapButton':{ if (value === true) html.motif.other.swapButton.addClass('motif'); else html.motif.other.swapButton.removeClass('motif'); break; } case 'atomVisibility':{ if (value === false) { selector.find('.atomButton').find('img').attr('src','Images/hidden-icon-sm.png'); selector.find('.atomButton').removeClass('visible'); } else { selector.find('.atomButton').find('img').attr('src','Images/visible-icon-sm.png'); selector.find('.atomButton').addClass('visible'); } break; } // Requires Selector // case 'atomColor':{ html.motif.panel.color.children().css('background',value); html.motif.panel.color.spectrum('set',value); break; } case 'atomOpacity':{ html.motif.atomParameters.atomOpacity.val(value); takeAction('atomOpacitySlider',value); break; } case 'atomOpacitySlider':{ html.motif.panel.opacitySlider.slider('value',value); break; } case 'rotAngleTheta':{ html.motif.rotatingAngles.combo.rotAngleTheta.val(value); break; } case 'rotAnglePhi':{ html.motif.rotatingAngles.combo.rotAngleTheta.val(value); break; } case 'rotAngleX':{ html.motif.rotatingAngles.x.text(value); break; } case 'rotAngleY':{ html.motif.rotatingAngles.y.text(value); break; } case 'rotAngleZ':{ html.motif.rotatingAngles.z.text(value); break; } // Visual Tab case 'autoQuality':{ if (value === true){ _.each(html.visual.parameters.renderizationQuality, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationQuality.autoQuality.addClass('active'); } else html.visual.parameters.renderizationQuality.autoQuality.removeClass('active'); break; } case 'lowQuality':{ if (value === true){ _.each(html.visual.parameters.renderizationQuality, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationQuality.lowQuality.addClass('active'); takeAction('lod',2); } else html.visual.parameters.renderizationQuality.lowQuality.removeClass('active'); break; } case 'mediumQuality':{ if (value === true){ _.each(html.visual.parameters.renderizationQuality, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationQuality.mediumQuality.addClass('active'); takeAction('lod',3); } else html.visual.parameters.renderizationQuality.mediumQuality.removeClass('active'); break; } case 'highQuality':{ if (value === true){ _.each(html.visual.parameters.renderizationQuality, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationQuality.highQuality.addClass('active'); takeAction('lod',4); } else html.visual.parameters.renderizationQuality.highQuality.removeClass('active'); break; } case 'wireframe':{ if (value === true){ _.each(html.visual.parameters.renderizationMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationMode.wireframe.addClass('active'); } else html.visual.parameters.renderizationMode.wireframe.removeClass('active'); break; } case 'toon':{ if (value === true){ _.each(html.visual.parameters.renderizationMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationMode.toon.addClass('active'); } else html.visual.parameters.renderizationMode.toon.removeClass('active'); break; } case 'flat':{ if (value === true){ _.each(html.visual.parameters.renderizationMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationMode.flat.addClass('active'); } else html.visual.parameters.renderizationMode.flat.removeClass('active'); break; } case 'realistic':{ if (value === true){ _.each(html.visual.parameters.renderizationMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.renderizationMode.realistic.addClass('active'); } else html.visual.parameters.renderizationMode.realistic.removeClass('active'); break; } case 'lights':{ if (value === true) html.visual.parameters.lights.addClass('active'); else html.visual.parameters.lights.removeClass('active'); break; } case 'ssao':{ if (value === true) html.visual.parameters.ssao.addClass('active'); else html.visual.parameters.ssao.removeClass('active'); break; } case 'shadows':{ if (value === true) html.visual.parameters.shadows.addClass('active'); else html.visual.parameters.shadows.removeClass('active'); break; } case 'distortionOn':{ if (value === true) { html.visual.parameters.distortionOn.addClass('active'); html.visual.parameters.distortionOff.removeClass('active'); } else { html.visual.parameters.distortionOn.removeClass('active'); html.visual.parameters.distortionOff.addClass('active'); } break; } case 'distortionOff':{ if (value === true) { html.visual.parameters.distortionOff.addClass('active'); html.visual.parameters.distortionOn.removeClass('active'); } else { html.visual.parameters.distortionOff.removeClass('active'); html.visual.parameters.distortionOn.addClass('active'); } break; } case 'anaglyph':{ if (value === true){ _.each(html.visual.stereoscopic, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopic.anaglyph.addClass('active'); } else html.visual.stereoscopic.anaglyph.removeClass('active'); break; } case 'oculus':{ if (value === true){ _.each(html.visual.oculus, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopic.oculus.addClass('active'); } else html.visual.stereoscopic.oculus.removeClass('active'); break; } case 'oculusTracker':{ if (value === false) { if (html.visual.parameters.oculusTracker.hasClass('active')) html.visual.parameters.oculusTracker.button('toggle'); } else { if (!(html.visual.oculusTracker.oculus.hasClass('active'))) html.visual.parameters.oculusTracker.button('toggle'); } break; } case 'cardboard':{ if (value === false) { if (html.visual.parameters.cardboard.hasClass('active')) html.visual.parameters.cardboard.button('toggle'); } else { if (!(html.visual.parameters.cardboard.hasClass('active'))) html.visual.parameters.cardboard.button('toggle'); } break; } case 'sideBySide':{ if (value === true){ _.each(html.visual.stereoscopic, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopic.sideBySide3D.addClass('active'); } else html.visual.stereoscopic.sideBySide3D.removeClass('active'); break; } case 'onTop':{ if (value === true){ _.each(html.visual.stereoscopic, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopic.onTop3D.addClass('active'); } else html.visual.stereoscopic.onTop3D.removeClass('active'); break; } case 'anaglyphCell':{ if (value === true){ _.each(html.visual.stereoscopicCell, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopicCell.anaglyphCell.addClass('active'); } else html.visual.stereoscopicCell.anaglyphCell.removeClass('active'); break; } case 'oculusCell':{ if (value === true){ _.each(html.visual.oculusCell, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopic.oculusCell.addClass('active'); } //else html.visual.stereoscopic.oculusCell.removeClass('active'); break; } case 'sideBySideCell':{ if (value === true){ _.each(html.visual.stereoscopicCell, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopicCell.sideBySide3DCell.addClass('active'); } else html.visual.stereoscopicCell.sideBySide3DCell.removeClass('active'); break; } case 'onTopCell':{ if (value === true){ _.each(html.visual.stereoscopicCell, function($param, a) { $param.removeClass('active');}); html.visual.stereoscopicCell.onTop3DCell.addClass('active'); } else html.visual.stereoscopicCell.onTop3DCell.removeClass('active'); break; } case 'crystalCamTargetOn':{ if (value === true) { html.visual.parameters.crystalCamTargetOn.addClass('active'); html.visual.parameters.crystalCamTargetOff.removeClass('active'); } else { html.visual.parameters.crystalCamTargetOn.removeClass('active'); html.visual.parameters.crystalCamTargetOff.addClass('active'); } break; } case 'crystalCamTargetOff':{ if (value === true) { html.visual.parameters.crystalCamTargetOff.addClass('active'); html.visual.parameters.crystalCamTargetOn.removeClass('active'); } else { html.visual.parameters.crystalCamTargetOff.removeClass('active'); html.visual.parameters.crystalCamTargetOn.addClass('active'); } break; } case 'leapMotion':{ if (value === false) { if (html.visual.parameters.leapMotion.hasClass('active')) html.visual.parameters.leapMotion.button('toggle'); } else { if (!(html.visual.parameters.leapMotion.hasClass('active'))) html.visual.parameters.leapMotion.button('toggle'); } break; } case 'crystalClassic':{ if (value === true){ _.each(html.visual.parameters.crystalMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.crystalMode.crystalClassic.addClass('active'); } else html.visual.parameters.crystalMode.crystalClassic.removeClass('active'); break; } case 'crystalSubstracted':{ if (value === true){ _.each(html.visual.parameters.crystalMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.crystalMode.crystalSubstracted.addClass('active'); } else html.visual.parameters.crystalMode.crystalSubstracted.removeClass('active'); break; } case 'crystalSolidVoid':{ if (value === true){ _.each(html.visual.parameters.crystalMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.crystalMode.crystalSolidVoid.addClass('active'); } else html.visual.parameters.crystalMode.crystalSolidVoid.removeClass('active'); break; } case 'crystalGradeLimited':{ if (value === true){ _.each(html.visual.parameters.crystalMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.crystalMode.crystalGradeLimited.addClass('active'); } else html.visual.parameters.crystalMode.crystalGradeLimited.removeClass('active'); break; } case 'cellClassic':{ if (value === true){ _.each(html.visual.parameters.unitCellMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.unitCellMode.cellClassic.addClass('active'); } else html.visual.parameters.unitCellMode.cellClassic.removeClass('active'); break; } case 'cellSubstracted':{ if (value === true){ _.each(html.visual.parameters.unitCellMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.unitCellMode.cellSubstracted.addClass('active'); } else html.visual.parameters.unitCellMode.cellSubstracted.removeClass('active'); break; } case 'cellSolidVoid':{ if (value === true){ _.each(html.visual.parameters.unitCellMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.unitCellMode.cellSolidVoid.addClass('active'); } else html.visual.parameters.unitCellMode.cellSolidVoid.removeClass('active'); break; } case 'cellGradeLimited':{ if (value === true){ _.each(html.visual.parameters.unitCellMode, function($param, a) { $param.removeClass('active');}); html.visual.parameters.unitCellMode.cellGradeLimited.addClass('active'); } else html.visual.parameters.unitCellMode.cellGradeLimited.removeClass('active'); break; } case 'autoZoom':{ _.each(html.visual.tools.zoomOptions, function($param, a) { $param.removeClass('active'); }); html.visual.tools.zoomOptions.autoZoom.addClass('active'); $menu.autoZoom(true); window.dispatchEvent(new Event('resize')); break; } case 'zoom100':{ _.each(html.visual.tools.zoomOptions, function($param, a) { $param.removeClass('active'); }); html.visual.tools.zoomOptions.zoom100.addClass('active'); $menu.autoZoom(false); $menu.transformMenu(1); break; } case 'zoom90':{ _.each(html.visual.tools.zoomOptions, function($param, a) { $param.removeClass('active'); }); html.visual.tools.zoomOptions.zoom90.addClass('active'); $menu.autoZoom(false); $menu.transformMenu(0.9); break; } case 'zoom80':{ _.each(html.visual.tools.zoomOptions, function($param, a) { $param.removeClass('active'); }); html.visual.tools.zoomOptions.zoom80.addClass('active'); $menu.autoZoom(false); $menu.transformMenu(0.8); break; } case 'zoom70':{ _.each(html.visual.tools.zoomOptions, function($param, a) { $param.removeClass('active'); }); html.visual.tools.zoomOptions.zoom70.addClass('active'); $menu.autoZoom(false); $menu.transformMenu(0.7); break; } case 'fog':{ if (value === true) { html.visual.fog.checkbox.addClass('active'); html.visual.fog.checkbox.iCheck('check'); } else { html.visual.fog.checkbox.addClass('active'); html.visual.fog.checkbox.iCheck('uncheck'); } break; } case 'fogColor':{ html.visual.fog.color.spectrum('set',value); html.visual.fog.color.children().css('background',value); break; } case 'fogDensity':{ html.visual.fog.density.val(value); takeAction('fogDensitySlider',value); break; } case 'fogDensitySlider':{ html.visual.fog.densitySlider.slider('value',value); break; } case 'sounds':{ if (value === true) { html.visual.sound.sounds.addClass('active'); takeAction('soundSliderToggle',true); takeAction('muteToggle',true); } else { html.visual.sound.sounds.removeClass('active'); takeAction('soundSliderToggle',false); takeAction('muteToggle',false); } break; } case 'soundSliderToggle':{ if (value === true) html.visual.sound.soundSlider.slider('enable'); else html.visual.sound.soundSlider.slider('disable'); break; } case 'muteToggle':{ if (value === true) html.visual.sound.mute.removeClass('disable'); else html.visual.sound.mute.addClass('disable'); break; } case 'muteSound':{ if (value === true) { html.visual.sound.mute.addClass('active'); html.visual.sound.soundSlider.slider('value',0); } else html.visual.sound.mute.removeClass('active'); break; } case 'soundSlider':{ html.visual.sound.soundSlider.slider('value',value); if (value > 0) takeAction('muteSound',false); break; } case 'lodQuality':{ if (value < 1.5) takeAction('lowQuality', true); else if (value < 3.5) takeAction('mediumQuality', true); else takeAction('highQuality', true); break; } case 'lod':{ html.visual.lod.lod.val(value); takeAction('lodSlider',value); break; } case 'lodSlider':{ html.visual.lod.lodSlider.slider('value',value); break; } case 'crystalScreenColor':{ html.visual.tools.colorPickers.crystalScreen.spectrum('set',value); html.visual.tools.colorPickers.crystalScreen.children().css('background',value); break; } case 'cellScreenColor':{ html.visual.tools.colorPickers.cellScreen.spectrum('set',value); html.visual.tools.colorPickers.cellScreen.children().css('background',value); break; } case 'motifXScreenColor':{ html.visual.tools.colorPickers.motifXScreen.spectrum('set',value); html.visual.tools.colorPickers.motifXScreen.children().css('background',value); break; } case 'motifYScreenColor':{ html.visual.tools.colorPickers.motifYScreen.spectrum('set',value); html.visual.tools.colorPickers.motifYScreen.children().css('background',value); break; } case 'motifZScreenColor':{ html.visual.tools.colorPickers.motifZScreen.spectrum('set',value); html.visual.tools.colorPickers.motifZScreen.children().css('background',value); break; } // Note Tab case 'noteTitle':{ html.notes.properties.title.val(value); break; } case 'noteBody':{ html.notes.other.body.val(value); break; } case 'noteOpacity':{ html.notes.properties.opacity.selectpicker('val',value); break; } case 'noteColor':{ html.notes.properties.color.spectrum('set',value); html.notes.properties.color.children().css('background',value); break; } case 'saveCamera':{ if (value === true) { html.notes.other.saveCamera.addClass('active'); html.notes.other.saveCamera.find('img').attr('src','Images/comments-hover.png'); } else { html.notes.other.saveCamera.removeClass('active'); html.notes.other.saveCamera.find('img').attr('src','Images/comments.png'); } break; } case 'enableParameters':{ if (value === true) { html.notes.other.enableParameters.addClass('active'); html.notes.other.enableParameters.find('img').attr('src','Images/motif-icon-white.png'); } else { html.notes.other.enableParameters.removeClass('active'); html.notes.other.enableParameters.find('img').attr('src','Images/motif-icon.png'); } break; } case 'noteVisibility':{ if (value === false) { selector.find('.noteButton').find('img').attr('src','Images/hidden-icon-sm.png'); selector.find('.noteButton').removeClass('visible'); } else { selector.find('.noteButton').find('img').attr('src','Images/visible-icon-sm.png'); selector.find('.noteButton').addClass('visible'); } break; } // Requires Selector // // Library Tab case 'projectName':{ html.library.project.name.val(value); break; } case 'projectDescription':{ html.library.project.description.val(value); break; } case 'projectTags':{ _.each(value, function($parameter,k){ html.library.project.tags.tagit("createTag", $parameter); }); } case 'frameIT':{ if (value === true) html.library.png.frameIT.attr('class','active btn btn-purple-dark'); else html.library.png.frameIT.attr('class','btn btn-light'); break; } case 'qrCode':{ if (value === true) html.library.png.qrCode.attr('class','active btn btn-purple-dark'); else html.library.png.qrCode.attr('class','btn btn-light'); break; } case 'printMode':{ if (value === true) html.library.png.printMode.attr('class','active btn btn-purple-dark'); else html.library.png.printMode.attr('class','btn btn-light'); break; } //IAC Box case 'iacVisibility':{ if (value === true) { html.iac.buttons.visibility.find('img').attr('src','Images/visible-icon-sm.png'); html.iac.buttons.visibility.removeClass('notVisible'); } else { html.iac.buttons.visibility.find('img').attr('src','Images/hidden-icon-sm.png'); html.iac.buttons.visibility.addClass('notVisible'); } break; } case 'iacColor':{ html.iac.buttons.color.children().css('background',value); break; } case 'iacOpacity':{ html.iac.other.opacity.val(value); takeAction('iacOpacitySlider',value); break; } case 'iacOpacitySlider':{ html.iac.other.opacitySlider.slider('value',value); break; } case 'playerPlay':{ if (value === true) { html.notes.other.play.find('a').addClass('active'); } else { html.notes.other.play.find('a').removeClass('active'); } break; } case 'playerRepeat':{ if (value === true) { html.notes.other.repeat.find('a').addClass('active'); } else { html.notes.other.repeat.find('a').removeClass('active'); } break; } case 'playerPause':{ if (value === true) { html.notes.other.pause.find('a').addClass('active'); } else { html.notes.other.pause.find('a').removeClass('active'); } break; } case 'playerForward':{ if (value === true) { html.notes.other.forward.find('a').addClass('active'); } else { html.notes.other.forward.find('a').removeClass('active'); } break; } case 'playerRewind':{ if (value === true) { html.notes.other.rewind.find('a').addClass('active'); } else { html.notes.other.rewind.find('a').removeClass('active'); } break; } case 'playerRepeat':{ if (value === true) { html.notes.other.repeat.find('a').addClass('active'); } else { html.notes.other.repeat.find('a').removeClass('active'); } break; } case 'reset':{ // Tabs // $menu.reset('tabs'); // Toggles // takeAction('latticePoints',true); takeAction('edges',false); takeAction('faces',false); takeAction('xyzAxes',true); takeAction('abcAxes',false); takeAction('unitCellViewport',false); takeActionWithoutPublish('planes',true); takeActionWithoutPublish('directions',true); takeAction('atomRadius',false); takeAction('atomToggle',true); takeAction('labelToggle',false); takeAction('highlightTangency',false); takeAction('fullScreen',false); // Lattice // takeAction('selectedLattice',$messages.getMessage(18)); takeAction('latticePadlock',false); takeAction('repeatX',1); takeAction('repeatY',1); takeAction('repeatZ',1); takeAction('scaleX',1); takeAction('scaleY',1); takeAction('scaleZ',1); takeAction('alpha',90); takeAction('beta',90); takeAction('gamma',90); takeAction('motifPadlock',false); takeAction('cylinderColor','A19EA1'); takeAction('faceColor','907190'); takeAction('radius','2'); takeAction('faceOpacity','3'); $menu.reset('restrictions'); $menu.reset('collisions'); // Motif // takeAction('tangency',false); takeAction('cellVolume','100'); $menu.reset('atomTable'); takeAction('atomPosX',0); takeAction('atomPosY',0); takeAction('atomPosZ',0); takeAction('atomPositioningABC',{value:false,toggle:true}); takeAction('atomPositioningXYZ',{value:false,toggle:true}); html.motif.other.nameContainer.hide(); html.motif.motifInputsLabels.xa.html('x'); html.motif.motifInputsLabels.yb.html('y'); html.motif.motifInputsLabels.zc.html('z'); $menu.reset('motifCollisions'); // Visual // takeAction('lod',2.5); takeAction('mediumQuality',true); takeAction('realistic',true); takeAction('lights',true); takeAction('ssao',false); takeAction('shadows',true); takeAction('distortionOff',true); takeAction('anaglyph',false); takeAction('oculus',false); takeAction('oculusTracker',false); takeAction('sideBySide',false); takeAction('onTop',false); takeAction('anaglyphCell',false); takeAction('oculusCell',false); takeAction('sideBySideCell',false); takeAction('onTopCell',false); takeAction('crystalCamTargetOn',true); takeAction('leapMotion',false); takeAction('cardboard',false); takeAction('oculusTracker',false); takeAction('crystalClassic',true); takeAction('cellClassic',true); takeAction('fog',false); takeAction('fogDensity',1); takeAction('fogColor','transparent'); takeAction('sounds',false); takeAction('soundSlider',75); takeAction('crystalScreenColor','#000'); takeAction('cellScreenColor','#000'); takeAction('motifXScreenColor','#000'); takeAction('motifYScreenColor','#000'); takeAction('motifZScreenColor','#000'); // PnD // takeAction('planeOpacity','6'); takeAction('millerH',''); takeAction('millerK',''); takeAction('millerL',''); takeAction('millerI',''); takeAction('planeName',''); takeAction('planeColor','transparent'); takeAction('directionColor','transparent'); takeAction('millerU',''); takeAction('millerV',''); takeAction('millerW',''); takeAction('millerT',''); takeAction('directionName',''); takeAction('dirRadius','10'); $menu.reset('planesTable'); $menu.reset('directionTable'); // Notes // takeAction('noteTitle',''); takeAction('noteOpacity','10'); takeAction('noteBody',''); takeAction('noteColor','transparent'); $menu.reset('notesTable'); // Library // takeAction('frameIT',true); takeAction('qrCode',true); takeAction('printMode',true); break; } }; allowPublish = success; }; // Turn on/off toggles without publishing the event // function takeActionWithoutPublish(index,value){ switch(index){ case 'planes':{ if (value === true) { html.pnd.tables.planes.find('.planeButton').find('img').attr('src','Images/hidden-icon-sm.png'); html.menu.toggles.planes.parent().addClass('lightThemeActive'); } else { html.pnd.tables.planes.find('.planeButton').find('img').attr('src','Images/visible-icon-sm.png'); html.menu.toggles.planes.parent().removeClass('lightThemeActive'); } break; } case 'directions':{ if (value === true) { html.pnd.tables.directions.find('.directionButton').find('img').attr('src','Images/hidden-icon-sm.png'); html.menu.toggles.directions.parent().addClass('lightThemeActive'); } else { html.pnd.tables.directions.find('.directionButton').find('img').attr('src','Images/visible-icon-sm.png'); html.menu.toggles.directions.parent().removeClass('lightThemeActive'); } break; } } }; // Publishes event to the system // function publishAction(index,value){ switch(index){ // Menu Ribbon case 'xyzAxes':{ PubSub.publish(events.AXIS_MODE, value); break; } case 'abcAxes':{ PubSub.publish(events.AXIS_MODE, value); break; } case 'latticePoints':{ PubSub.publish(events.LATTICE_POINTS_TOGGLE, value); break; } case 'planes':{ PubSub.publish(events.PLANE_TOGGLE, value); break; } case 'directions':{ PubSub.publish(events.DIRECTION_TOGGLE, value); break; } case 'atomToggle':{ PubSub.publish(events.ATOM_TOGGLE, value); break; } case 'atomRadius':{ PubSub.publish(events.CHANGE_CRYSTAL_ATOM_RADIUS, value); break; } case 'unitCellViewport':{ PubSub.publish(events.UC_CRYSTAL_VIEWPORT, value); break; } case 'labelToggle':{ PubSub.publish(events.LABEL_TOGGLE, value); break; } case 'highlightTangency':{ PubSub.publish(events.HIGHLIGHT_TANGENCY, value); break; } // Motif tab case 'atomOpacity':{ PubSub.publish(events.ATOM_PARAMETER_CHANGE, value); break; } case 'atomColor':{ PubSub.publish(events.ATOM_PARAMETER_CHANGE, value); break; } case 'atomPosX':{ PubSub.publish(events.ATOM_POSITION_CHANGE, value); break; } case 'atomPosY':{ PubSub.publish(events.ATOM_POSITION_CHANGE, value); break; } case 'atomPosZ':{ PubSub.publish(events.ATOM_POSITION_CHANGE, value); break; } case 'cellVolume':{ PubSub.publish(events.CELL_VOLUME_CHANGE, value); break; } case 'tangentR':{ PubSub.publish(events.TANGENTR, value); break; } case 'tangency':{ PubSub.publish(events.ATOM_TANGENCY_CHANGE, value); break; } case 'previewAtomChanges':{ PubSub.publish(events.MOTIF_TO_LATTICE, value); break; } case 'saveAtomChanges':{ PubSub.publish(events.ATOM_SUBMIT, value); break; } case 'deleteAtom':{ PubSub.publish(events.ATOM_SUBMIT, value); break; } case 'atomPositioningXYZ':{ PubSub.publish(events.CHANGE_ATOM_POSITIONING_MODE, value); break; } case 'atomPositioningABC':{ PubSub.publish(events.CHANGE_ATOM_POSITIONING_MODE, value); break; } case 'atomPositioningAuto':{ PubSub.publish(events.CHANGE_ATOM_POSITIONING_MODE, value); break; } case 'lockCameras':{ PubSub.publish(events.MOTIF_CAMERASYNC_CHANGE, value); break; } case 'motifVisibilityInUC':{ PubSub.publish(events.TOGGLE_MOTIF_VISIBILITY_IN_UC, value); break; } case 'swapButton':{ PubSub.publish(events.SWAP_SCREEN, value); break; } case 'rotatingAngles':{ PubSub.publish(events.SET_ROTATING_ANGLE, value); break; } // Lattice Tab case 'motifPadlock':{ PubSub.publish(events.SET_PADLOCK, value); break; } case 'gridCheckButton':{ PubSub.publish(events.GRADE_CHOICES, value); break; } case 'faceCheckButton':{ PubSub.publish(events.GRADE_CHOICES, value); break; } case 'cylinderColor':{ PubSub.publish(events.GRADE_PARAMETER_CHANGE, value); break; } case 'faceColor':{ PubSub.publish(events.GRADE_PARAMETER_CHANGE, value); break; } case 'repeatX':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'repeatY':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'repeatZ':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'faceOpacity':{ PubSub.publish(events.GRADE_PARAMETER_CHANGE, value); break; } case 'radius':{ PubSub.publish(events.GRADE_PARAMETER_CHANGE, value); break; } case 'alpha':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'alphaMotif':{ PubSub.publish(events.MAN_ANGLE_CHANGE, value); break; } case 'beta':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'betaMotif':{ PubSub.publish(events.MAN_ANGLE_CHANGE, value); break; } case 'gamma':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'gammaMotif':{ PubSub.publish(events.MAN_ANGLE_CHANGE, value); break; } case 'scaleX':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'scaleXMotif':{ PubSub.publish(events.AXYZ_CHANGE, value); break; } case 'scaleY':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'scaleYMotif':{ PubSub.publish(events.AXYZ_CHANGE, value); break; } case 'scaleZ':{ PubSub.publish(events.LATTICE_PARAMETER_CHANGE, value); break; } case 'scaleZMotif':{ PubSub.publish(events.AXYZ_CHANGE, value); break; } case 'motifRefresh':{ PubSub.publish(events.MOTIF_TO_LATTICE, value); break; } case 'selectAtom':{ PubSub.publish(events.SAVED_ATOM_SELECTION, value); break; } case 'atomVisibility':{ PubSub.publish(events.ATOM_VISIBILITY, value); break; } case 'autoUpdate':{ PubSub.publish(events.AUTO_UPDATE, value); break; } // PnD Tab case 'planeColor':{ PubSub.publish(events.PLANE_PARAMETER_CHANGE, value); break; } case 'planeOpacity':{ PubSub.publish(events.PLANE_PARAMETER_CHANGE, value); break; } case 'planeName':{ PubSub.publish(events.PLANE_PARAMETER_CHANGE, value); break; } case 'millerH':{ PubSub.publish(events.PLANE_PARAMETER_CHANGE, value); break; } case 'millerK':{ PubSub.publish(events.PLANE_PARAMETER_CHANGE, value); break; } case 'millerL':{ PubSub.publish(events.PLANE_PARAMETER_CHANGE, value); break; } case 'millerI':{ PubSub.publish(events.PLANE_PARAMETER_CHANGE, value); break; } case 'directionColor':{ PubSub.publish(events.DIRECTION_PARAMETER_CHANGE, value); break; } case 'dirRadius':{ value.dirRadius = $stringEditor.divide10(value.dirRadius).toString(); PubSub.publish(events.DIRECTION_PARAMETER_CHANGE, value); break; } case 'directionName':{ PubSub.publish(events.DIRECTION_PARAMETER_CHANGE, value); break; } case 'millerU':{ PubSub.publish(events.DIRECTION_PARAMETER_CHANGE, value); break; } case 'millerV':{ PubSub.publish(events.DIRECTION_PARAMETER_CHANGE, value); break; } case 'millerW':{ PubSub.publish(events.DIRECTION_PARAMETER_CHANGE, value); break; } case 'millerT':{ PubSub.publish(events.DIRECTION_PARAMETER_CHANGE, value); break; } case 'selectPlane':{ PubSub.publish(events.PLANE_SELECTION, value); break; } case 'planeVisibility':{ PubSub.publish(events.PLANE_VISIBILITY, value); break; } case 'planeParallel':{ PubSub.publish(events.PLANE_PARALLEL, value); break; } case 'planeInterception':{ PubSub.publish(events.PLANE_INTERCEPTION, value); break; } case 'selectDirection':{ PubSub.publish(events.DIRECTION_SELECTION, value); break; } case 'directionVisibility':{ PubSub.publish(events.DIRECTION_VISIBILITY, value); break; } // Visual Tab case 'lod': { PubSub.publish(events.LOD, value); break; } case 'autoQuality': { PubSub.publish(events.AUTO_REND_QUALITY, value); break; } case 'lowQuality': { PubSub.publish(events.LOW_REND_QUALITY, value); break; } case 'mediumQuality': { PubSub.publish(events.MEDIUM_REND_QUALITY, value); break; } case 'highQuality': { PubSub.publish(events.HIGH_REND_QUALITY, value); break; } case 'wireframe': { PubSub.publish(events.CHANGE_REND_MODE, value); break; } case 'toon': { PubSub.publish(events.CHANGE_REND_MODE, value); break; } case 'flat': { PubSub.publish(events.CHANGE_REND_MODE, value); break; } case 'realistic': { PubSub.publish(events.CHANGE_REND_MODE, value); break; } case 'lights':{ PubSub.publish(events.SET_LIGHTS, value); break; } case 'ssao':{ PubSub.publish(events.SET_SSAO, value); break; } case 'shadows':{ PubSub.publish(events.SET_SHADOWS, value); break; } case 'distortionOn':{ PubSub.publish(events.MOTIF_DISTORTION_CHANGE, value); break; } case 'distortionOff':{ PubSub.publish(events.MOTIF_DISTORTION_CHANGE, value); break; } case 'anaglyph':{ PubSub.publish(events.ANAGLYPH_EFFECT_CRYSTAL, value); break; } case 'oculus':{ PubSub.publish(events.OCULUS_CRYSTAL, value); break; } case 'oculusTracker':{ PubSub.publish(events.OCULUS_CRYSTAL_TRACKER, value); break; } case 'cardboard':{ PubSub.publish(events.CARDBOARD, value); break; } case 'sideBySide':{ PubSub.publish(events.SIDE_BY_SIDE_3D_CRYSTAL, value); break; } case 'onTop':{ PubSub.publish(events.ON_TOP_3D_CRYSTAL, value); break; } case 'anaglyphCell':{ PubSub.publish(events.ANAGLYPH_EFFECT_UNIT_CELL, value); break; } case 'oculusCell':{ PubSub.publish(events.OCULUS_UNIT_CELL, value); break; } case 'sideBySideCell':{ PubSub.publish(events.SIDE_BY_SIDE_3D_UNIT_CELL, value); break; } case 'onTopCell':{ PubSub.publish(events.ON_TOP_3D_UNIT_CELL, value); break; } case 'crystalCamTargetOn':{ PubSub.publish(events.CRYSTAL_CAM_TARGET, value); break; } case 'crystalCamTargetOff':{ PubSub.publish(events.CRYSTAL_CAM_TARGET, value); break; } case 'fullScreen':{ PubSub.publish(events.FULL_SCREEN_APP, value); break; } case 'leapMotion':{ PubSub.publish(events.LEAP_MOTION, value); break; } case 'crystalClassic':{ PubSub.publish(events.CHANGE_CRYSTAL_MODE, value); break; } case 'crystalSubstracted':{ PubSub.publish(events.CHANGE_CRYSTAL_MODE, value); break; } case 'crystalSolidVoid':{ PubSub.publish(events.CHANGE_CRYSTAL_MODE, value); break; } case 'crystalGradeLimited':{ PubSub.publish(events.CHANGE_CRYSTAL_MODE, value); break; } case 'cellClassic':{ PubSub.publish(events.CHANGE_UNIT_CELL_MODE, value); break; } case 'cellSubstracted':{ PubSub.publish(events.CHANGE_UNIT_CELL_MODE, value); break; } case 'cellSolidVoid':{ PubSub.publish(events.CHANGE_UNIT_CELL_MODE, value); break; } case 'cellGradeLimited':{ PubSub.publish(events.CHANGE_UNIT_CELL_MODE, value); break; } case 'fog': { PubSub.publish(events.FOG_CHANGE, value); break; } case 'fogDensity': { PubSub.publish(events.FOG_PARAMETER_CHANGE, value); break; } case 'fogColor': { PubSub.publish(events.FOG_PARAMETER_CHANGE, value); break; } case 'sounds': { PubSub.publish(events.SET_SOUNDS, value); break; } case 'muteSound': { PubSub.publish(events.MUTE_SOUND, value); break; } case 'soundVolume': { PubSub.publish(events.SOUND_VOLUME, value); break; } case 'crystalScreenColor':{ PubSub.publish(events.RENDERER_COLOR_CHANGE, value); break; } case 'cellScreenColor':{ PubSub.publish(events.RENDERER_COLOR_CHANGE, value); break; } case 'motifXScreenColor':{ PubSub.publish(events.RENDERER_COLOR_CHANGE, value); break; } case 'motifYScreenColor':{ PubSub.publish(events.RENDERER_COLOR_CHANGE, value); break; } case 'motifZScreenColor':{ PubSub.publish(events.RENDERER_COLOR_CHANGE, value); break; } case '3DPrinting':{ PubSub.publish(events.THREE_D_PRINTING, value); break; } case 'objExporting':{ PubSub.publish(events.OBJ_SAVE, value); break; } // Notes Tab case 'atomNoteTable':{ PubSub.publish(events.UPDATE_NOTES, value); break; } case 'noteVisibility':{ PubSub.publish(events.NOTE_VISIBILITY, value); break; } case 'noteMovement':{ PubSub.publish(events.NOTE_MOVEMENT, value); break; } case 'noteColor':{ PubSub.publish(events.NOTE_COLOR, value); break; } case 'saveCamera':{ PubSub.publish(events.ENABLE_CAMERA_PARAMETERS, value); break; } case 'saveNoteForSystem':{ PubSub.publish(events.SAVE_NOTE_FOR_SYSTEM, value); break; } case 'selectNote':{ PubSub.publish(events.SELECT_NOTE_FOR_SYSTEM, value); break; } case 'deleteNote':{ PubSub.publish(events.DELETE_NOTE_FOR_SYSTEM, value); break; } case 'enableParameters':{ PubSub.publish(events.ENABLE_MOTIF_PARAMETERS, value); break; } case 'publishCameraData':{ PubSub.publish(events.PUBLISH_CAMERA_STATE, value); break; } // IAC Box case 'iacSound': { PubSub.publish(events.ATOM_CUSTOMIZATION, value); break; } case 'iacVisibility':{ PubSub.publish(events.ATOM_CUSTOMIZATION, value); break; } case 'iacDoll':{ PubSub.publish(events.ATOM_CUSTOMIZATION, value); break; } case 'iacColor':{ PubSub.publish(events.ATOM_CUSTOMIZATION, value); break; } case 'iacClose':{ PubSub.publish(events.ATOM_CUSTOMIZATION, value); break; } case 'iacOpacity':{ PubSub.publish(events.ATOM_CUSTOMIZATION, value); break; } case 'reset':{ PubSub.publish(events.RESET, value); break; } // player narrative case 'playerPlay':{ PubSub.publish(events.PLAYER_PLAY, value); break; } case 'playerRepeat':{ PubSub.publish(events.PLAYER_REPEAT, value); break; } case 'playerPause':{ PubSub.publish(events.PLAYER_PAUSE, value); break; } case 'playerForward':{ PubSub.publish(events.PLAYER_FORWARD, value); break; } case 'playerRepeat':{ PubSub.publish(events.PLAYER_REPEAT, value); break; } case 'playerRewind':{ PubSub.publish(events.PLAYER_REWIND, value); break; } }; }; // Module Interface // setUIValue.prototype.setValue = function(argument){ if (Object.keys(argument).length <= 0) return false; else { _.each(argument,function($parameter, k){ // Read Value and run action // if (!(_.isUndefined($parameter.value))) { // Select Element (if no selector is defined, the index is used // if (_.isUndefined($parameter.other)) $selector = jQuery('#'+k); else $selector = $parameter.other; takeAction(k,$parameter.value,$selector); } else allowPublish = true; // Publish Event // if (!(_.isUndefined($parameter.publish))) { if (allowPublish === true) publishAction(k,$parameter.publish); } allowPublish = false; }); } }; setUIValue.prototype.restoreUI = function(appUI,info){ // Restore Library Tab // takeAction('projectName',info.name); takeAction('projectDescription',info.description); takeAction('projectTags',info.tags); // Tabs // $menu.restoreTabs(appUI.menuRibbon); // Toggles // takeAction('latticePoints',appUI.menuRibbon.toggleButtons.latticePoints); takeAction('edges',appUI.menuRibbon.toggleButtons.edges); takeAction('faces',appUI.menuRibbon.toggleButtons.faces); takeAction('xyzAxes',appUI.menuRibbon.toggleButtons.xyzAxes); takeAction('abcAxes',appUI.menuRibbon.toggleButtons.abcAxes); // Ignore Viewport and Full Screen // takeAction('unitCellViewport',false); takeAction('fullScreen',false); //takeAction('unitCellViewport',appUI.menuRibbon.toggleButtons.unitCellViewport); takeActionWithoutPublish('planes',appUI.menuRibbon.toggleButtons.planes); takeActionWithoutPublish('directions',appUI.menuRibbon.toggleButtons.directions); takeAction('atomRadius',appUI.menuRibbon.toggleButtons.atomRadius); takeAction('atomToggle',appUI.menuRibbon.toggleButtons.atomToggle); takeAction('labelToggle',appUI.menuRibbon.toggleButtons.labelToggle); takeAction('highlightTangency',appUI.menuRibbon.toggleButtons.highlightTangency); // Atom Radius Slider // takeAction('atomRadiusSlider',appUI.menuRibbon.toggleButtons.atomRadiusSlider.toString()); // Lattice Tab // $menu.reset('collisions'); takeAction('selectedLattice',appUI.latticeTab.latticeSelecion.selectedLattice); takeAction('repeatX',appUI.latticeTab.latticeRepetition.repeatX); takeAction('repeatY',appUI.latticeTab.latticeRepetition.repeatY); takeAction('repeatZ',appUI.latticeTab.latticeRepetition.repeatZ); takeAction('scaleX',appUI.latticeTab.latticeLength.scaleX); takeAction('scaleY',appUI.latticeTab.latticeLength.scaleY); takeAction('scaleZ',appUI.latticeTab.latticeLength.scaleZ); takeAction('alpha',appUI.latticeTab.latticeAngle.alpha); takeAction('beta',appUI.latticeTab.latticeAngle.beta); takeAction('gamma',appUI.latticeTab.latticeAngle.gamma); $menu.restorePadlocks(appUI.latticeTab.padlocks.lattice.state,appUI.latticeTab.padlocks.motif.state); takeAction('cellEdgeColor',appUI.latticeTab.cellVisualization.cellEdge.color); takeAction('cellFaceColor',appUI.latticeTab.cellVisualization.cellFace.color); takeAction('radius',appUI.latticeTab.cellVisualization.cellEdge.radius.toString()); takeAction('faceOpacity',appUI.latticeTab.cellVisualization.cellFace.opacity.toString()); // Motif // takeAction('tangency',appUI.motifTab.tangency); takeAction('cellVolume',appUI.motifTab.cellVolume.toString()); takeAction('lockCameras',appUI.motifTab.lockCameras); $menu.reset('atomTable'); html.motif.other.nameContainer.hide(); $menu.reset('motifCollisions'); // Library if (appUI.hasOwnProperty('libraryTab')) { takeAction('frameIT',appUI.libraryTab.pngOptions.frameIT); takeAction('qrCode',appUI.libraryTab.pngOptions.qrCode); takeAction('printMode',appUI.libraryTab.pngOptions.printMode); } // Visual // if (appUI.visualTab.visualParameters.hasOwnProperty('lod')) takeAction('lod', appUI.visualTab.visualParameters.lod.lod.toString()); if (appUI.visualTab.visualParameters.hasOwnProperty('renderizationQuality')) { takeAction('autoQuality',appUI.visualTab.visualParameters.renderizationQuality.autoQuality); takeAction('lowQuality',appUI.visualTab.visualParameters.renderizationQuality.lowQuality); takeAction('mediumQuality',appUI.visualTab.visualParameters.renderizationQuality.mediumQuality); takeAction('highQuality',appUI.visualTab.visualParameters.renderizationQuality.highQuality); } takeAction('wireframe',appUI.visualTab.visualParameters.renderizationMode.wireframe); takeAction('toon',appUI.visualTab.visualParameters.renderizationMode.toon); takeAction('flat',appUI.visualTab.visualParameters.renderizationMode.flat); takeAction('realistic',appUI.visualTab.visualParameters.renderizationMode.realistic); takeAction('lights',appUI.visualTab.visualParameters.lights.lights); takeAction('ssao',appUI.visualTab.visualParameters.lights.ssao); takeAction('shadows',appUI.visualTab.visualParameters.lights.shadows); takeAction('distortionOff',appUI.visualTab.visualParameters.visualizationMode.distortionOff); takeAction('distortionOn',appUI.visualTab.visualParameters.visualizationMode.distortionOn); takeAction('anaglyph',appUI.visualTab.visualParameters.stereoscopicEffect.anaglyph); takeAction('oculus',appUI.visualTab.visualParameters.stereoscopicEffect.oculus); takeAction('sideBySide',appUI.visualTab.visualParameters.stereoscopicEffect.sideBySide3D); takeAction('onTop',appUI.visualTab.visualParameters.stereoscopicEffect.OnTop3D); if (appUI.visualTab.visualParameters.hasOwnProperty('stereoscopicCellEffect')) { takeAction('anaglyphCell',appUI.visualTab.visualParameters.stereoscopicCellEffect.anaglyphCell); takeAction('oculusCell',appUI.visualTab.visualParameters.stereoscopicCellEffect.oculusCell); takeAction('sideBySideCell',appUI.visualTab.visualParameters.stereoscopicCellEffect.sideBySide3DCell); takeAction('onTopCell',appUI.visualTab.visualParameters.stereoscopicCellEffect.OnTop3DCell); } takeAction('crystalCamTargetOn',appUI.visualTab.visualParameters.focalPoint.crystalCamTargetOn); takeAction('crystalCamTargetOff',appUI.visualTab.visualParameters.focalPoint.crystalCamTargetOff); takeAction('leapMotion',appUI.visualTab.visualParameters.leapMotion); takeAction('crystalClassic',appUI.visualTab.visualParameters.crystalModelRepresentation.crystalClassic); takeAction('crystalSubstracted',appUI.visualTab.visualParameters.crystalModelRepresentation.crystalSubstracted); takeAction('crystalSolidVoid',appUI.visualTab.visualParameters.crystalModelRepresentation.crystalSolidVoid); takeAction('crystalGradeLimited',appUI.visualTab.visualParameters.crystalModelRepresentation.crystalGradeLimited); takeAction('cellClassic',appUI.visualTab.visualParameters.unitCellModelRepresentation.cellClassic); takeAction('cellSubstracted',appUI.visualTab.visualParameters.unitCellModelRepresentation.cellSubstracted); takeAction('cellSolidVoid',appUI.visualTab.visualParameters.unitCellModelRepresentation.cellSolidVoid); takeAction('cellGradeLimited',appUI.visualTab.visualParameters.unitCellModelRepresentation.cellGradeLimited); if (appUI.visualTab.visualTools.menuZoom.autoZoom === true) takeAction('autoZoom',''); if (appUI.visualTab.visualTools.menuZoom.zoom100 === true) takeAction('zoom100',''); if (appUI.visualTab.visualTools.menuZoom.zoom90 === true) takeAction('zoom90',''); if (appUI.visualTab.visualTools.menuZoom.zoom80 === true) takeAction('zoom80',''); if (appUI.visualTab.visualTools.menuZoom.zoom70 === true) takeAction('zoom70',''); takeAction('fog',appUI.visualTab.visualTools.fog.state); takeAction('fogDensity',appUI.visualTab.visualTools.fog.density); takeAction('fogColor',appUI.visualTab.visualTools.fog.color); takeAction('sounds',appUI.visualTab.visualTools.sound.state); takeAction('soundSlider',appUI.visualTab.visualTools.sound.volume); takeAction('crystalScreenColor',appUI.visualTab.visualTools.colorization.crystalScreenColor); takeAction('cellScreenColor',appUI.visualTab.visualTools.colorization.cellScreenColor); takeAction('motifXScreenColor',appUI.visualTab.visualTools.colorization.motifXScreenColor); takeAction('motifYScreenColor',appUI.visualTab.visualTools.colorization.motifYScreenColor); takeAction('motifZScreenColor',appUI.visualTab.visualTools.colorization.motifZScreenColor); }; return setUIValue; });
var NOOP = require('../utils/NOOP'); // Phaser.Input.InteractiveObject var InteractiveObject = function (gameObject, hitArea, hitAreaCallback) { return { gameObject: gameObject, enabled: true, draggable: false, dropZone: false, target: null, camera: null, hitArea: hitArea, hitAreaCallback: hitAreaCallback, localX: 0, localY: 0, // 0 = Not being dragged // 1 = Being checked for dragging // 2 = Being dragged dragState: 0, dragStartX: 0, dragStartY: 0, dragX: 0, dragY: 0, // Callbacks callbackContext: gameObject, // gameObject, pointer, x, y onUp: NOOP, // gameObject, pointer, x, y onDown: NOOP, // gameObject, pointer, x, y onOver: NOOP, // gameObject, pointer onOut: NOOP, // gameObject, pointer, x, y onMove: NOOP, onDragStart: NOOP, onDrag: NOOP, onDragEnd: NOOP }; }; module.exports = InteractiveObject;
console.log('file2');
'use strict' var l = require('./log'); function tokenGenerator(lexRules) { return function* tokenize(input) { let pos = 0; while (pos < input.length) { let matchedRuleArr = lexRules.map(function(rule){ return {'rule': rule, 'match': rule[0].exec(input.substring(pos))}; }).filter(function(ruleAndMatch){ return ruleAndMatch.match != null && ruleAndMatch.match.index === 0; }).sort(function(matchedRule0, matchedRule1){ return matchedRule1.match[0].length - matchedRule0.match[0].length; }); let {rule, match} = matchedRuleArr[0]; let lexAction = rule[1]; let matchedStr = match[0]; pos += matchedStr.length; let token = lexAction(matchedStr); if (token) { yield token; } } } } exports.tokenGenerator = tokenGenerator;
var PersistentStorage = require('./persistent_storage'); var _ = require('./utils'); var keys = { data: 'data', protocol: 'protocol', thumbprint: 'thumbprint' }; var location = null; if(typeof window !== 'undefined') { location = window.location; } else { location = { protocol: 'https:' }; } // constructor // ----------- // defaults for options are handled in options_parser function Prefetch(o) { this.url = o.url; this.ttl = o.ttl; this.cache = o.cache; this.prepare = o.prepare; this.transform = o.transform; this.transport = o.transport; this.thumbprint = o.thumbprint; this.storage = new PersistentStorage(o.cacheKey); } _.mixin(Prefetch.prototype, { _settings: function() { return { url: this.url, type: 'GET', dataType: 'json' }; }, store: function(data) { if (!this.cache) { return; } this.storage.set(keys.data, data, this.ttl); this.storage.set(keys.protocol, location.protocol, this.ttl); this.storage.set(keys.thumbprint, this.thumbprint, this.ttl); }, fromCache: function() { var stored = {}, isExpired; if (!this.cache) { return null; } stored.data = this.storage.get(keys.data); stored.protocol = this.storage.get(keys.protocol); stored.thumbprint = this.storage.get(keys.thumbprint); // the stored data is considered expired if the thumbprints // don't match or if the protocol it was originally stored under // has changed isExpired = stored.thumbprint !== this.thumbprint || stored.protocol !== location.protocol; // TODO: if expired, remove from local storage return stored.data && !isExpired ? stored.data : null; }, fromNetwork: function(cb) { var that = this, settings; if (!cb) { return; } settings = this.prepare(this._settings()); // this.transport(settings).fail(onError).done(onResponse); this.transport(settings).then(onResponse, onError); function onError() { cb(true); } function onResponse(resp) { cb(null, that.transform(resp)); } }, clear: function() { this.storage.clear(); return this; } }); module.exports = Prefetch;
module.exports = function(config) { config.set({ frameworks: ['jasmine'], basePath : './', files : [ 'static/admin/js/libs.js', 'bower_components/angular-mocks/angular-mocks.js', 'static/admin/js/built.js', 'spec/angular/*Spec.js' ], // reporters: ['progress'], autoWatch : true, // browsers : ['Chrome'], plugins : [ // 'karma-junit-reporter', // 'karma-chrome-launcher', // 'karma-firefox-launcher', 'karma-jasmine' ] /*exclude : [ 'static/lib/angular/angular-loader.js', 'static/lib/angular/*.min.js', 'static/lib/angular/angular-scenario.js' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' }*/ }); };
/*global describe, it, expect, require, beforeEach */ describe('TableUtil', function () { 'use strict'; var TableUtil = require('../src/table-util'), underTest; beforeEach(function () { underTest = new TableUtil(); }); describe('justifyTable', function () { it('padds cells to fit max length values in each column with spaces around', function () { expect(underTest.justifyTable([ '| short| loooooooooooong|', '|loooooong | short |', '|loooooong ||', '|short|short|' ])).toEqual([ '| short | loooooooooooong |', '| loooooong | short |', '| loooooong | |', '| short | short |' ]); }); it('expands row dividers without spaces', function () { expect(underTest.justifyTable([ '| short| loooooooooooong|', '|-|-|', '|loooooong | short |', '|--|---|' ])).toEqual([ '| short | loooooooooooong |', '|-----------|-----------------|', '| loooooong | short |', '|-----------|-----------------|' ]); }); it('ignores manual spacing and dividers', function () { expect(underTest.justifyTable([ '| short | loooooooooooong|', '|-|-------------------------------------------------------------|', '|loooooong | short |' ])).toEqual([ '| short | loooooooooooong |', '|-----------|-----------------|', '| loooooong | short |' ]); }); it('removes spacing before the first pipe', function () { expect(underTest.justifyTable([ ' | short | loooooooooooong|', '|loooooong | short |' ])).toEqual([ '| short | loooooooooooong |', '| loooooong | short |' ]); }); }); describe('cellValuesForRow', function () { it('should return the values as an array', function () { expect(underTest.cellValuesForRow('|a|1|2.3|')).toEqual(['a', 1, 2.3]); }); it('should trim the values', function () { expect(underTest.cellValuesForRow(' | a |\tb |\tc\t| ')).toEqual(['a', 'b', 'c']); }); it('should return an empty array if not a table row', function () { expect(underTest.cellValuesForRow(' a \tb \tc\t')).toEqual([]); }); it('should return an empty array if empty string or undefined', function () { expect(underTest.cellValuesForRow('')).toEqual([]); expect(underTest.cellValuesForRow(' ')).toEqual([]); expect(underTest.cellValuesForRow()).toEqual([]); }); }); describe('tableValuesForTitles', function () { var table; beforeEach(function () { table = { type: 'table', titles: ['COST OF ACTION', 'profit'], items: [[1, 2], [3, 4], [5, 6]]}; }); it('returns a two-dimensional array with columns ordered according to specified titles', function () { expect(underTest.tableValuesForTitles(table, ['profit', 'cost of action'])).toEqual([[2, 1], [4, 3], [6, 5]]); }); it('adds undefined values for missing columns', function () { expect(underTest.tableValuesForTitles(table, ['loss', 'cost of action'])).toEqual([[undefined, 1], [undefined, 3], [undefined, 5]]); }); it('ignores additional columns', function () { expect(underTest.tableValuesForTitles(table, ['cost of action'])).toEqual([[1], [3], [5]]); }); it('returns false if there are no titles', function () { expect(underTest.tableValuesForTitles(table, [])).toBeFalsy(); expect(underTest.tableValuesForTitles(table)).toBeFalsy(); }); }); describe('objectArrayValuesForTitles', function () { var list; beforeEach(function () { list = [{'cost of action': 1, profit: 2}, {'COST OF ACTION': 3, proFit: 4}, {costOfAction: 5, profit: 6 }]; }); it('returns a two-dimensional array with columns ordered according to specified titles', function () { expect(underTest.objectArrayValuesForTitles(list, ['profit', 'cost of action'])).toEqual([[2, 1], [4, 3], [6, 5]]); }); it('adds undefined values for missing columns', function () { expect(underTest.objectArrayValuesForTitles(list, ['loss', 'cost of action'])).toEqual([[undefined, 1], [undefined, 3], [undefined, 5]]); }); it('ignores additional columns', function () { expect(underTest.objectArrayValuesForTitles(list, ['cost of action'])).toEqual([[1], [3], [5]]); }); it('returns false if there are no titles', function () { expect(underTest.objectArrayValuesForTitles(list, [])).toBeFalsy(); expect(underTest.objectArrayValuesForTitles(list)).toBeFalsy(); }); it('returns original array if an item in the list is an array rather than an object with properties', function () { expect(underTest.objectArrayValuesForTitles([[1, 2], {'COST OF ACTION': 3, proFit: 4}, [5, 6]], ['profit', 'cost of action'])).toEqual([[1, 2], [4, 3], [5, 6]]); }); }); });
import React from 'react'; import { render } from 'react-dom'; import { Field, Meta, Description, Label, Value, } from './FormComponents'; describe('Field', () => { it('renders without crashing', () => { const div = document.createElement('div'); render(<Field />, div); }); }); describe('Meta', () => { it('renders without crashing', () => { const div = document.createElement('div'); render(<Meta />, div); }); }); describe('Description', () => { it('renders without crashing', () => { const div = document.createElement('div'); render(<Description />, div); }); }); describe('Label', () => { it('renders without crashing', () => { const div = document.createElement('div'); render(<Label />, div); }); }); describe('Value', () => { it('renders without crashing', () => { const div = document.createElement('div'); render(<Value />, div); }); });
$(function(){function t(t){var e=t.attr("data-action");e||(e=location.pathname),e+=e.indexOf("?")===-1?"?":"&",location.href=e+t.find("input, textarea, select").serialize()}$(".sdx-getform").find("input, select").on("keypress",function(e){if(13==e.which){e.preventDefault();var n=$(this).closest(".sdx-getform");return t(n),!1}}),$(".sdx-getform .sdx-getform-submit").on("click",function(e){e.preventDefault();var n=$(this).closest(".sdx-getform");return t(n),!1}),$(".sdx-getform .sdx-getform-reset").on("click",function(t){t.preventDefault();var e=$(this),n=!0,r=e.attr("data-confirm");return r&&(n=confirm(r)),n&&e.closest(".sdx-getform").find("input:not([type=submit], [type=button], [type=reset], [type=image]), textarea, select").val(""),!1})});
import { Sequence, Parallel } from './primitives' export { FunctionTreeExecutionError, FunctionTreeError } from './errors' export function sequence(...args) { return new Sequence(...args) } export function parallel(...args) { return new Parallel(...args) } export { FunctionTree } from './FunctionTree' export { FunctionTree as default } from './FunctionTree'
var Backbone = require('backbone'); var UserModel = require('./user.js'); var CurrentRoomModel = require('./currentRoom.js'); var AppModel = Backbone.Model.extend({ initialize: function () { this.set('user', new UserModel()); this.set('current_room', new CurrentRoomModel()); this.get('current_room').on('room status', function () { this.trigger('room status'); }.bind(this)); this.get('user').on('user status', function () { this.trigger('user status'); }.bind(this)); }, userSignIn: function (res) { this.get('user').set(res); this.get('user').retrievePlaylists(); this.trigger('userSignInOut'); }, userSignOut: function () { this.get('user').updateToDefaults(); this.trigger('userSignInOut'); }, isSignedIn: function () { return (!!this.get('user').get('id')); }, isEnqueued: function () { if (this.isSignedIn()) { var user_id = this.get('user').get('id'); if (this.get('current_room').get('djQueue').get(user_id)) { //user is in djQueue return true; } else if (this.get('current_room').get('currentDJ').get('id') === user_id) { //user is currentDJ return true; } } return false; }, setCurrentRoom: function (room_id) { if (room_id) { this.get('current_room').set('id', room_id); //this.get('current_room').retrieveCurrentRoomInfo(); } else { this.get('current_room').updateToDefaults(); } } }); module.exports = AppModel;
module.exports={A:{A:{"2":"M D H F A B mB"},B:{"1":"K","2":"C E q L O I J"},C:{"2":"5 8 jB AB G M D H F A B C E q L O I J P Q R S T U V W X Y Z a b c d f g h i j k l m n o p N r s t u v w eB cB","129":"0 1 2 3 4 6 9 x y z LB BB CB DB EB FB HB IB JB"},D:{"1":"0 1 2 3 4 6 9 z LB BB CB DB EB FB HB IB JB bB VB PB oB K QB RB SB TB","2":"5 8 G M D H F A B C E q L O I J P Q R S T U V W X Y Z a b c d f g h i j k l m n o p N r s t u v w x y"},E:{"2":"5 7 G M D H F A B C E UB NB WB XB YB ZB aB e dB KB"},F:{"1":"0 1 2 3 4 m n o p N r s t u v w x y z","2":"7 8 F B C L O I J P Q R S T U V W X Y Z a b c d f g h i j k l fB gB hB iB e MB kB"},G:{"2":"H E NB lB GB nB OB pB qB rB sB tB uB vB wB xB yB KB"},H:{"2":"zB"},I:{"1":"K","2":"AB G 0B 1B 2B 3B GB 4B 5B"},J:{"2":"D A"},K:{"2":"7 A B C e MB","16":"N"},L:{"1":"K"},M:{"1":"6"},N:{"2":"A B"},O:{"1":"6B"},P:{"1":"7B 8B 9B AC BC","2":"G"},Q:{"1":"CC"},R:{"1":"DC"},S:{"2":"EC"}},B:5,C:"Auxclick"};
/* eslint-env node, mocha */ /* global $pg_database */ import knexCleaner from 'knex-cleaner' import { dbAdapter, User, Group } from '../../app/models' describe('Group', () => { beforeEach(async () => { await knexCleaner.clean($pg_database) }) describe('#create()', () => { let groupAdmin beforeEach(async () => { groupAdmin = new User({ username: 'Pluto', password: 'password' }) await groupAdmin.create() }) it('should create without error', (done) => { const group = new Group({ username: 'FriendFeed' }) const ownerId = groupAdmin.id group.create(ownerId) .then((group) => { group.should.be.an.instanceOf(Group) group.should.not.be.empty group.should.have.property('id') return group }) .then((group) => dbAdapter.getGroupById(group.id)) .then((newGroup) => { newGroup.should.be.an.instanceOf(Group) newGroup.should.not.be.empty newGroup.should.have.property('id') newGroup.id.should.eql(group.id) newGroup.should.have.property('type') newGroup.type.should.eql('group') return dbAdapter.getGroupByUsername(group.username) }) .then((groupByName) => { groupByName.id.should.eql(group.id) groupByName.should.be.an.instanceOf(Group) return groupByName.getAdministratorIds() }) .then((adminIds) => { adminIds.should.contain(ownerId) done() }) .catch((e) => { done(e) }) }) it('should create with null screenName', (done) => { const group = new Group({ username: 'username', screenName: null }) group.create() .then((newGroup) => { newGroup.should.be.an.instanceOf(Group) newGroup.should.not.be.empty newGroup.should.have.property('id') newGroup.id.should.eql(group.id) newGroup.should.have.property('type') newGroup.type.should.eql('group') group.should.have.property('screenName') newGroup.screenName.should.eql(group.username) done() }) .catch((e) => { done(e) }) }) it('should not create with tiny screenName', async () => { const group = new Group({ username: 'FriendFeed', screenName: 'a' }) try { await group.create() } catch (e) { e.message.should.eql(`"${group.screenName}" is not a valid display name. Names must be between 3 and 25 characters long.`) return } throw new Error(`FAIL (screenname "a" should not be valid)`) }) it('should not create with username that already exists', (done) => { const groupA = new Group({ username: 'FriendFeedA', screenName: 'FriendFeedA' }) const groupB = new Group({ username: 'FriendFeedA', screenName: 'FriendFeedB' }) groupA.create() .then(() => { return groupB.create() }) .then(() => { done(new Error('Creted group with existing username')) }) .catch((e) => { e.message.should.eql('Already exists') done() }) }) }) describe('#update()', () => { it('should update without error', async () => { const screenName = 'Pepyatka' const group = new Group({ username: 'FriendFeed' }) await group.create() group.should.be.an.instanceOf(Group) group.should.not.be.empty group.should.have.property('id') group.should.have.property('screenName') await group.update({ screenName }) group.should.be.an.instanceOf(Group) group.should.not.be.empty group.should.have.property('id') group.id.should.eql(group.id) group.should.have.property('type') group.type.should.eql('group') group.should.have.property('screenName') group.screenName.should.eql(screenName) }) it('should update without screenName', (done) => { const screenName = 'Luna' const group = new Group({ username: 'Luna', screenName }) group.create() .then((group) => group.update({})) .then((newGroup) => { newGroup.should.be.an.instanceOf(Group) newGroup.should.not.be.empty newGroup.should.have.property('id') newGroup.screenName.should.eql(screenName) done() }) .catch((e) => { done(e) }) }) }) describe('#isValidUsername()', () => { const valid = [ 'luna', 'lun', '12345', 'hello1234', 'save-our-snobs', ' group', 'group ', // automatically trims 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' // 35 chars is ok ] valid.forEach((username) => { it(`should allow username ${username}`, async () => { const group = new Group({ username, screenName: 'test' }) await group.create(); (await group.isValidEmail()).should.eql(true) }) }) const invalid = [ 'lu', '-12345', 'luna-', 'hel--lo', 'абизьян', 'gr oup', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' // 36 chars is 1 char too much ] invalid.forEach((username) => { it(`should not allow invalid username ${username}`, async () => { const group = new Group({ username, screenName: 'test' }) try { await group.create() } catch (e) { e.message.should.eql('Invalid username') return } throw new Error(`FAIL (username "${username}" should not be valid)`) }) }) }) describe('addAdministrator', () => { let group , groupAdmin beforeEach(async () => { groupAdmin = new User({ username: 'Pluto', password: 'password' }) await groupAdmin.create() group = new Group({ username: 'Luna', screenName: 'Moon' }) await group.create() }) it('should add an administrator', (done) => { group.addAdministrator(groupAdmin.id) .then(() => group.getAdministratorIds()) .then((res) => { res.should.contain(groupAdmin.id) done() }) .catch((e) => { done(e) }) }) }) describe('removeAdministrator', () => { let group , groupAdmin , secondGroupAdmin beforeEach(async () => { groupAdmin = new User({ username: 'Pluto', password: 'password' }) await groupAdmin.create() secondGroupAdmin = new User({ username: 'Jupiter', password: 'password' }) await secondGroupAdmin.create() group = new Group({ username: 'Luna', screenName: 'Moon' }) await group.create(groupAdmin.id) await group.addAdministrator(secondGroupAdmin.id) }) it('should remove an administrator', (done) => { group.removeAdministrator(groupAdmin.id) .then(() => group.getAdministratorIds()) .then((res) => { res.length.should.eql(1) done() }) .catch((e) => { done(e) }) }) it('should refuse to remove the last administrator', (done) => { group.removeAdministrator(secondGroupAdmin.id) .then(() => group.removeAdministrator(groupAdmin.id)) .catch((e) => { e.message.should.eql('Cannot remove last administrator') done() }) }) }) })
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4 7h4v10H6V9H4V7zm11.83 4.72L18.66 7h-2.33l-1.66 2.77L13 7h-2.33l2.83 4.72L10.33 17h2.33l2-3.34 2 3.34H19l-3.17-5.28z" /> , 'TimesOneMobiledata');
var saveSelectColor = { 'Name': 'SelcetColor', 'Color': 'theme-white' } // 判断用户是否已有自己选择的模板风格 if (storageLoad('SelcetColor')) { $('body').attr('class', storageLoad('SelcetColor').Color) } else { storageSave(saveSelectColor); $('body').attr('class', 'theme-white') } // 本地缓存 function storageSave(objectData) { localStorage.setItem(objectData.Name, JSON.stringify(objectData)); } function storageLoad(objectName) { if (localStorage.getItem(objectName)) { return JSON.parse(localStorage.getItem(objectName)) } else { return false } }
'use strict'; var gulp = require('gulp'); var gutil = require('gulp-util'); var webpack = require('webpack'); var WebpackNotifierPlugin = require('webpack-notifier'); var webpackConfig = require('../webpack.config.js'); function buildProduction(done) { // modify some webpack config options var myProdConfig = Object.create(webpackConfig); myProdConfig.output.filename = '[name].[hash].js'; myProdConfig.plugins = myProdConfig.plugins.concat( new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.[hash].js' }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin() ); // run webpack webpack(myProdConfig, function(err, stats) { if(err) { throw new gutil.PluginError('webpack:build', err); } gutil.log('[webpack:build]', stats.toString({ colors: true })); if (done) { done(); } }); } function createDevCompiler() { // modify some webpack config options var myDevConfig = Object.create(webpackConfig); myDevConfig.devtool = 'inline-source-map'; myDevConfig.debug = true; myDevConfig.plugins = myDevConfig.plugins.concat( new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js' }), new WebpackNotifierPlugin({ title: 'Webpack build', excludeWarnings: true }) ); // create a single instance of the compiler to allow caching return webpack(myDevConfig); } function buildDevelopment(done, devCompiler) { // run webpack devCompiler.run(function(err, stats) { if(err) { throw new gutil.PluginError('webpack:build-dev', err); } gutil.log('[webpack:build-dev]', stats.toString({ chunks: false, colors: true })); if (done) { done(); } }); } function bundle(options) { var devCompiler; function build(done) { if (options.shouldWatch) { buildDevelopment(done, devCompiler); } else { buildProduction(done); } } if (options.shouldWatch) { devCompiler = createDevCompiler(); gulp.watch('src/**/*', function() { build(); }); } return new Promise(function(resolve, reject) { build(function (err) { if (err) { reject(err); } else { resolve('webpack built'); } }); }); } module.exports = { build: function() { return bundle({ shouldWatch: false }); }, watch: function() { return bundle({ shouldWatch: true }); } };
function isClassDescriptor(possibleDesc) { let [target] = possibleDesc; return ( possibleDesc.length === 1 && typeof target === 'function' && 'prototype' in target && !target.__isComputedDecorator ); } export function isFieldDescriptor(possibleDesc) { let [target, key, desc] = possibleDesc; return ( possibleDesc.length === 3 && typeof target === 'object' && target !== null && typeof key === 'string' && ((typeof desc === 'object' && desc !== null && 'enumerable' in desc && 'configurable' in desc) || desc === undefined) // TS compatibility ); } export function isDescriptor(possibleDesc) { return isFieldDescriptor(possibleDesc) || isClassDescriptor(possibleDesc); }
/*! * Ext JS Library 3.1.1 * Copyright(c) 2006-2010 Ext JS, LLC * [email protected] * http://www.extjs.com/license */ /** * @class Ext.ux.tree.TreeGridLoader * @extends Ext.tree.TreeLoader */ Ext.ux.tree.TreeGridLoader = Ext.extend(Ext.tree.TreeLoader, { createNode : function(attr) { if (!attr.uiProvider) { attr.uiProvider = Ext.ux.tree.TreeGridNodeUI; } return Ext.tree.TreeLoader.prototype.createNode.call(this, attr); } });
/* Kazakh (UTF-8) initialisation for the jQuery UI date picker plugin. */ /* Written by Dmitriy Karasyov ([email protected]). */ jQuery(function ($) { $.datepicker.regional['kk'] = { closeText: 'Жабу', prevText: '&#x3c;Алдыңғы', nextText: 'Келесі&#x3e;', currentText: 'Бүгін', monthNames: ['Қаңтар', 'Ақпан', 'Наурыз', 'Сәуір', 'Мамыр', 'Маусым', 'Шілде', 'Тамыз', 'Қыркүйек', 'Қазан', 'Қараша', 'Желтоқсан'], monthNamesShort: ['Қаң', 'Ақп', 'Нау', 'Сәу', 'Мам', 'Мау', 'Шіл', 'Там', 'Қыр', 'Қаз', 'Қар', 'Жел'], dayNames: ['Жексенбі', 'Дүйсенбі', 'Сейсенбі', 'Сәрсенбі', 'Бейсенбі', 'Жұма', 'Сенбі'], dayNamesShort: ['жкс', 'дсн', 'ссн', 'срс', 'бсн', 'жма', 'снб'], dayNamesMin: ['Жк', 'Дс', 'Сс', 'Ср', 'Бс', 'Жм', 'Сн'], weekHeader: 'Не', dateFormat: 'dd.mm.yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: '' }; $.datepicker.setDefaults($.datepicker.regional['kk']); });
'use strict'; //Categories service used for categories REST endpoint angular.module('mean.categories').factory('Categories', ['$resource', function($resource) { return $resource('categories/:menuId', { menuId: '@_id' }, { update: { method: 'PUT' } }); }]);
import { fork } from 'redux-saga/effects' export const makeRootSaga = (sagas) => { return function *rootSaga () { yield sagas.map(saga => fork(saga)) } } export const injectSagas = (store, { key, sagas }) => { if (store.asyncSagas[key]) { return } store.asyncSagas[key] = sagas store.runSaga(makeRootSaga(sagas)) } export default makeRootSaga
var npm = require('npm'); console.log("I'm bad!");
/** * @ignore * Button control for KISSY. * @author [email protected] */ KISSY.add("button", function (S, Node, Control, ButtonRender) { var KeyCode = Node.KeyCode; /** * KISSY Button. * @extends KISSY.Component.Control * @class KISSY.Button */ return Control.extend({ isButton: 1, bindUI: function () { this.$el.on("keyup", this.handleKeyDownInternal, this); }, handleKeyDownInternal: function (e) { if (e.keyCode == KeyCode.ENTER && e.type == "keydown" || e.keyCode == KeyCode.SPACE && e.type == "keyup") { return this.handleClickInternal(e); } // Return true for space keypress (even though the event is handled on keyup) // as preventDefault needs to be called up keypress to take effect in IE and // WebKit. return e.keyCode == KeyCode.SPACE; }, handleClickInternal: function () { var self = this; if (self.get("checkable")) { self.set("checked", !self.get("checked")); } // button 的默认行为就是触发 click self.fire("click"); } }, { ATTRS: { /** * Value associated with button component. * @property value */ /** * Value associated with button component. * @cfg {*} value */ /** * @ignore */ value: {}, /** *Aria-describedby attribute. * @property describedby * @type {String} */ /** *Aria-describedby attribute. * @cfg {String} describedby */ /** * @ignore */ describedby: { value: '', view: 1 }, /** * Tooltip for button. * @cfg {String} tooltip */ /** * Tooltip for button. * @property tooltip * @type {String} */ /** * @ignore */ tooltip: { value: '', view: 1 }, /** * Whether button can be checkable(toggle). * Defaults to: false. * @cfg {Boolean} checkable */ /** * @ignore */ checkable: { }, /** * Whether button is checked(toggle). * Defaults to: false. * @type {Boolean} * @property checked */ /** * Whether button is checked(toggle). * @cfg {Boolean} checked */ /** * @ignore */ checked: { value:false, view: 1 }, xrender: { value: ButtonRender } }, xclass: 'button' }); }, { requires: ['node', 'component/control', 'button/render'] });
/* * HexGL * @author Thibaut 'BKcore' Despoulain <http://bkcore.com> * @license This work is licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/. */ var bkcore = bkcore || {}; bkcore.hexgl = bkcore.hexgl || {}; bkcore.hexgl.ShipControls = function(domElement) { var self = this; this.active = true; this.destroyed = false; this.dom = domElement; this.mesh = null; this.epsilon = 0.00000001; this.zero = new THREE.Vector3(0,0,0); this.airResist = 0.02; this.airDrift = 0.1; this.thrust = 0.02; this.airBrake = 0.02; this.maxSpeed = 7.0; this.boosterSpeed = this.maxSpeed * 0.4; this.boosterDecay = 0.01; this.angularSpeed = 0.005; this.airAngularSpeed = 0.0065; this.repulsionRatio = 0.5; this.repulsionCap = 2.5; this.repulsionLerp = 0.1; this.collisionSpeedDecrease = 0.8; this.collisionSpeedDecreaseCoef = 0.8; this.maxShield = 1.0; this.shieldDelay = 60; this.shieldTiming = 0; this.shieldDamage = 0.25; this.driftLerp = 0.35; this.angularLerp = 0.35; this.movement = new THREE.Vector3(0,0,0); this.rotation = new THREE.Vector3(0,0,0); this.roll = 0.0; this.rollAxis = new THREE.Vector3(); this.drift = 0.0; this.speed = 0.0; this.speedRatio = 0.0; this.boost = 0.0; this.shield = 1.0; this.angular = 0.0; this.currentVelocity = new THREE.Vector3(); this.quaternion = new THREE.Quaternion(); this.dummy = new THREE.Object3D(); this.dummy.useQuaternion = true; this.collisionMap = null; this.collisionPixelRatio = 1.0; this.collisionDetection = false; this.collisionPreviousPosition = new THREE.Vector3(); this.heightMap = null; this.heightPixelRatio = 1.0; this.heightBias = 0.0; this.heightLerp = 0.4; this.heightScale = 1.0; this.rollAngle = 0.6; this.rollLerp = 0.08; this.rollDirection = new THREE.Vector3(0,0,1); this.gradient = 0.0; this.gradientTarget = 0.0; this.gradientLerp = 0.05; this.gradientScale = 4.0; this.gradientVector = new THREE.Vector3(0,0,5); this.gradientAxis = new THREE.Vector3(1,0,0); this.tilt = 0.0; this.tiltTarget = 0.0; this.tiltLerp = 0.05; this.tiltScale = 4.0; this.tiltVector = new THREE.Vector3(5,0,0); this.tiltAxis = new THREE.Vector3(0,0,1); this.repulsionVLeft = new THREE.Vector3(1,0,0); this.repulsionVRight = new THREE.Vector3(-1,0,0); this.repulsionVFront = new THREE.Vector3(0,0,1); this.repulsionVScale = 4.0; this.repulsionAmount = 0.0; this.repulsionForce = new THREE.Vector3(); this.resetPos = null; this.resetRot = null; this.key = { forward: false, backward: false, left: false, right: false, ltrigger: false, rtrigger: false, use: false }; this.collision = { front: false, left: false, right: false }; function onKeyDown(event) { switch(event.keyCode) { case 38: /*up*/ self.key.forward = true; break; case 40: /*down*/self.key.backward = true; break; case 37: /*left*/self.key.left = true; break; case 39: /*right*/self.key.right = true; break; case 81: /*Q*/self.key.ltrigger = true; break; case 65: /*A*/self.key.ltrigger = true; break; case 68: /*D*/self.key.rtrigger = true; break; case 69: /*E*/self.key.rtrigger = true; break; } }; function onKeyUp(event) { switch(event.keyCode) { case 38: /*up*/ self.key.forward = false; break; case 40: /*down*/self.key.backward = false; break; case 37: /*left*/self.key.left = false; break; case 39: /*right*/self.key.right = false; break; case 81: /*Q*/self.key.ltrigger = false; break; case 65: /*A*/self.key.ltrigger = false; break; case 68: /*D*/self.key.rtrigger = false; break; case 69: /*E*/self.key.rtrigger = false; break; } }; domElement.addEventListener('keydown', onKeyDown, false); domElement.addEventListener('keyup', onKeyUp, false); }; bkcore.hexgl.ShipControls.prototype.control = function(threeMesh) { this.mesh = threeMesh; this.mesh.martixAutoUpdate = false; this.dummy.position = this.mesh.position; }; bkcore.hexgl.ShipControls.prototype.reset = function(position, rotation) { this.resetPos = position; this.resetRot = rotation; this.movement.set(0,0,0); this.rotation.copy(rotation); this.roll = 0.0; this.drift = 0.0; this.speed = 0.0; this.speedRatio = 0.0; this.boost = 0.0; this.shield = this.maxShield; this.destroyed = false; this.dummy.position.copy(position); this.quaternion.set(rotation.x, rotation.y, rotation.z, 1).normalize(); this.dummy.quaternion.set(0,0,0,1); this.dummy.quaternion.multiplySelf(this.quaternion); this.dummy.matrix.setPosition(this.dummy.position); this.dummy.matrix.setRotationFromQuaternion(this.dummy.quaternion); this.mesh.matrix.identity(); this.mesh.applyMatrix(this.dummy.matrix); } bkcore.hexgl.ShipControls.prototype.destroy = function() { this.active = false; this.destroyed = true; this.collision.front = false; this.collision.left = false; this.collision.right = false; } bkcore.hexgl.ShipControls.prototype.update = function(dt) { if(!this.active) return; this.rotation.y = 0; this.movement.set(0,0,0); this.drift += (0.0 - this.drift) * this.driftLerp; this.angular += (0.0 - this.angular) * this.angularLerp * 0.5; var rollAmount = 0.0; var angularAmount = 0.0; if(this.key.forward) this.speed += this.thrust * dt; else this.speed -= this.airResist * dt; if(this.key.left) { angularAmount += this.angularSpeed * dt; rollAmount -= this.rollAngle; } if(this.key.right) { angularAmount -= this.angularSpeed * dt; rollAmount += this.rollAngle; } if(this.key.ltrigger) { if(this.key.left) angularAmount += this.airAngularSpeed * dt; else angularAmount += this.airAngularSpeed * 0.5 * dt; this.speed -= this.airBrake * dt; this.drift += (this.airDrift - this.drift) * this.driftLerp; this.movement.x += this.speed * this.drift * dt; if(this.drift > 0.0) this.movement.z -= this.speed * this.drift * dt; rollAmount -= this.rollAngle * 0.7; } if(this.key.rtrigger) { if(this.key.right) angularAmount -= this.airAngularSpeed * dt; else angularAmount -= this.airAngularSpeed * 0.5 * dt; this.speed -= this.airBrake * dt; this.drift += (-this.airDrift - this.drift) * this.driftLerp; this.movement.x += this.speed * this.drift * dt; if(this.drift < 0.0) this.movement.z += this.speed * this.drift * dt; rollAmount += this.rollAngle * 0.7; } this.angular += (angularAmount - this.angular) * this.angularLerp; this.rotation.y = this.angular; this.speed = Math.max(0.0, Math.min(this.speed, this.maxSpeed)); this.speedRatio = this.speed / this.maxSpeed; this.movement.z += this.speed * dt; if(this.repulsionForce.isZero()) { this.repulsionForce.set(0,0,0); } else { if(this.repulsionForce.z != 0.0) this.movement.z = 0; this.movement.addSelf(this.repulsionForce); this.repulsionForce.lerpSelf(this.zero, dt > 1.5 ? this.repulsionLerp*2 : this.repulsionLerp); } this.collisionPreviousPosition.copy(this.dummy.position); this.boosterCheck(dt); //this.movement.multiplyScalar(dt); //this.rotation.multiplyScalar(dt); this.dummy.translateX(this.movement.x); this.dummy.translateZ(this.movement.z); this.heightCheck(dt); this.dummy.translateY(this.movement.y); this.currentVelocity.copy(this.dummy.position).subSelf(this.collisionPreviousPosition); this.collisionCheck(dt); this.quaternion.set(this.rotation.x, this.rotation.y, this.rotation.z, 1).normalize(); this.dummy.quaternion.multiplySelf(this.quaternion); this.dummy.matrix.setPosition(this.dummy.position); this.dummy.matrix.setRotationFromQuaternion(this.dummy.quaternion); if(this.shield <= 0.0) { this.shield = 0.0; this.destroy(); } if(this.mesh != null) { this.mesh.matrix.identity(); // Gradient (Mesh only, no dummy physics impact) var gradientDelta = (this.gradientTarget - this.gradient) * this.gradientLerp; if(Math.abs(gradientDelta) > this.epsilon) this.gradient += gradientDelta; if(Math.abs(this.gradient) > this.epsilon) { this.gradientAxis.set(1,0,0); this.mesh.matrix.rotateByAxis(this.gradientAxis, this.gradient); } // Tilting (Idem) var tiltDelta = (this.tiltTarget - this.tilt) * this.tiltLerp; if(Math.abs(tiltDelta) > this.epsilon) this.tilt += tiltDelta; if(Math.abs(this.tilt) > this.epsilon) { this.tiltAxis.set(0,0,1); this.mesh.matrix.rotateByAxis(this.tiltAxis, this.tilt); } // Rolling (Idem) var rollDelta = (rollAmount - this.roll) * this.rollLerp; if(Math.abs(rollDelta) > this.epsilon) this.roll += rollDelta; if(Math.abs(this.roll) > this.epsilon) { this.rollAxis.copy(this.rollDirection); this.mesh.matrix.rotateByAxis(this.rollAxis, this.roll); } this.mesh.applyMatrix(this.dummy.matrix); this.mesh.updateMatrixWorld(true); } }; bkcore.hexgl.ShipControls.prototype.boosterCheck = function(dt) { if(!this.collisionMap || !this.collisionMap.loaded) return false; this.boost -= this.boosterDecay * dt; if(this.boost < 0) this.boost = 0.0; var x = Math.round(this.collisionMap.pixels.width/2 + this.dummy.position.x * this.collisionPixelRatio); var z = Math.round(this.collisionMap.pixels.height/2 + this.dummy.position.z * this.collisionPixelRatio); var pos = new THREE.Vector3(x, 0, z); var color = this.collisionMap.getPixel(x, z); if(color.r == 255 && color.g < 127 && color.b < 127) this.boost = this.boosterSpeed; this.movement.z += this.boost * dt; } bkcore.hexgl.ShipControls.prototype.collisionCheck = function(dt) { if(!this.collisionDetection || !this.collisionMap || !this.collisionMap.loaded) return false; if(this.shieldDelay > 0) this.shieldDelay -= dt; this.collision.left = false; this.collision.right = false; this.collision.front = false; var x = Math.round(this.collisionMap.pixels.width/2 + this.dummy.position.x * this.collisionPixelRatio); var z = Math.round(this.collisionMap.pixels.height/2 + this.dummy.position.z * this.collisionPixelRatio); var pos = new THREE.Vector3(x, 0, z); //console.log({c: this.collisionMap.getPixel(414, 670), d: this.dummy.position, x: x, y: y, p: this.collisionMap.getPixel(x, y)}) var collision = this.collisionMap.getPixelBilinear(x, z); if(collision.r < 255) { // Shield var sr = (this.getRealSpeed() / this.maxSpeed); this.shield -= sr * sr * 0.8 * this.shieldDamage; // Repulsion this.repulsionVLeft.set(1,0,0); this.repulsionVRight.set(-1,0,0); this.dummy.matrix.rotateAxis(this.repulsionVLeft); this.dummy.matrix.rotateAxis(this.repulsionVRight); this.repulsionVLeft.multiplyScalar(this.repulsionVScale); this.repulsionVRight.multiplyScalar(this.repulsionVScale); var lPos = this.repulsionVLeft.addSelf(pos); var rPos = this.repulsionVRight.addSelf(pos); var lCol = this.collisionMap.getPixel(Math.round(lPos.x), Math.round(lPos.z)).r; var rCol = this.collisionMap.getPixel(Math.round(rPos.x), Math.round(rPos.z)).r; this.repulsionAmount = Math.max(0.8, Math.min(this.repulsionCap, this.speed * this.repulsionRatio ) ); if(rCol > lCol) {// Repulse right this.repulsionForce.x += -this.repulsionAmount; this.collision.left = true; } else if(rCol < lCol) {// Repulse left this.repulsionForce.x += this.repulsionAmount; this.collision.right = true; } else { //console.log(collision.r+" -- "+fCol+" @ "+lCol+" / "+rCol); this.repulsionForce.z += -this.repulsionAmount*4; this.collision.front = true; this.speed = 0; } this.speed *= this.collisionSpeedDecrease; this.speed *= (1-this.collisionSpeedDecreaseCoef*(1-collision.r/255)); this.boost = 0; return true; } else { return false; } } bkcore.hexgl.ShipControls.prototype.heightCheck = function(dt) { if(!this.heightMap || !this.heightMap.loaded) return false; var x = this.heightMap.pixels.width/2 + this.dummy.position.x * this.heightPixelRatio; var z = this.heightMap.pixels.height/2 + this.dummy.position.z * this.heightPixelRatio; var height = this.heightMap.getPixelFBilinear(x, z) / this.heightScale + this.heightBias; var color = this.heightMap.getPixel(x, z); if(height < 16777) { var delta = (height - this.dummy.position.y); if(delta > 0) { this.movement.y += delta; } else { this.movement.y += delta * this.heightLerp; } } // gradient this.gradientVector.set(0,0,5); this.dummy.matrix.rotateAxis(this.gradientVector); this.gradientVector.addSelf(this.dummy.position); x = this.heightMap.pixels.width/2 + this.gradientVector.x * this.heightPixelRatio; z = this.heightMap.pixels.height/2 + this.gradientVector.z * this.heightPixelRatio; var nheight = this.heightMap.getPixelFBilinear(x, z) / this.heightScale + this.heightBias; if(nheight < 16777) this.gradientTarget = -Math.atan2(nheight-height, 5.0)*this.gradientScale; // tilt this.tiltVector.set(5,0,0); this.dummy.matrix.rotateAxis(this.tiltVector); this.tiltVector.addSelf(this.dummy.position); x = this.heightMap.pixels.width/2 + this.tiltVector.x * this.heightPixelRatio; z = this.heightMap.pixels.height/2 + this.tiltVector.z * this.heightPixelRatio; nheight = this.heightMap.getPixelFBilinear(x, z) / this.heightScale + this.heightBias; if(nheight >= 16777) // If right project out of bounds, try left projection { this.tiltVector.subSelf(this.dummy.position).multiplyScalar(-1).addSelf(this.dummy.position); x = this.heightMap.pixels.width/2 + this.tiltVector.x * this.heightPixelRatio; z = this.heightMap.pixels.height/2 + this.tiltVector.z * this.heightPixelRatio; nheight = this.heightMap.getPixelFBilinear(x, z) / this.heightScale + this.heightBias; } if(nheight < 16777) this.tiltTarget = Math.atan2(nheight-height, 5.0)*this.tiltScale; }; bkcore.hexgl.ShipControls.prototype.getRealSpeed = function(scale) { return Math.round( (this.speed+this.boost) * (scale == undefined ? 1 : scale) ); }; bkcore.hexgl.ShipControls.prototype.getRealSpeedRatio = function() { return Math.min( this.maxSpeed, this.speed+this.boost ) / this.maxSpeed; }; bkcore.hexgl.ShipControls.prototype.getSpeedRatio = function() { return (this.speed+this.boost)/ this.maxSpeed; }; bkcore.hexgl.ShipControls.prototype.getBoostRatio = function() { return this.boost / this.boosterSpeed; }; bkcore.hexgl.ShipControls.prototype.getShieldRatio = function() { return this.shield / this.maxShield; }; bkcore.hexgl.ShipControls.prototype.getShield = function(scale) { return Math.round( this.shield * (scale == undefined ? 1 : scale) ); };
!function(a){a.fn.datepicker.dates["rs-latin"]={days:["Nedelja","Ponedeljak","Utorak","Sreda","\u010cetvrtak","Petak","Subota","Nedelja"],daysShort:["Ned","Pon","Uto","Sre","\u010cet","Pet","Sub","Ned"],daysMin:["N","Po","U","Sr","\u010c","Pe","Su","N"],months:["Januar","Februar","Mart","April","Maj","Jun","Jul","Avgust","Septembar","Oktobar","Novembar","Decembar"],monthsShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"],today:"Danas",weekStart:1,format:"dd.mm.yyyy"}}(jQuery);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S12.7_A1_T3; * @section: 12.7; * @assertion: Appearing of continue without an IterationStatement leads to syntax error; * @description: Checking if laballed "continue" with no IterationStatement, placed into a block, fails; * @negative; */ LABEL : x=3.14; ////////////////////////////////////////////////////////////////////////////// //CHECK#1 { var x=1; continue LABEL; var y=2; } // //////////////////////////////////////////////////////////////////////////////
var is = require('./is') module.exports = { arr: toArray , obj: toObject } function toArray(d){ return Array.prototype.slice.call(d, 0) } function toObject(d) { var by = 'id' , o = {} return arguments.length == 1 ? (by = d, reduce) : reduce.apply(this, arguments) function reduce(p,v,i){ if (i === 0) p = {} p[is.fn(by) ? by(v, i) : v[by]] = v return p } }
'use strict'; const blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); const setupTestHooks = blueprintHelpers.setupTestHooks; const emberNew = blueprintHelpers.emberNew; const emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; const modifyPackages = blueprintHelpers.modifyPackages; const chai = require('ember-cli-blueprint-test-helpers/chai'); const expect = chai.expect; const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest'); const fixture = require('../helpers/fixture'); describe('Blueprint: controller-test', function() { setupTestHooks(this); describe('in app', function() { beforeEach(function() { return emberNew(); }); describe('with [email protected]', function() { beforeEach(function() { modifyPackages([ { name: 'ember-qunit', delete: true }, { name: 'ember-cli-qunit', dev: true }, ]); generateFakePackageManifest('ember-cli-qunit', '4.1.0'); }); it('controller-test foo', function() { return emberGenerateDestroy(['controller-test', 'foo'], _file => { expect(_file('tests/unit/controllers/foo-test.js')).to.equal( fixture('controller-test/default.js') ); }); }); it('controller-test foo/bar', function() { return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => { expect(_file('tests/unit/controllers/foo/bar-test.js')).to.equal( fixture('controller-test/default-nested.js') ); }); }); }); describe('with [email protected]', function() { beforeEach(function() { modifyPackages([ { name: 'ember-qunit', delete: true }, { name: 'ember-cli-qunit', dev: true }, ]); generateFakePackageManifest('ember-cli-qunit', '4.2.0'); }); it('controller-test foo', function() { return emberGenerateDestroy(['controller-test', 'foo'], _file => { expect(_file('tests/unit/controllers/foo-test.js')).to.equal( fixture('controller-test/rfc232.js') ); }); }); it('controller-test foo/bar', function() { return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => { expect(_file('tests/unit/controllers/foo/bar-test.js')).to.equal( fixture('controller-test/rfc232-nested.js') ); }); }); }); describe('with [email protected]', function() { beforeEach(function() { modifyPackages([ { name: 'ember-qunit', delete: true }, { name: 'ember-cli-mocha', dev: true }, ]); generateFakePackageManifest('ember-cli-mocha', '0.11.0'); }); it('controller-test foo for mocha', function() { return emberGenerateDestroy(['controller-test', 'foo'], _file => { expect(_file('tests/unit/controllers/foo-test.js')).to.equal( fixture('controller-test/mocha.js') ); }); }); it('controller-test foo/bar for mocha', function() { return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => { expect(_file('tests/unit/controllers/foo/bar-test.js')).to.equal( fixture('controller-test/mocha-nested.js') ); }); }); }); describe('with [email protected]', function() { beforeEach(function() { modifyPackages([ { name: 'ember-qunit', delete: true }, { name: 'ember-cli-mocha', dev: true }, ]); generateFakePackageManifest('ember-cli-mocha', '0.12.0'); }); it('controller-test foo', function() { return emberGenerateDestroy(['controller-test', 'foo'], _file => { expect(_file('tests/unit/controllers/foo-test.js')).to.equal( fixture('controller-test/mocha-0.12.js') ); }); }); it('controller-test foo/bar', function() { return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => { expect(_file('tests/unit/controllers/foo/bar-test.js')).to.equal( fixture('controller-test/mocha-0.12-nested.js') ); }); }); }); describe('with [email protected]', function() { beforeEach(function() { modifyPackages([{ name: 'ember-qunit', delete: true }, { name: 'ember-mocha', dev: true }]); generateFakePackageManifest('ember-mocha', '0.14.0'); }); it('controller-test foo', function() { return emberGenerateDestroy(['controller-test', 'foo'], _file => { expect(_file('tests/unit/controllers/foo-test.js')).to.equal( fixture('controller-test/mocha-rfc232.js') ); }); }); it('controller-test foo/bar', function() { return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => { expect(_file('tests/unit/controllers/foo/bar-test.js')).to.equal( fixture('controller-test/mocha-rfc232-nested.js') ); }); }); }); }); describe('in addon', function() { beforeEach(function() { return emberNew({ target: 'addon' }) .then(() => modifyPackages([ { name: 'ember-qunit', delete: true }, { name: 'ember-cli-qunit', dev: true }, ]) ) .then(() => generateFakePackageManifest('ember-cli-qunit', '4.1.0')); }); it('controller-test foo', function() { return emberGenerateDestroy(['controller-test', 'foo'], _file => { expect(_file('tests/unit/controllers/foo-test.js')).to.equal( fixture('controller-test/default.js') ); }); }); it('controller-test foo/bar', function() { return emberGenerateDestroy(['controller-test', 'foo/bar'], _file => { expect(_file('tests/unit/controllers/foo/bar-test.js')).to.equal( fixture('controller-test/default-nested.js') ); }); }); }); });
/** * Created by Shreya on 7/19/2017. */ function checkusername() { var v=document.getElementById('username').value; if(v!=null){ var url="uniqueusername?val="+v; if(window.XMLHttpRequest){ request=new XMLHttpRequest(); } else if(window.ActiveXObject){ request=new ActiveXObject("Microsoft.XMLHTTP"); } try{ request.onreadystatechange=getInfo; request.open("POST",url,true); request.send(); }catch(e){alert("Unable to connect to server");} } else document.getElementById('status').innerHTML="User name can't be null"; } function getInfo(){ if(request.readyState==4){ var val=request.responseText; document.getElementById("status").innerHTML=val; if(val==="not available") { userflag=1; document.getElementById("register").disabled=true; } else { userflag=0; document.getElementById("register").disabled=false; } } }
var path = require('path'); var createPattern = function(file) { return {pattern: file, included: true, served: true, watched: false}; }; var initHappen = function(files) { files.unshift(createPattern(require.resolve('happen'))); }; initHappen.$inject = ['config.files']; module.exports = { 'framework:happen': ['factory', initHappen] };
var SkipLastObservable = (function (__super__) { inherits(SkipLastObservable, __super__); function SkipLastObservable(source, c) { this.source = source; this._c = c; __super__.call(this); } SkipLastObservable.prototype.subscribeCore = function (o) { return this.source.subscribe(new SkipLastObserver(o, this._c)); }; return SkipLastObservable; }(ObservableBase)); var SkipLastObserver = (function (__super__) { inherits(SkipLastObserver, __super__); function SkipLastObserver(o, c) { this._o = o; this._c = c; this._q = []; __super__.call(this); } SkipLastObserver.prototype.next = function (x) { this._q.push(x); this._q.length > this._c && this._o.onNext(this._q.shift()); }; SkipLastObserver.prototype.error = function (e) { this._o.onError(e); }; SkipLastObserver.prototype.completed = function () { this._o.onCompleted(); }; return SkipLastObserver; }(AbstractObserver)); /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } return new SkipLastObservable(this, count); };
//>>built define("dojo/_base/array dojo/aspect dojo/_base/declare dojo/dom dojo/dom-attr dojo/dom-construct dojo/dom-geometry dojo/dom-style dojo/has dojo/keys dojo/_base/lang dojo/on ./place ./BackgroundIframe ./Viewport ./main dojo/touch".split(" "),function(w,x,e,y,z,r,k,p,A,t,m,u,v,B,C,D){function E(){this._popupWrapper&&(r.destroy(this._popupWrapper),delete this._popupWrapper)}e=e(null,{_stack:[],_beginZIndex:1E3,_idGen:1,_repositionAll:function(){if(this._firstAroundNode){var a=this._firstAroundPosition, b=k.position(this._firstAroundNode,!0),c=b.x-a.x,a=b.y-a.y;if(c||a)for(this._firstAroundPosition=b,b=0;b<this._stack.length;b++){var d=this._stack[b].wrapper.style;d.top=parseFloat(d.top)+a+"px";"auto"==d.right?d.left=parseFloat(d.left)+c+"px":d.right=parseFloat(d.right)-c+"px"}this._aroundMoveListener=setTimeout(m.hitch(this,"_repositionAll"),c||a?10:50)}},_createWrapper:function(a){var b=a._popupWrapper,c=a.domNode;b||(b=r.create("div",{"class":"dijitPopup",style:{display:"none"},role:"region", "aria-label":a["aria-label"]||a.label||a.name||a.id},a.ownerDocumentBody),b.appendChild(c),c=c.style,c.display="",c.visibility="",c.position="",c.top="0px",a._popupWrapper=b,x.after(a,"destroy",E,!0),"ontouchend"in document&&u(b,"touchend",function(a){/^(input|button|textarea)$/i.test(a.target.tagName)||a.preventDefault()}),b.dojoClick=!0);return b},moveOffScreen:function(a){var b=this._createWrapper(a);a=k.isBodyLtr(a.ownerDocument);var c={visibility:"hidden",top:"-9999px",display:""};c[a?"left": "right"]="-9999px";c[a?"right":"left"]="auto";p.set(b,c);return b},hide:function(a){var b=this._createWrapper(a);p.set(b,{display:"none",height:"auto",overflowY:"visible",border:""});a=a.domNode;"_originalStyle"in a&&(a.style.cssText=a._originalStyle)},getTopPopup:function(){for(var a=this._stack,b=a.length-1;0<b&&a[b].parent===a[b-1].widget;b--);return a[b]},open:function(a){for(var b=this._stack,c=a.popup,d=c.domNode,f=a.orient||["below","below-alt","above","above-alt"],F=a.parent?a.parent.isLeftToRight(): k.isBodyLtr(c.ownerDocument),h=a.around,q=a.around&&a.around.id?a.around.id+"_dropdown":"popup_"+this._idGen++;b.length&&(!a.parent||!y.isDescendant(a.parent.domNode,b[b.length-1].widget.domNode));)this.close(b[b.length-1].widget);var g=this.moveOffScreen(c);c.startup&&!c._started&&c.startup();var l,n=k.position(d);if("maxHeight"in a&&-1!=a.maxHeight)l=a.maxHeight||Infinity;else{l=C.getEffectiveBox(this.ownerDocument);var e=h?k.position(h,!1):{y:a.y-(a.padding||0),h:2*(a.padding||0)};l=Math.floor(Math.max(e.y, l.h-(e.y+e.h)))}n.h>l&&(n=p.getComputedStyle(d),p.set(g,{overflowY:"scroll",height:l+"px",border:n.borderLeftWidth+" "+n.borderLeftStyle+" "+n.borderLeftColor}),d._originalStyle=d.style.cssText,d.style.border="none");z.set(g,{id:q,style:{zIndex:this._beginZIndex+b.length},"class":"dijitPopup "+(c.baseClass||c["class"]||"").split(" ")[0]+"Popup",dijitPopupParent:a.parent?a.parent.id:""});0==b.length&&h&&(this._firstAroundNode=h,this._firstAroundPosition=k.position(h,!0),this._aroundMoveListener=setTimeout(m.hitch(this, "_repositionAll"),50));A("config-bgIframe")&&!c.bgIframe&&(c.bgIframe=new B(g));q=c.orient?m.hitch(c,"orient"):null;f=h?v.around(g,h,f,F,q):v.at(g,a,"R"==f?["TR","BR","TL","BL"]:["TL","BL","TR","BR"],a.padding,q);g.style.visibility="visible";d.style.visibility="visible";d=[];d.push(u(g,"keydown",m.hitch(this,function(b){if(b.keyCode==t.ESCAPE&&a.onCancel)b.stopPropagation(),b.preventDefault(),a.onCancel();else if(b.keyCode==t.TAB&&(b.stopPropagation(),b.preventDefault(),(b=this.getTopPopup())&&b.onCancel))b.onCancel()}))); c.onCancel&&a.onCancel&&d.push(c.on("cancel",a.onCancel));d.push(c.on(c.onExecute?"execute":"change",m.hitch(this,function(){var a=this.getTopPopup();if(a&&a.onExecute)a.onExecute()})));b.push({widget:c,wrapper:g,parent:a.parent,onExecute:a.onExecute,onCancel:a.onCancel,onClose:a.onClose,handlers:d});if(c.onOpen)c.onOpen(f);return f},close:function(a){for(var b=this._stack;a&&w.some(b,function(b){return b.widget==a})||!a&&b.length;){var c=b.pop(),d=c.widget,f=c.onClose;d.bgIframe&&(d.bgIframe.destroy(), delete d.bgIframe);if(d.onClose)d.onClose();for(var e;e=c.handlers.pop();)e.remove();d&&d.domNode&&this.hide(d);f&&f()}0==b.length&&this._aroundMoveListener&&(clearTimeout(this._aroundMoveListener),this._firstAroundNode=this._firstAroundPosition=this._aroundMoveListener=null)}});return D.popup=new e});
'use strict' const cloneDeep = require('lodash.clonedeep') const merge = require('lodash.merge') const pluginRegistry = require('./pluginRegistry') function freezeTheme (theme) { const queue = [theme] while (queue.length > 0) { const object = queue.shift() Object.freeze(object) for (const key of Object.keys(object)) { const value = object[key] if (value !== null && typeof value === 'object') { queue.push(value) } } } return theme } const defaultTheme = freezeTheme({ boolean: { open: '', close: '' }, circular: '[Circular]', date: { invalid: 'invalid', value: { open: '', close: '' } }, diffGutters: { actual: '- ', expected: '+ ', padding: ' ' }, error: { ctor: { open: '(', close: ')' }, name: { open: '', close: '' } }, function: { name: { open: '', close: '' }, stringTag: { open: '', close: '' } }, global: { open: '', close: '' }, item: { after: ',', customFormat: null, increaseValueIndent: false }, list: { openBracket: '[', closeBracket: ']' }, mapEntry: { after: ',', separator: ' => ' }, maxDepth: '…', null: { open: '', close: '' }, number: { open: '', close: '' }, object: { openBracket: '{', closeBracket: '}', ctor: { open: '', close: '' }, stringTag: { open: '@', close: '' }, secondaryStringTag: { open: '@', close: '' } }, property: { after: ',', customFormat: null, keyBracket: { open: '[', close: ']' }, separator: ': ', increaseValueIndent: false }, regexp: { source: { open: '/', close: '/' }, flags: { open: '', close: '' }, separator: '---' }, stats: { separator: '---' }, string: { open: '', close: '', line: { open: "'", close: "'", escapeQuote: "'" }, multiline: { start: '`', end: '`', escapeQuote: '``' }, controlPicture: { open: '', close: '' }, diff: { insert: { open: '', close: '' }, delete: { open: '', close: '' }, equal: { open: '', close: '' }, insertLine: { open: '', close: '' }, deleteLine: { open: '', close: '' } } }, symbol: { open: '', close: '' }, typedArray: { bytes: { open: '', close: '' } }, undefined: { open: '', close: '' } }) const pluginRefs = new Map() pluginRefs.count = 0 const normalizedPluginThemes = new Map() function normalizePlugins (plugins) { if (!Array.isArray(plugins) || plugins.length === 0) return null const refs = [] const themes = [] for (const fromPlugin of pluginRegistry.getThemes(plugins)) { if (!pluginRefs.has(fromPlugin.name)) { pluginRefs.set(fromPlugin.name, pluginRefs.count++) } refs.push(pluginRefs.get(fromPlugin.name)) themes.push(fromPlugin.theme) } const ref = refs.join('.') if (normalizedPluginThemes.has(ref)) { return { ref, theme: normalizedPluginThemes.get(ref) } } const theme = freezeTheme(themes.reduce((acc, pluginTheme) => { return merge(acc, pluginTheme) }, cloneDeep(defaultTheme))) normalizedPluginThemes.set(ref, theme) return {ref, theme} } const normalizedCache = new WeakMap() function normalize (options) { options = Object.assign({plugins: [], theme: null}, options) const normalizedPlugins = normalizePlugins(options.plugins) if (!options.theme) { return normalizedPlugins ? normalizedPlugins.theme : defaultTheme } const entry = normalizedCache.get(options.theme) || {theme: null, withPlugins: new Map()} if (!normalizedCache.has(options.theme)) normalizedCache.set(options.theme, entry) if (normalizedPlugins) { if (entry.withPlugins.has(normalizedPlugins.ref)) { return entry.withPlugins.get(normalizedPlugins.ref) } const theme = freezeTheme(merge(cloneDeep(normalizedPlugins.theme), options.theme)) entry.withPlugins.set(normalizedPlugins.ref, theme) return theme } if (!entry.theme) { entry.theme = freezeTheme(merge(cloneDeep(defaultTheme), options.theme)) } return entry.theme } exports.normalize = normalize const modifiers = new WeakMap() function addModifier (descriptor, modifier) { if (modifiers.has(descriptor)) { modifiers.get(descriptor).add(modifier) } else { modifiers.set(descriptor, new Set([modifier])) } } exports.addModifier = addModifier const modifierCache = new WeakMap() const originalCache = new WeakMap() function applyModifiers (descriptor, theme) { if (!modifiers.has(descriptor)) return theme return Array.from(modifiers.get(descriptor)).reduce((prev, modifier) => { const cache = modifierCache.get(modifier) || new WeakMap() if (!modifierCache.has(modifier)) modifierCache.set(modifier, cache) if (cache.has(prev)) return cache.get(prev) const modifiedTheme = cloneDeep(prev) modifier(modifiedTheme) freezeTheme(modifiedTheme) cache.set(prev, modifiedTheme) originalCache.set(modifiedTheme, theme) return modifiedTheme }, theme) } exports.applyModifiers = applyModifiers function applyModifiersToOriginal (descriptor, theme) { return applyModifiers(descriptor, originalCache.get(theme) || theme) } exports.applyModifiersToOriginal = applyModifiersToOriginal
/* node ./test/twitterstream.js todo test - various errors, should reconnect */ var twitterstream = require('../lib/twitterstream') ,config = require('../config.js') ; /* var level = require('level')(__dirname+'/../'+config.leveldb.engines) ,subLevel = require('level-sublevel')(level) ,articlesDb = subLevel.sublevel('articles') ,lev = require('fast-levenshtein') */ //var google = require('google'); var GoogleSearch = require('google-search') ,googleSearch = new GoogleSearch({ key: config.google.key ,cx: config.google.cx }); var s = twitterstream('https://stream.twitter.com/1.1/statuses/filter.json',{ data: { locations: '-170.534369,23.830106,-52.497261,70.416383' // us/ca ,track: '#KristenStewart' //locations: '-122.75,36.8,-121.75,37.8' // sf //follow: 'jewelmint' //track: 'pizza' } }) .on('softerror',function(err){ console.log('softerror',err); }) .on('error',function(err){ console.log('error',err); }) .on('data',function(data){ if (data.entities.hashtags && data.entities.hashtags.length) console.log('HASHTAGS\n',data.entities.hashtags); console.log(JSON.stringify(data)+'\n'); //console.log('twitterstream test data',data); var tweet = data ,importantWords = [] tweet.text.split(' ').forEach(function(word){ if (word && word.charAt(0) == word.charAt(0).toUpperCase() && /[a-zA-Z]/.test(word.charAt(0))) importantWords.push(word); }); if (importantWords.length > 3) { var search = importantWords.join(' '); googleSearch.build({ q: search, start: 0, //fileType: 'pdf', //gl: 'tr', //geolocation, //lr: 'lang_tr', num: 1, siteSearch: 'http://www.luckyshops.com' },function(err,data) { //console.log(err,data); //console.log('\nwefwefwe'); }); /* var search = 'site:www.luckyshops.com '+importantWords.join(' '); google(search,function(err,next,links){ if (err) return console.log('ERROR',err); if (!links[0]) return; //s.destroy(); //console.log(tweet.text+'\n\n'+search+'\n\n'+JSON.stringify(links[0])+'\n\n'); console.log(tweet.user.screen_name+': '+tweet.text); console.log('LuckyMagazine: @'+tweet.user.screen_name+' Check this out! <a href="'+links[0].link+'">'+links[0].title+'</a>'); console.log('\n\n'); }); */ } /* var tweet = data; s.destroy(); articlesDb.createReadStream({}).on('data',function(data){ var articleTitle = JSON.parse(data.value).postTitle; lev.getAsync(articleTitle, tweet.text, function (err, distance) { if (err) return console.log(err); //console.log(articleTitle); //console.log(err, distance); if (distance < 50) console.log(distance+'\n'+articleTitle+'\n'+tweet.text+'\n\n'); }); }) */ }) ; /* twitterstream('https://stream.twitter.com/1.1/statuses/sample.json',{ data: {} }) .on('softerror',function(err){ console.log('softerror',err); }) .on('error',function(err){ console.log('error',err); }) .on('data',function(data){ console.log('data',data.toString()); }) ; */
describe('{{ module}}.{{ name }} directive', function() { 'use strict'; var $compile, $scope, element, isolateScope; // Include the main module beforeEach(module('{{module}}', 'templatesModule')); //Mock dependencies beforeEach(module(function($provide) { var serviceMock = jasmine.createSpy('serviceMock') .and.returnValue(...); $provide.value('service', serviceMock); })); //Mock directive's controller beforeEach(module(function($controllerProvider) { $controllerProvider .register('{{name}}Controller', function() { this.timeZoneOffset = mockTimeZoneOffset; this.timeZone = mockTimeZone; }); })); // Get useful references beforeEach(inject(function($injector) { $scope = $injector.get('$rootScope').$new(); $compile = $injector.get('$compile'); })); beforeEach(function() { element = $compile('<your-directive></your-directive>')($scope); $scope.$digest(); isolateScope = element.isolateScope(); }); it('should ....', function() { expect(element).toBe(...); expect(element).toEqual(...); }); describe('alternative flows', function() { it('should ...', function() { expect(element).toBe(...); expect(element).toEqual(...); }); }); });
import React from 'react'; import jQuery from 'jquery'; import {addTopic} from '../lib/client'; import {redirectURL} from '../lib/utils'; import MarkdownEditor from './MarkdownEditor'; export default class TopicEditor extends React.Component{ constructor(props){ super(props); this.state = props.topic || {}; } handleChange(name, e){ this.setState({[name]: e.target.value}); } // 点击‘保存’ handleSubmit(e){ const $btn = jQuery(e.target); $btn.button('loading'); this.props.onSave(this.state,() => { $btn.button('reset'); }); } render(){ return( <div className="panel panel-primary"> <div className="panel-heading">{this.props.title}</div> <div className="panel-body"> <form> <div className="form-group"> <label htmlFor="ipt-title">标题</label> <input type="text" className="form-control" id="ipt-title" value={this.state.title} onChange={this.handleChange.bind(this, 'title')} placeholder="" /> </div> <div className="form-group"> <label htmlFor="ipt-tags">标签</label> <input type="text" className="form-control" id="ipt-tags" value={this.state.tags} onChange={this.handleChange.bind(this, 'tags')} placeholder="" /> <p className="help-block">多个标签使用半角都好分隔</p> </div> <div className="form-group"> <label htmlFor="ipt-content">内容</label> <MarkdownEditor value={this.state.content} onChange={this.handleChange.bind(this, 'content')} /> </div> <button type="button" className="btn btn-primary" onClick={this.handleSubmit.bind(this)}>保存</button> </form> </div> </div> ); } }
"use strict"; var GraphModel = require('./GraphModel'); var pageNodeDesc = { // Node attributes description "word": { type: "string" }, "doc_count": { type: "integer" } }; var pageEdgeDesc = { "weight": { type: "integer" } }; module.exports = function PageGraph(){ return new GraphModel(pageNodeDesc, pageEdgeDesc, {defaultedgetype: "undirected"}); };
import React from 'react' import ReactDom from 'react-dom' import Input, * as inputHelper from '../src/index' import './css/bootstrap/bootstrap.min.css' import './css/site.css' //optional: setting up global config -- begin inputHelper.config({ validationStateProperty: 'validation', // the property name in the state object to link the validation useWraper: true, // uses wrappers for the input, built in wrappers are bootStrap styles errorCssClass : 'has-error', // the class applied when has error wraningCssClass : 'has-warning', // the class applied when has warning successCssClass : 'has-success', // the class applied when has success feedbackCssClass : 'has-feedback', // the class applied when has feedback propsPassThrough : true, // default to true, pass every props to the internal components mutate : false, // default to false, not allow instance to be changed by this component, set to true it will put the error indicator into the instance when validation failed, errorIndicatorKey : '_hasError', //the property name of the error indicator put in to the instance when mutate = true errorMessageKey : '_errors', //the property name of the error message collection put in to the instance when mutate = true classNameKey : '_class', // the property name used to find the validation className rulesKey : '_rules' // the property name used to find the validation rules }) // -- end //additional code needed to enable supporting of datepicker -- begin import DatePicker from 'react-datepicker' import moment from 'moment' import validator from 'validate.js' inputHelper.extend('datepicker', { wrapper: 'div', //the wrapper component to wrap the component, this will wrap this datepicker with bootstrap style, set to null to disable wrapping. wrapperClass: 'form-group', // the className to put into the wrapper className: 'form-control', //the className to put into the component component: DatePicker, //the component reference, react class or string such as 'input' valueProp: 'selected', // the prop name used to assign value to the component, this date picker uses 'selected' instead of 'value' defaultProps: { dateFormat: 'MM/DD/YYYY' }, // the default props that the component needs getValueOnChange: (e, props) => e.toString(), // to internally handle the event in onChange, otherwise it will try to retrieve e.target.value includedLabel : false, // indicates the component does not include a label props it self, we'll renderer the label for it setValue: (value, props) => isNaN(Date.parse(value))? null:moment(value), //the handler to pass the value from instance to the component propsMap: [{from: 'placeholder', to: 'placeholderText'}] //map a different name for the default properties }) validator.extend(validator.validators.datetime, { parse: function(value, options) { return +moment.utc(value); }, format: function(value, options) { var format = options.dateOnly ? "MM/DD/YYYY" : "MM/DD/YYYY hh:mm:ss"; return moment.utc(value).format(format); } }); //additional code needed to enable supporting of datepicker -- end //register some global validation rules -- begin inputHelper.registerClasses({ ExampleTestTarget: { textarea: {presence: true}, select: {presence: true, format: /^[1,3]$/}, datetime: {datetime: true, presence: true} } } ) // -- end //Example component class BasicInputTest extends React.Component { constructor(){ super() this.state= {target: {_class:"ExampleTestTarget", text:"", select:"2", checkbox:true, test:0, radio: "2"}, validation: {}, group2: {}} } doValidate1(){ inputHelper.validate(this, [this.state.target]) .then( () => { //do something when no errors }, (errorMessage) => { //do something with the error message } ) .catch((err) => console.log(err)) } doValidate2(){ inputHelper.validate(this, [this.state.target], null, ["group2"]) .then( () => { //do something when no errors }, (errorMessage) => { //do something with the error message } ) .catch((err) => console.log(err)) } doValidateAll(){ inputHelper.validate(this, [this.state.target], null, ["validation", "group2"]) .then( () => { //do something when no errors }, (errorMessage) => { //do something with the error message } ) .catch((err) => console.log(err)) } clear(){ this.setState({validation:{}, group2:{}}) } render(){ return <div className="container"> <Input type="text" placeholder="text" label="text (Group 1)" rules={{presence:true}} instance={this.state.target} propertyKey="text" validate={this.state.validation} /> <Input type="email" placeholder="select" label="email (Group 1)" rules={{presence:true, email:true}} instance={this.state.target} propertyKey="email" validate={this.state.validation} /> <Input type="password" placeholder="password" label="password (Group 1)" rules={{presence:true}} instance={this.state.target} propertyKey="password" validate={this.state.validation} /> <Input type="select" placeholder="select" label="select (Group 2, using global class rules)" instance={this.state.target} propertyKey="select" options={[{text:"Option1", value: 1}, {text:"Option2", value: 2}]} validate={this.state.group2} /> <Input type="textarea" placeholder="textarea" label="textarea (Group 2, using global class rules)" instance={this.state.target} propertyKey="textarea" validate={this.state.group2} /> <Input type="datepicker" noWrap placeholder="datepicker" label="Extened Datepicker (Group 2, using global class rules)" instance={this.state.target} propertyKey="datetime" validate={this.state.group2} /> <br/> <Input type="checkbox" label="checkbox" instance={this.state.target} propertyKey="checkbox" validate={this.state.validation} /> <Input type="radio" label="raidio_1" name="Radio" value="1" rules={{presence:true}} instance={this.state.target} propertyKey="radio" validate={this.state.validation} /> <span/> <Input type="radio" label="raidio_2" name="Radio" value="2" rules={{presence:true}} instance={this.state.target} propertyKey="radio" validate={this.state.validation} /> <br/> <button onClick={this.doValidate1.bind(this)}>Validate Group 1</button> <span>&nbsp;</span> <button onClick={this.doValidate2.bind(this)}>Validate Group 2</button> <span>&nbsp;</span> <button onClick={this.doValidateAll.bind(this)}>Validate All</button> <span>&nbsp;</span> <button onClick={this.clear.bind(this)}>Clear</button> <span>&nbsp;</span> </div> } } class InputTest extends React.Component { constructor(){ super() } render(){ return <div> <h2><a target="_blank" href="https://github.com/Jishun/react-validated-input">react-validated-input</a></h2> <h3>Examples (<a target="_blank" href="https://github.com/Jishun/react-validated-input/blob/master/project/test/entry.js">View Source code</a>):</h3> <BasicInputTest/> </div> } } ReactDom.render(<InputTest/>, document.getElementById('content'));
var searchData= [ ['iconimageview',['iconImageView',['../interface_category_detail_view_controller.html#a7ae5baab3f989c4c470e73f29a132f2c',1,'CategoryDetailViewController']]], ['iconname',['iconName',['../interface_checklist.html#a8cf1d13a9c2780d67fca7df8e02864c4',1,'Checklist']]], ['image',['image',['../interface_checklist_item.html#a3542e7f7f0c4004017b836edb3f60821',1,'ChecklistItem']]], ['imagefield',['imageField',['../interface_item_detail_view_controller.html#ae3b752dab2cb58398896d2885d8f82c4',1,'ItemDetailViewController']]], ['itemid',['itemId',['../interface_checklist_item.html#a57819dc861cee7c6d6bb35f82ee097d7',1,'ChecklistItem']]], ['items',['items',['../interface_checklist.html#a4be406e9e0444c9a3691c8ea776a855a',1,'Checklist::items()'],['../interface_u_i_picker_action_sheet.html#a89ee574615afe8a3270aa1586fdf3a3e',1,'UIPickerActionSheet::items()']]], ['itemtoedit',['itemToEdit',['../interface_item_detail_view_controller.html#a0c18d4e6c36c06948dca5a76223896b7',1,'ItemDetailViewController']]] ];
!function($) { 'use strict'; $.fn.provePrecision = function(options) { var regex = /^(.)*(\.[0-9]{1,2})?$/; var input = $(this); var value = input.vals(); var enabled = $('body').booleanator(options.enabled); var has = regex.test(value)? 'success' : 'danger'; var validation = (enabled)? has : 'reset'; var message = (validation === 'danger')? options.message : undefined; if (options.debug) { console.groupCollapsed('Validator.provePrecision()', options.field); /* eslint-disable indent */ console.log('options', options); console.log('input', input); console.log('value', value); console.log('enabled', enabled); console.log('validation', validation); console.groupEnd(); /* eslint-enable indent */ } return { field: options.field, validator: options.validator, status: 'validated', validation: validation, message: message }; }; }(window.jQuery);
'use strict'; var fs = require('fs'), tasks = fs.readdirSync('./gulp/tasks/'); tasks.forEach(function (task) { require('./tasks/' + task); });
// ** I18N // Calendar EN language // Author: Mihai Bazon, <[email protected]> // Translator: Fabio Di Bernardini, <[email protected]> // Encoding: any // Distributed under the same terms as the calendar itself. // For translators: please use UTF-8 if possible. We strongly believe that // Unicode is the answer to a real internationalized world. Also please // include your contact information in the header, as can be seen above. // full day names Calendar._DN = new Array ("Domenica", "Luned√¨", "Marted√¨", "Mercoled√¨", "Gioved√¨", "Venerd√¨", "Sabato", "Domenica"); // Please note that the following array of short day names (and the same goes // for short month names, _SMN) isn't absolutely necessary. We give it here // for exemplification on how one can customize the short day names, but if // they are simply the first N letters of the full name you can simply say: // // Calendar._SDN_len = N; // short day name length // Calendar._SMN_len = N; // short month name length // // If N = 3 then this is not needed either since we assume a value of 3 if not // present, to be compatible with translation files that were written before // this feature. // short day names Calendar._SDN = new Array ("Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"); // First day of the week. "0" means display Sunday first, "1" means display // Monday first, etc. Calendar._FD = 1; // full month names Calendar._MN = new Array ("Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Augosto", "Settembre", "Ottobre", "Novembre", "Dicembre"); // short month names Calendar._SMN = new Array ("Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"); // tooltips Calendar._TT = {}; Calendar._TT["INFO"] = "Informazioni sul calendario"; Calendar._TT["ABOUT"] = "DHTML Date/Time Selector\n" + "(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-) "Per gli aggiornamenti: http://www.dynarch.com/projects/calendar/\n" + "Distribuito sotto licenza GNU LGPL. Vedi http://gnu.org/licenses/lgpl.html per i dettagli." + "\n\n" + "Selezione data:\n" + "- Usa \xab, \xbb per selezionare l'anno\n" + "- Usa " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " per i mesi\n" + "- Tieni premuto a lungo il mouse per accedere alle funzioni di selezione veloce."; Calendar._TT["ABOUT_TIME"] = "\n\n" + "Selezione orario:\n" + "- Clicca sul numero per incrementarlo\n" + "- o Shift+click per decrementarlo\n" + "- o click e sinistra o destra per variarlo."; Calendar._TT["PREV_YEAR"] = "Anno prec.(clicca a lungo per il men√π)"; Calendar._TT["PREV_MONTH"] = "Mese prec. (clicca a lungo per il men√π)"; Calendar._TT["GO_TODAY"] = "Oggi"; Calendar._TT["NEXT_MONTH"] = "Pross. mese (clicca a lungo per il men√π)"; Calendar._TT["NEXT_YEAR"] = "Pross. anno (clicca a lungo per il men√π)"; Calendar._TT["SEL_DATE"] = "Seleziona data"; Calendar._TT["DRAG_TO_MOVE"] = "Trascina per spostarlo"; Calendar._TT["PART_TODAY"] = " (oggi)"; // the following is to inform that "%s" is to be the first day of week // %s will be replaced with the day name. Calendar._TT["DAY_FIRST"] = "Mostra prima %s"; // This may be locale-dependent. It specifies the week-end days, as an array // of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1 // means Monday, etc. Calendar._TT["WEEKEND"] = "0"; Calendar._TT["CLOSE"] = "Chiudi"; Calendar._TT["TODAY"] = "Oggi"; Calendar._TT["TIME_PART"] = "(Shift-)Click o trascina per cambiare il valore"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "%d-%m-%Y"; Calendar._TT["TT_DATE_FORMAT"] = "%a:%b:%e"; Calendar._TT["WK"] = "set"; Calendar._TT["TIME"] = "Ora:"; // ** I18N // Calendar EN language // Author: Mihai Bazon, <[email protected]> // Translator: Fabio Di Bernardini, <[email protected]> // Encoding: any // Distributed under the same terms as the calendar itself. // For translators: please use UTF-8 if possible. We strongly believe that // Unicode is the answer to a real internationalized world. Also please // include your contact information in the header, as can be seen above. // full day names Calendar._DN = new Array ("Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"); // Please note that the following array of short day names (and the same goes // for short month names, _SMN) isn't absolutely necessary. We give it here // for exemplification on how one can customize the short day names, but if // they are simply the first N letters of the full name you can simply say: // // Calendar._SDN_len = N; // short day name length // Calendar._SMN_len = N; // short month name length // // If N = 3 then this is not needed either since we assume a value of 3 if not // present, to be compatible with translation files that were written before // this feature. // short day names Calendar._SDN = new Array ("Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"); // full month names Calendar._MN = new Array ("Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Augosto", "Settembre", "Ottobre", "Novembre", "Dicembre"); // short month names Calendar._SMN = new Array ("Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"); // tooltips Calendar._TT = {}; Calendar._TT["INFO"] = "Informazioni sul calendario"; Calendar._TT["ABOUT"] = "DHTML Date/Time Selector\n" + "(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-) "Per gli aggiornamenti: http://www.dynarch.com/projects/calendar/\n" + "Distribuito sotto licenza GNU LGPL. Vedi http://gnu.org/licenses/lgpl.html per i dettagli." + "\n\n" + "Selezione data:\n" + "- Usa \xab, \xbb per selezionare l'anno\n" + "- Usa " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " per i mesi\n" + "- Tieni premuto a lungo il mouse per accedere alle funzioni di selezione veloce."; Calendar._TT["ABOUT_TIME"] = "\n\n" + "Selezione orario:\n" + "- Clicca sul numero per incrementarlo\n" + "- o Shift+click per decrementarlo\n" + "- o click e sinistra o destra per variarlo."; Calendar._TT["PREV_YEAR"] = "Anno prec.(clicca a lungo per il menù)"; Calendar._TT["PREV_MONTH"] = "Mese prec. (clicca a lungo per il menù)"; Calendar._TT["GO_TODAY"] = "Oggi"; Calendar._TT["NEXT_MONTH"] = "Pross. mese (clicca a lungo per il menù)"; Calendar._TT["NEXT_YEAR"] = "Pross. anno (clicca a lungo per il menù)"; Calendar._TT["SEL_DATE"] = "Seleziona data"; Calendar._TT["DRAG_TO_MOVE"] = "Trascina per spostarlo"; Calendar._TT["PART_TODAY"] = " (oggi)"; // the following is to inform that "%s" is to be the first day of week // %s will be replaced with the day name. Calendar._TT["DAY_FIRST"] = "Mostra prima %s"; // This may be locale-dependent. It specifies the week-end days, as an array // of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1 // means Monday, etc. Calendar._TT["WEEKEND"] = "0,6"; Calendar._TT["CLOSE"] = "Chiudi"; Calendar._TT["TODAY"] = "Oggi"; Calendar._TT["TIME_PART"] = "(Shift-)Click o trascina per cambiare il valore"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "%d-%m-%Y"; Calendar._TT["TT_DATE_FORMAT"] = "%a:%b:%e"; Calendar._TT["WK"] = "set"; Calendar._TT["TIME"] = "Ora:";
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- if (typeof (WScript) != "undefined") { WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js", "self"); } var tests = { // Note: each test has name (string) and body (function) properties. // Success is when the body does not throw, failure -- when it throws. test01: { name: "8.12.9.4.a (variation 1): define generic property, check default attrbitues", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo02"; var pd = {}; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: undefined, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test02: { name: "8.12.9.4.a (variation 2): define data property, check default attrbitues", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo03"; var pd = { value: 0 }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 0, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test03: { name: "8.12.9.4.a (variation 3): define generic property by specifying some attributes, check attrbitues", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo02_v3"; var pd = { configurable: true, writable: false }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: undefined, configurable: true, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test04: { name: "8.12.9.4.b: define accessor property, check default attrbitues", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo04"; var getter = function () { return this.Value }; var pd = { get: getter }; Object.defineProperty(o, propertyName, pd); var expected = { get: getter, set: undefined, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test05: { name: "8.12.9.5: re-define property: use descriptor with all fields absent, check that nothing happens to previous descriptor", body: function () { var propertyName = "foo05"; var o = { foo05: 1 }; var pd = {}; Object.defineProperty(o, propertyName, pd); var expected = { writable: true, value: 1, configurable: true, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test06: { name: "8.12.9.6: re-define property: use equal descriptor with data field, check that nothing happens to previous descriptor", body: function () { var propertyName = "foo06"; var o = { foo06: 1 }; var pd = { value: 1 }; Object.defineProperty(o, propertyName, pd); var expected = { writable: true, value: 1, configurable: true, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, // where we are: // - re-define // - desc is not empty // - desc and current are not the same test07: { name: "8.12.9.7.a: re-define property: current descriptor is not configurable and descriptor is configurable, check that it throws TypeError", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo07"; var pd = { value: 0, configurable: false }; Object.defineProperty(o, propertyName, pd); pd = { value: 1, configurable: true }; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError); } }, test08: { name: "8.12.9.7.b (variation 1): re-define property: current descriptor is not configurable and descriptor enumerable is specified and it's negation of current enumerable, check that it throws TypeError", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo08"; var pd = { value: 0 }; Object.defineProperty(o, propertyName, pd); pd = { value: 1, enumerable: true }; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError); } }, test09: { name: "8.12.9.7.b (variation 2): re-define property: current descriptor is not configurable and descriptor enumerable is not specified, check that it does not throw", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo09"; var pd = { value: 0, writable: true }; // set writable to true to avoid throw code path. Object.defineProperty(o, propertyName, pd); pd = { value: 1, writable: false }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 1, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test10: { name: "8.12.9.7.b (variation 3): re-define property: current descriptor is not configurable and descriptor enumerable is same as current enumerable, check that it does not throw", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo10"; var pd = { value: 0, writable: true }; // set writable to true to avoid throw code path. Object.defineProperty(o, propertyName, pd); pd = { value: 1, enumerable: false, writable: false }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 1, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test11: { name: "8.12.9.8: re-define property: descriptor is not empty, generic and is different from current", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo11"; var pd = { value: 0, configurable: true }; Object.defineProperty(o, propertyName, pd); pd = { enumerable: true }; // change enumerable to make sure that descriptor is different from current. Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 0, configurable: true, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, // where we are: // - re-define // - desc is not empty // - desc and current are not the same // - descriptor.IsData != current.IsData test12: { name: "8.12.9.9.a: re-define property: descriptor.IsData != current.IsData and current is not configurable, check that it throws TypeError", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo12"; var pd = { value: 0, configurable: false }; Object.defineProperty(o, propertyName, pd); pd = { get: function () { return this.Value; } }; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError); } }, test13: { name: "8.12.9.9.b (variation 1): re-define property: convert from data to accessor descriptor, check that configurable/enumerable (true) are preserved", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo13"; var pd = { value: 0, configurable: true, enumerable: true }; Object.defineProperty(o, propertyName, pd); var getter = function() { return this.Value; }; pd = { get: getter }; Object.defineProperty(o, propertyName, pd); var expected = { get: getter, set: undefined, configurable: true, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test14: { name: "8.12.9.9.b (variation 2): re-define property: convert from data to accessor descriptor, check that enumerable (false) is preserved", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo14"; var pd = { value: 0, configurable: true, enumerable: false }; Object.defineProperty(o, propertyName, pd); var getter = function () { return this.Value; }; pd = { get: getter }; Object.defineProperty(o, propertyName, pd); var expected = { get: getter, set: undefined, configurable: true, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test15: { name: "8.12.9.9.b (variation 3): re-define property: convert from data to accessor descriptor, check that configurable/enumerable not preserved when specified by descriptor", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo15"; var pd = { value: 0, configurable: true, enumerable: true }; Object.defineProperty(o, propertyName, pd); var getter = function () { return this.Value; }; pd = { get: getter, configurable: false }; Object.defineProperty(o, propertyName, pd); var expected = { get: getter, set: undefined, configurable: false, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test16: { name: "8.12.9.9.c (variation 1): re-define property: convert from accessor to data descriptor, check that configurable/enumerable (true) are preserved", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo16"; var pd = { set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; }, configurable: true, enumerable: true }; Object.defineProperty(o, propertyName, pd); pd = { value: 1 }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 1, configurable: true, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test17: { name: "8.12.9.9.c (variation 2): re-define property: convert from accessor to data descriptor, check that enumerable (false) is preserved", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo17"; var pd = { set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; }, configurable: true, enumerable: false }; Object.defineProperty(o, propertyName, pd); pd = { value: 1 }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 1, configurable: true, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test18: { name: "8.12.9.9.c (variation 3): re-define property: convert from accessor to data descriptor, check that configurable/enumerable (true/false) not preserved when specified by descriptor (false/absent)", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo18"; var pd = { set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; }, configurable: true, enumerable: false }; Object.defineProperty(o, propertyName, pd); pd = { value: 1, configurable: false }; Object.defineProperty(o, propertyName, pd); // expected: configurable/enumerable = false/false. var expected = { writable: false, value: 1, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test19: { name: "8.12.9.9.c (variation 4): re-define property: convert from accessor to data descriptor, check that configurable/enumerable (true/true) not preserved when specified by descriptor (absent/false)", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo19"; var pd = { set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; }, configurable: true, enumerable: true }; Object.defineProperty(o, propertyName, pd); pd = { value: 1, enumerable: false }; Object.defineProperty(o, propertyName, pd); // expected: configurable/enumerable = true/false. var expected = { writable: false, value: 1, configurable: true, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, // where we are: // - re-define // - desc is not empty // - desc and current are not the same // - descriptor is data, current is data test20: { name: "8.12.9.10.a (variation 1): re-define data property: current is not configurable/not writable and descriptor writable is absent/value is same", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo20"; var pd = { value: 1 }; Object.defineProperty(o, propertyName, pd); pd = { value: 1 }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 1, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test21: { name: "8.12.9.10.a.i: re-define data property: current is not configurable/not writable and descriptor is writable, check that it throws TypeError", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo21"; var pd = { value: 1 }; Object.defineProperty(o, propertyName, pd); pd = { value: 2, writable: true }; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError, '', 'Cannot redefine non-configurable property \'foo21\''); return true; } }, test22: { name: "8.12.9.10.a.ii: re-define data property: current is not configurable/not writable and descriptor writable is false and value is different, check that it throws TypeError", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo22"; var pd = { value: 1 }; Object.defineProperty(o, propertyName, pd); pd = { value: 2, writable: false }; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError, '', 'Cannot modify non-writable property \'foo22\''); } }, test23: { name: "8.12.9.10.a (variation 2): re-define data property: current is configurable", body: function () { var propertyName = "foo23"; var o = { foo23: 1 }; var pd = { value: 2, writable: false }; Object.defineProperty(o, propertyName, pd); var expected = { writable: false, value: 2, configurable: true, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, // where we are: // - re-define // - desc is not empty // - desc and current are not the same // - descriptor is accessor, current is accessor test24: { name: "Test: 8.12.9.11 (variation 1): re-define accessor property: current configurable is true: valid case", body: function () { var propertyName = "foo24"; var o = { get foo24() { return this.Value; }, set foo24(arg) { helpers.writeln("old setter"); this.Value = arg; } }; var newGetter = function() { return 2; }; var newSetter = function(arg) { helpers.writeln("new setter"); } var pd = { get: newGetter, set: newSetter }; Object.defineProperty(o, propertyName, pd); var expected = { get: newGetter, set: newSetter, configurable: true, enumerable: true }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test25: { name: "8.12.9.11.a.i: re-define accessor property: current configurable is false, descriptor specifies setter as different, expect TypeError", body: function () { var propertyName = "foo25"; var o = helpers.getDummyObject(); var pd = { set: function(arg) { helpers.writeln("old setter"); this.Value = arg; } }; Object.defineProperty(o, propertyName, pd); pd = { set: function(arg) { helpers.writeln("new setter"); } }; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError); } }, test26: { name: "8.12.9.11.a.ii: re-define accessor property: current configurable is false, descriptor specifies getter as different, expect TypeError", body: function () { var propertyName = "foo26"; var o = helpers.getDummyObject(); var pd = { get: function() { return this.Value; }, }; Object.defineProperty(o, propertyName, pd); pd = { get: function() { helpers.writeln("new getter"); return 2; } }; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError); } }, test27: { name: "8.12.9.11 (variation 2): re-define accessor property: current configurable is true and no getter, descriptor specifies getter as undefined, setter as same", body: function () { var propertyName = "foo27"; var o = helpers.getDummyObject(); var setter = function(arg) { helpers.writeln("setter") }; var pd = { set: setter }; Object.defineProperty(o, propertyName, pd); pd = { get: undefined, set: setter }; Object.defineProperty(o, propertyName, pd); var expected = { get: undefined, set: setter, configurable: false, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); } }, test28: { name: "Re-define property from data to accessor property. Make sure that setter is called when setting the value.", body: function () { // define a data property. var propertyName = "foo28"; var o = helpers.getDummyObject(); var pd = { value: 1, configurable: true }; Object.defineProperty(o, propertyName, pd); // re-define the property to be accessor property. var log = ""; var getter = function() { log += "getter was called."; return this.Value; } var setter = function(arg) { log += "setter was called."; this.Value = arg; }; pd = { get: getter, set: setter }; Object.defineProperty(o, propertyName, pd); // set the value and get it. var newValue = 2; o[propertyName] = newValue; var actualValue = o[propertyName]; // validate. var expected = { get: getter, set: setter, configurable: true, enumerable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); assert.areEqual("setter was called.getter was called.", log, "wrong log"); assert.areEqual(newValue, actualValue, "wrong value"); } }, test29: { name: "Define property 'length' as accessor property on array: check that it throws TypeError.", body: function () { assert.throws( function() { Object.defineProperty([], "length", {configurable: false, get: function() {return 2;}}); }, TypeError); assert.throws( function() { Object.defineProperty(Array.prototype, "length", {configurable: false, get: function() {return 2;}}); }, TypeError); } }, // Where we are: some tests for specific issues. test30: { name: "Define property with getter specified as undefined, then access the property (WOOB bug 1123281)", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo30"; var pd = { get: undefined }; Object.defineProperty(o, propertyName, pd); assert.areEqual(undefined, o[propertyName]); } }, test31: { name: "Define property with setter specified as undefined, then set the property (WOOB bug 1123281)", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo31"; var pd = { set: undefined }; Object.defineProperty(o, propertyName, pd); o[propertyName] = 1; // Make sure this does not throw. assert.areEqual(undefined, o[propertyName]); // Just in case try to access the property. } }, test32: { name: "Convert data to accessor property with getter specified as undefined, then access the property (WOOB bug 1123281)", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo32"; var pd = { configurable: true, value: 0 }; Object.defineProperty(o, propertyName, pd); pd = { get: undefined }; Object.defineProperty(o, propertyName, pd); assert.areEqual(undefined, o[propertyName]); } }, test33: { name: "Convert data to accessor property with setter specified as undefined, then set the property (WOOB bug 1123281)", body: function () { var o = helpers.getDummyObject(); var propertyName = "foo33"; var pd = { configurable: true, value: 0 }; Object.defineProperty(o, propertyName, pd); pd = { set: undefined }; Object.defineProperty(o, propertyName, pd); o[propertyName] = 1; // Make sure this does not throw. assert.areEqual(undefined, o[propertyName]); // Just in case try to access the property. } }, test34: { name: "Convert accessor to a data property for non-extensible object (WIN8 bug 463559)", body: function () { var o = helpers.getDummyObject(); var propertyName = "x"; Object.defineProperty(o, propertyName, { get: function() { return 0; }, set: function(val) { helpers.writeln("setter was called although it shouldn't"); }, configurable: true }); Object.preventExtensions(o); var val = 1; Object.defineProperty(o, propertyName, { value: val, }); var expected = { value: val, configurable: true, enumerable: false, writable: false }; assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor"); assert.areEqual(val, o[propertyName], "the property value is wrong"); assert.areEqual(false, Object.isExtensible(o), "isExtensible() changed"); } }, test35: { name: "Set and unset getter property on a non-configurable property", body: function() { function function_1(a,b,c) { return 1; } function_1.__defineGetter__("length",function(){}); Object.defineProperty(function_1,"length", { value:(0x0a000030/2) }); assert.areEqual(function_1.length, 0x0a000030/2, "value in defineProperty not assigned"); } }, // Note: this test irreversibly changes the dummy object (that's important when dummy object is document/window), // it should in the very end. test_last_01: { name: "8.12.9.3: define property for non-extensible object, check that it throws TypeError", body: function () { var o = helpers.getDummyObject(); Object.preventExtensions(o); var propertyName = "foo01"; var pd = {}; assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError); } } }; // tests. testRunner.runTests(tests);
import DS from 'ember-data'; export default DS.Model.extend({ rooms: DS.hasMany('room', { async: false }), });
jest.autoMockOff(); describe('WEAKMAPS', () => { xit('has a set method', ()=>{ let key = {name: "Aaron"}; let value = {twitter: '@js_dev', gplus: '+AaronFrost'}; // Create a new WeakMap called 'myMap' // Add a new entry. Use key as the key and values as the value expect(myMap.has(key)).toBe(true); expect(myMap.get(key)).toEqual(value); }); xit('EXTRA CREDIT', () => { //If you make it this far, write a class with private member variables, using WeakMaps }) });
var MeshData = require('../renderer/MeshData'); var ObjectUtils = require('../util/ObjectUtils'); /** * MeshData for a Grid. * @extends MeshData * @param {number} [xSegments=10] Number of columns. * @param {number} [ySegments=10] Number of rows. * @param {number} [width=1] Total width of the Grid. * @param {number} [height=1] Total height of the Grid. * @example var meshData = new Grid( 10, 10, 10, 10); */ function Grid(xSegments, ySegments, width, height) { if (arguments.length === 1 && arguments[0] instanceof Object) { var props = arguments[0]; xSegments = props.xSegments; ySegments = props.ySegments; width = props.width; height = props.height; } this.xSegments = xSegments || 10; this.ySegments = ySegments || 10; this.width = width || 1; this.height = height || 1; var attributeMap = MeshData.defaultMap([MeshData.POSITION]); var vertsCount = 4 + (this.xSegments - 1) * 2 + (this.ySegments - 1) * 2; var idcsCount = 8 + (this.xSegments - 1) * 2 + (this.ySegments - 1) * 2; MeshData.call(this, attributeMap, vertsCount, idcsCount); this.indexModes[0] = 'Lines'; this.rebuild(); } Grid.prototype = Object.create(MeshData.prototype); Grid.prototype.constructor = Grid; Grid.prototype.rebuild = function () { var xExtent = this.width / 2; var yExtent = this.height / 2; var verts = []; var indices = []; // Outer lines verts.push( -xExtent, -yExtent, 0, -xExtent, yExtent, 0, xExtent, yExtent, 0, xExtent, -yExtent, 0 ); // Connecting the corners indices.push( 0, 1, 1, 2, 2, 3, 3, 0 ); // X grid lines var xPos; var step = this.width / this.xSegments; for (var i = 1; i < this.xSegments; i++) { xPos = i * step - xExtent; verts.push( xPos, -yExtent, 0, xPos, yExtent, 0 ); } // Y grid lines var yPos; step = this.height / this.ySegments; for (var i = 1; i < this.ySegments; i++) { yPos = i * step - yExtent; verts.push( -xExtent, yPos, 0, xExtent, yPos, 0 ); } for (var i = indices.length / 2; i < verts.length / 3; i += 2) { indices.push(i, i + 1); } this.getAttributeBuffer(MeshData.POSITION).set(verts); this.getIndexBuffer().set(indices); }; /** * Returns a clone of this grid * @returns {Grid} */ Grid.prototype.clone = function () { var options = ObjectUtils.shallowSelectiveClone(this, ['xSegments', 'ySegments', 'width', 'height']); return new Grid(options); }; module.exports = Grid;
const path = require('path'); module.exports = (baseConfig, env, config) => { config.module.rules.push({ test: /\.(ts|tsx)$/, use: [ { loader: 'babel-loader' }, { loader: 'awesome-typescript-loader' }, { loader: 'react-docgen-typescript-loader' } ] }); config.resolve.extensions.push('.ts', '.tsx'); return config; };
const data = { stage: null, background: 0xffffff, width: 32, height: 32, framerate: 24, totalFrames: 3, assets: { "tween_scale_y": "images/tween_scale_y.shapes.json" }, lib: {}, shapes: {}, textures: {}, spritesheets: [], getTexture: function(id) { if (data.textures[id]) { return data.textures[id]; } const atlas = data.spritesheets.find(atlas => !!atlas.textures[id]); return atlas ? atlas.textures[id] : null; }, setup: function(animate) { const MovieClip = animate.MovieClip; const Graphics = animate.Graphics; const Graphic1 = class extends MovieClip { constructor(mode) { super({ mode: mode, duration: 3, loop: false }); const instance1 = new Graphics() .drawCommands(data.shapes.tween_scale_y[0]); this.addTimedChild(instance1); } } data.lib.tween_scale_y = class extends MovieClip { constructor() { super({ duration: 3, framerate: 24 }); const instance1 = new Graphic1(MovieClip.SYNCHED); this.addTimedChild(instance1, 0, 3, { "0": { x: 16, y: 16, sy: 1 }, "1": { y: 15.983, sy: 0.602 }, "2": { y: 16, sy: 0.204 } }); } } data.stage = data.lib.tween_scale_y; } }; module.exports = data;
import _ from 'lodash'; import { SingleScrollingScreen, SplitScrollingScreen } from '../screen'; import RespawnScreen from './respawn'; import ConductCalc from '../../constants/conducts'; import GameState from '../../init/gamestate'; export class SingleConductScreen extends SingleScrollingScreen { static enter() { super.enter(); const target = this.getMainPlayer(); const sortedConduct = ConductCalc(target); this.scrollContent = sortedConduct; this.title = `${target.name}'s Traits (${sortedConduct.length})`; // shorten this for splitscreen this.nextScreen = RespawnScreen; } // static get split() { return SplitConductScreen; } } export class SplitConductScreen extends SplitScrollingScreen { static enter() { super.enter(); this.scrollContent = []; this.title = []; _.each(GameState.players, (target, i) => { const sortedConduct = ConductCalc(target); this.scrollContent[i] = sortedConduct; this.title[i] = `${target.name}'s Traits (${sortedConduct.length})`; // shorten this for splitscreen }); this.nextScreen = RespawnScreen; } // static get split() { return SingleConductScreen; } }
/** * Copyright (c) ActiveState 2013 - ALL RIGHTS RESERVED. */ if (typeof define !== 'function') { var define = require('amdefine')(module) } define([], function () { var page = function (collection, data) { this.collection = collection; this.data = data; }; page.prototype = { getPage: function (direction, options, done) { var url = direction === 'prev' ? this.data.prev_url : this.data.next_url; if (!url) {return done(new Error('Page unavailable.'));} if (typeof options === 'function' && typeof done === 'undefined') { done = options; options = null; } options = options || {}; options.status_code = 200; var self = this; this.collection.api.get(url, options, function (err, res) { if (err) {return done(err);} done(null, new page(self.collection, res.body)); }); }, hasPrevPage: function () { return this.data.prev_url ? true : false; }, getPrevPage: function (options, done) { this.getPage('prev', options, done); }, hasNextPage: function () { return this.data.next_url ? true : false; }, getNextPage: function (options, done) { this.getPage('next', options, done); } }; return page; } );
define({ "_widgetLabel": "Atributová tabulka", "_featureAction_ShowRelatedRecords": "Zobrazit související záznamy", "_featureAction_ViewInTable": "Zobrazit v atributové tabulce", "ok": "OK", "cancel": "Storno", "unsupportQueryWarning": "Vrstva musí podporovat operace dané založené na dotazu, aby bylo možné ji zobrazovat ve widgetu Atributová tabulka. Ujistěte se, že je ve službě aktivní možnost dotazování.", "exportMessage": "Přejete si exportovat data do CSV souboru ?", "exportFiles": "Exportovat do CSV", "exportSelected": "Exportovat vybrané do CSV", "exportAll": "Exportovat vše do CSV", "options": "Možnosti", "zoomto": "Přiblížit na", "highlight": "Zvýraznit grafiku", "selectAll": "Vybrat záznamy na všech stránkách", "selectPage": "Vybrat záznamy na aktuální stránce", "clearSelection": "Vymazat výběr", "filter": "Filtr", "setFilterTip": "Nastavte filtr správně.", "noFilterTip": "Pokud nedefinujete výrazy filtru, tato dotazovací úloha zobrazí všechny prvky v zadaném zdroji dat.", "filterByExtent": "Filtrovat podle rozsahu mapy", "showSelectedRecords": "Zobrazit vybrané záznamy", "showAllRecords": "Zobrazit všechny záznamy", "showRelatedRecords": "Zobrazit související záznamy", "noRelatedRecords": "Nebyly nalezeny žádné související záznamy.", "attachmentColumn": "Fotografie a soubory", "refresh": "Obnovit", "features": "prvků", "records": "záznamy", "selected": "vybrané", "transparent": "Režim průhlednosti", "indicate": "Najít výběr", "columns": "Zobrazit/skrýt sloupce", "selectionSymbol": "Symbol výběru", "closeMessage": "Skrýt tabulku (znovu ji rozbalit zespodu)", "dataNotAvailable": "Data nejsou k dispozici!<br>Zkuste to znovu kliknutím na tlačítko [Obnovit].", "openTableTip": "Otevřít atributovou tabulku", "closeTableTip": "Skrýt atributovou tabulku", "sortAsc": "Seřadit vzestupně", "sortDes": "Seřadit sestupně", "statistics": "Statistika", "attachments": "Přílohy", "files": "soubory" });
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.createTable('ProfileItems', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, profileId: { type: Sequelize.INTEGER, allowNull: false, references: { model: 'Profiles', key: 'id' } }, itemId: { type: Sequelize.INTEGER, allowNull: true, // profil mix tidak butuh ref ke item references: { model: 'Items', key: 'id' } }, amount: { type: Sequelize.INTEGER, allowNull: false }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function (queryInterface, Sequelize) { return queryInterface.dropTable('ProfileItems'); } };
import {AppError} from './error'; export class Cache { constructor() { this.items = {}; } set(key, value) { this.items[key] = value; } get(key) { const entry = this.find(key); if (!entry) { throw new AppError( 'cache.get', `Entry with key was not found "${key}"`); } return entry; } has(key) { const items = this.items; return items.hasOwnProperty(key); } find(key) { const items = this.items; if (items.hasOwnProperty(key)) { return items[key]; } return null; } remove(key) { if (!this.items.hasOwnProperty(key)) { throw new AppError( 'cache.remove', `Entry with key was not found "${key}"`); } delete this.items[key]; } clear() { this.items = {}; } }
(function(c){var l=function(a,d){var e=c(this),b=e.data("MediaTable");c.isEmptyObject(b)&&(b={$wrap:c("<div>"),$table:e,$menu:!1,cfg:a,id:e.attr("id")},b.id||(b.id="MediaTable-"+d,b.$table.attr("id",b.id)),b.$table.addClass("activeMediaTable"),b.$wrap.addClass("mediaTableWrapper"),b.$table.before(b.$wrap).appendTo(b.$wrap),b.cfg.menu&&h(b),b.$table.find("thead th").each(function(a){k.call(this,a,b)}),b.$table.data("MediaTable",b))},h=function(a){a.$menu=c('<div class="btn-group" />');a.$menu.$header= c('<a class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" href="#" />');a.$menu.$list=c('<ul class="dropdown-menu" />');a.$menu.addClass("mediaTableMenu").addClass("mediaTableMenuClosed").append(a.$menu.$header).append(a.$menu.$list);a.$wrap.addClass("mediaTableWrapperWithMenu");a.$menu.$header.html(a.cfg.menuTitle+' <span class="caret"></span>');a.$table.before(a.$menu);c(window).bind("orientationchange resize",function(){a.$menu.find("input").trigger("updateCheck")});a.$menu.$header.bind("click", function(){a.$menu.toggleClass("mediaTableMenuClosed")});a.$menu.$list.bind("mouseleave",function(){a.$menu.toggleClass("mediaTableMenuClosed")})},k=function(a,d){var e=c(this),b=e.attr("id"),f=e.attr("class");b||(b=d.id+"-mediaTableCol-"+a,e.attr("id",b));if(d.cfg.menu&&!e.is(".persist")){var g=c('<li><div class="checkbox"><label for="toggle-col-'+d.id+"-"+a+'"><input type="checkbox" name="toggle-cols" id="toggle-col-'+d.id+"-"+a+'" value="'+b+'" /> '+e.text()+"</label></div></li>");d.$menu.$list.append(g); m(e,g.find("input"),d)}c("tbody tr",d.$table).each(function(){var d=b,e=c(this).find("td,th").eq(a);e.attr("headers",d);f&&e.attr("class",f)})},m=function(a,d,c){d.bind("change",function(){var a=d.val(),a=c.$table.find("#"+a+", [headers="+a+"]");d.is(":checked")?a.show():a.hide()}).bind("updateCheck",function(){a.is(":visible")?d.attr("checked",!0):d.attr("checked",!1)}).trigger("updateCheck")};c.fn.mediaTable=function(){var a=!1;if(!arguments.length||c.isPlainObject(arguments[0]))a=c.extend({},{menu:!0, menuTitle:"Columns",t:"e"},arguments[0]);if(!1!==a)c(this).each(function(d){l.call(this,a,d)});else if(arguments.length)switch(arguments[0]){case "destroy":c(this).each(function(){var a=c(this).data("MediaTable");a&&(a.$wrap.after(a.$table).remove(),a.$table.removeClass("activeMediaTable"),a.$table.data("MediaTable",null))})}return this}})(jQuery);
/** * @author Richard Davey <[email protected]> * @author Florian Mertens * @copyright 2022 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var Point = require('../point/Point'); /** * Get the nearest point on a line perpendicular to the given point. * * @function Phaser.Geom.Line.GetNearestPoint * @since 3.16.0 * * @generic {Phaser.Geom.Point} O - [out,$return] * * @param {Phaser.Geom.Line} line - The line to get the nearest point on. * @param {(Phaser.Geom.Point|object)} point - The point to get the nearest point to. * @param {(Phaser.Geom.Point|object)} [out] - An optional point, or point-like object, to store the coordinates of the nearest point on the line. * * @return {(Phaser.Geom.Point|object)} The nearest point on the line. */ var GetNearestPoint = function (line, point, out) { if (out === undefined) { out = new Point(); } var x1 = line.x1; var y1 = line.y1; var x2 = line.x2; var y2 = line.y2; var L2 = (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); if (L2 === 0) { return out; } var r = (((point.x - x1) * (x2 - x1)) + ((point.y - y1) * (y2 - y1))) / L2; out.x = x1 + (r * (x2 - x1)); out.y = y1 + (r * (y2 - y1)); return out; }; module.exports = GetNearestPoint;
'use strict' var geo = require('geometry'), util = require('util'), actions = require('../actions') var Scene = require('./Scene').Scene, Director = require('../Director').Director, EventDispatcher = require('../EventDispatcher').EventDispatcher, Scheduler = require('../Scheduler').Scheduler /** @ignore * Orientation Type used by some transitions */ var tOrientation = { kOrientationLeftOver: 0, kOrientationRightOver: 1, kOrientationUpOver: 0, kOrientationDownOver: 1 } /** * @class * Base class for Transition scenes * * @memberOf cocos.nodes * @extends cocos.nodes.Scene * * @opt {Float} duration How long the transition should last * @opt {cocos.nodes.Scene} scene Income scene */ function TransitionScene (opts) { TransitionScene.superclass.constructor.call(this, opts) this.duration = opts.duration if (!opts.scene) { throw "TransitionScene requires scene property" } this.inScene = opts.scene this.outScene = Director.sharedDirector._runningScene if (this.inScene == this.outScene) { throw "Incoming scene must be different from the outgoing scene" } EventDispatcher.sharedDispatcher.dispatchEvents = false this.sceneOrder() } TransitionScene.inherit(Scene, /** @lends cocos.nodes.TransitionScene# */ { /** * Incoming scene * @type {cocos.nodes.Scene} */ inScene: null, /** * Outgoing (current) scene * @type {cocos.nodes.Scene} */ outScene: null, /** * transition duration * @type Float */ duration: null, inSceneOnTop: null, sendCleanupToScene: null, /** * Called after the transition finishes */ finish: function () { var is = this.inScene, os = this.outScene /* clean up */ is.visible = true is.position = geo.PointZero() is.scale = 1.0 is.rotation = 0 os.visible = false os.position = geo.PointZero() os.scale = 1.0 os.rotation = 0 Scheduler.sharedScheduler.schedule({ target: this, method: this.setNewScene, interval: 0 }) }, /** * Used by some transitions to hide the outer scene */ hideOutShowIn: function () { this.inScene.visible = true this.outScene.visible = false }, setNewScene: function (dt) { var dir = Director.sharedDirector this.unscheduleSelector(this.setNewScene) // Save 'send cleanup to scene' // Not sure if it's cool to be accessing all these Director privates like this... this.sendCleanupToScene = dir._sendCleanupToScene dir.replaceScene(this.inScene) // enable events while transitions EventDispatcher.sharedDispatcher.dispatchEvents = true // issue #267 this.outScene.visible = true }, sceneOrder: function () { this.inSceneOnTop = true }, draw: function (context, rect) { if (this.inSceneOnTop) { this.outScene.visit(context, rect) this.inScene.visit(context, rect) } else { this.inScene.visit(context, rect) this.outScene.visit(context, rect) } }, onEnter: function () { TransitionScene.superclass.onEnter.call(this) this.inScene.onEnter() // outScene_ should not receive the onEnter callback }, onExit: function () { TransitionScene.superclass.onExit.call(this) this.outScene.onExit() // inScene_ should not receive the onExit callback // only the onEnterTransitionDidFinish if (this.inScene.hasOwnProperty('onEnterTransitionDidFinish')) { this.inScene.onEnterTransitionDidFinish() } }, cleanup: function () { TransitionScene.superclass.cleanup.call(this) if (this.sendCleanupToScene) { this.outScene.cleanup() } } }) /** * @class * Rotate and zoom out the outgoing scene, and then rotate and zoom in the incoming * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionScene */ function TransitionRotoZoom (opts) { TransitionRotoZoom.superclass.constructor.call(this, opts) } TransitionRotoZoom.inherit(TransitionScene, /** @lends cocos.nodes.TransitionRotoZoom# */ { onEnter: function() { TransitionRotoZoom.superclass.onEnter.call(this) var dur = this.duration this.inScene.scale = 0.001 this.outScene.scale = 1.0 this.inScene.anchorPoint = geo.ccp(0.5, 0.5) this.outScene.anchorPoint = geo.ccp(0.5, 0.5) var outzoom = [ new actions.Spawn({actions: [ new actions.ScaleBy({scale: 0.001, duration: dur/2}), new actions.RotateBy({angle: 360*2, duration: dur/2}) ]}), new actions.DelayTime({duration: dur/2})] // Can't nest sequences or reverse them very easily, so incoming scene actions must be put // together manually for now... var inzoom = [ new actions.DelayTime({duration: dur/2}), new actions.Spawn({actions: [ new actions.ScaleTo({scale: 1.0, duration: dur/2}), new actions.RotateBy({angle: -360*2, duration: dur/2}) ]}), new actions.CallFunc({ target: this, method: this.finish }) ] // Sequence init() copies actions this.outScene.runAction(new actions.Sequence({actions: outzoom})) this.inScene.runAction(new actions.Sequence({actions: inzoom})) } }) /** * @class * Move in from to the left the incoming scene. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionScene */ function TransitionMoveInL (opts) { TransitionMoveInL.superclass.constructor.call(this, opts) } TransitionMoveInL.inherit(TransitionScene, /** @lends cocos.nodes.TransitionMoveInL# */ { onEnter: function () { TransitionMoveInL.superclass.onEnter.call(this) this.initScenes() this.inScene.runAction(new actions.Sequence({actions: [ this.action(), new actions.CallFunc({ target: this, method: this.finish })] })) }, action: function () { return new actions.MoveTo({ position: geo.ccp(0, 0), duration: this.duration }) }, initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(-s.width, 0) } }) /** * @class * Move in from to the right the incoming scene. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionMoveInL */ function TransitionMoveInR (opts) { TransitionMoveInR.superclass.constructor.call(this, opts) } TransitionMoveInR.inherit(TransitionMoveInL, /** @lends cocos.nodes.TransitionMoveInR# */ { initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(s.width, 0) } }) /** * @class * Move the incoming scene in from the top. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionMoveInL */ function TransitionMoveInT (opts) { TransitionMoveInT.superclass.constructor.call(this, opts) } TransitionMoveInT.inherit(TransitionMoveInL, /** @lends cocos.nodes.TransitionMoveInT# */ { initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(0, s.height) } }) /** * @class * Move the incoming scene in from the bottom. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionMoveInL */ function TransitionMoveInB (opts) { TransitionMoveInB.superclass.constructor.call(this, opts) } TransitionMoveInB.inherit(TransitionMoveInL, /** @lends cocos.nodes.TransitionMoveInB# */ { initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(0, -s.height) } }) /** * @class * Slide in the incoming scene from the left. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionScene */ function TransitionSlideInL (opts) { TransitionSlideInL.superclass.constructor.call(this, opts) } TransitionSlideInL.inherit(TransitionScene, /** @lends cocos.nodes.TransitionSlideInL# */ { onEnter: function () { TransitionSlideInL.superclass.onEnter.call(this) this.initScenes() var movein = this.action() var moveout = this.action() var outAction = new actions.Sequence({ actions: [ moveout, new actions.CallFunc({ target: this, method: this.finish })] }) this.inScene.runAction(movein) this.outScene.runAction(outAction) }, sceneOrder: function () { this.inSceneOnTop = false }, initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(-s.width, 0) }, action: function () { var s = Director.sharedDirector.winSize return new actions.MoveBy({ position: geo.ccp(s.width, 0), duration: this.duration }) } }) /** * @class * Slide in the incoming scene from the right. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionSlideInL */ function TransitionSlideInR (opts) { TransitionSlideInR.superclass.constructor.call(this, opts) } TransitionSlideInR.inherit(TransitionSlideInL, /** @lends cocos.nodes.TransitionSlideInR# */ { sceneOrder: function () { this.inSceneOnTop = true }, initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(s.width, 0) }, action: function () { var s = Director.sharedDirector.winSize return new actions.MoveBy({ position: geo.ccp(-s.width, 0), duration: this.duration }) } }) /** * @class * Slide in the incoming scene from the top. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionSlideInL */ function TransitionSlideInT (opts) { TransitionSlideInT.superclass.constructor.call(this, opts) } TransitionSlideInT.inherit(TransitionSlideInL, /** @lends cocos.nodes.TransitionSlideInT# */ { sceneOrder: function () { this.inSceneOnTop = false }, initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(0, s.height) }, action: function () { var s = Director.sharedDirector.winSize return new actions.MoveBy({ position: geo.ccp(0, -s.height), duration: this.duration }) } }) /** * @class * Slide in the incoming scene from the bottom. * * @memberOf cocos.nodes * @extends cocos.nodes.TransitionSlideInL */ function TransitionSlideInB (opts) { TransitionSlideInB.superclass.constructor.call(this, opts) } TransitionSlideInB.inherit(TransitionSlideInL, /** @lends cocos.nodes.TransitionSlideInB# */ { sceneOrder: function () { this.inSceneOnTop = true }, initScenes: function () { var s = Director.sharedDirector.winSize this.inScene.position = geo.ccp(0, -s.height) }, action: function () { var s = Director.sharedDirector.winSize return new actions.MoveBy({ position: geo.ccp(0, s.height), duration: this.duration }) } }) exports.TransitionScene = TransitionScene exports.TransitionRotoZoom = TransitionRotoZoom exports.TransitionMoveInL = TransitionMoveInL exports.TransitionMoveInR = TransitionMoveInR exports.TransitionMoveInT = TransitionMoveInT exports.TransitionMoveInB = TransitionMoveInB exports.TransitionSlideInL = TransitionSlideInL exports.TransitionSlideInR = TransitionSlideInR exports.TransitionSlideInT = TransitionSlideInT exports.TransitionSlideInB = TransitionSlideInB // vim:et:st=4:fdm=marker:fdl=0:fdc=1
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ cc.RAND_MAX = 0xffffff; cc.rand = function () { return Math.random() * cc.RAND_MAX; }; /** * cc.Waves3D action * @class * @extends cc.Grid3DAction */ cc.Waves3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{ _waves:null, _amplitude:null, _amplitudeRate:null, ctor:function () { cc.GridAction.prototype.ctor.call(this); this._waves = 0; this._amplitude = 0; this._amplitudeRate = 0; }, /** * get Amplitude * @return {Number} */ getAmplitude:function () { return this._amplitude; }, /** * set Amplitude * @param {Number} amplitude */ setAmplitude:function (amplitude) { this._amplitude = amplitude; }, /** * get Amplitude Rate * @return {Number} */ getAmplitudeRate:function () { return this._amplitudeRate; }, /** * set Amplitude Rate * @param {Number} amplitudeRate */ setAmplitudeRate:function (amplitudeRate) { this._amplitudeRate = amplitudeRate; }, /** * initializes an action with duration, grid size, waves and amplitude * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} waves * @param {Number} amplitude * @return {Boolean} */ initWithDuration:function (duration, gridSize, waves, amplitude) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { this._waves = waves; this._amplitude = amplitude; this._amplitudeRate = 1.0; return true; } return false; }, update:function (time) { var locGridSize = this._gridSize; var locAmplitude = this._amplitude, locPos = cc.p(0, 0); var locAmplitudeRate = this._amplitudeRate, locWaves = this._waves; for (var i = 0; i < locGridSize.width + 1; ++i) { for (var j = 0; j < locGridSize.height + 1; ++j) { locPos.x = i; locPos.y = j; var v = this.originalVertex(locPos); v.z += (Math.sin(Math.PI * time * locWaves * 2 + (v.y + v.x) * 0.01) * locAmplitude * locAmplitudeRate); //cc.log("v.z offset is" + (Math.sin(Math.PI * time * this._waves * 2 + (v.y + v.x) * 0.01) * this._amplitude * this._amplitudeRate)); this.setVertex(locPos, v); } } } }); /** * creates an action with duration, grid size, waves and amplitude * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} waves * @param {Number} amplitude * @return {cc.Waves3D} */ cc.Waves3D.create = function (duration, gridSize, waves, amplitude) { var action = new cc.Waves3D(); action.initWithDuration(duration, gridSize, waves, amplitude); return action; }; /** * cc.FlipX3D action * @class * @extends cc.Grid3DAction */ cc.FlipX3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{ /** * initializes the action with duration * @param {Number} duration * @return {Boolean} */ initWithDuration:function (duration) { return cc.Grid3DAction.prototype.initWithDuration.call(this, duration, cc.size(1, 1)); }, /** * initializes the action with gridSize and duration * @param {cc.Size} gridSize * @param {Number} duration * @return {Boolean} */ initWithSize:function (gridSize, duration) { if (gridSize.width != 1 || gridSize.height != 1) { // Grid size must be (1,1) cc.log("Grid size must be (1,1)"); return false; } return cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize); }, update:function (time) { var angle = Math.PI * time; // 180 degrees var mz = Math.sin(angle); angle = angle / 2.0; // x calculates degrees from 0 to 90 var mx = Math.cos(angle); var diff = new cc.Vertex3F(); var tempVer = cc.p(0, 0); tempVer.x = tempVer.y = 1; var v0 = this.originalVertex(tempVer); tempVer.x = tempVer.y = 0; var v1 = this.originalVertex(tempVer); var x0 = v0.x; var x1 = v1.x; var x; var a, b, c, d; if (x0 > x1) { // Normal Grid a = cc.p(0, 0); b = cc.p(0, 1); c = cc.p(1, 0); d = cc.p(1, 1); x = x0; } else { // Reversed Grid c = cc.p(0, 0); d = cc.p(0, 1); a = cc.p(1, 0); b = cc.p(1, 1); x = x1; } diff.x = ( x - x * mx ); diff.z = Math.abs(parseFloat((x * mz) / 4.0)); // bottom-left var v = this.originalVertex(a); v.x = diff.x; v.z += diff.z; this.setVertex(a, v); // upper-left v = this.originalVertex(b); v.x = diff.x; v.z += diff.z; this.setVertex(b, v); // bottom-right v = this.originalVertex(c); v.x -= diff.x; v.z -= diff.z; this.setVertex(c, v); // upper-right v = this.originalVertex(d); v.x -= diff.x; v.z -= diff.z; this.setVertex(d, v); } }); /** * creates FlipX3D action with duration * @param {Number} duration * @return {cc.FlipX3D} */ cc.FlipX3D.create = function (duration) { var action = new cc.FlipX3D(); action.initWithDuration(duration); return action; }; /** * cc.FlipY3D action * @class * @extends cc.FlipX3D */ cc.FlipY3D = cc.FlipX3D.extend(/** @lends cc.FlipY3D# */{ update:function (time) { var angle = Math.PI * time; // 180 degrees var mz = Math.sin(angle); angle = angle / 2.0; // x calculates degrees from 0 to 90 var my = Math.cos(angle); var diff = new cc.Vertex3F(); var tempP = cc.p(0, 0); tempP.x = tempP.y = 1; var v0 = this.originalVertex(tempP); tempP.x = tempP.y = 0; var v1 = this.originalVertex(tempP); var y0 = v0.y; var y1 = v1.y; var y; var a, b, c, d; if (y0 > y1) { // Normal Grid a = cc.p(0, 0); b = cc.p(0, 1); c = cc.p(1, 0); d = cc.p(1, 1); y = y0; } else { // Reversed Grid b = cc.p(0, 0); a = cc.p(0, 1); d = cc.p(1, 0); c = cc.p(1, 1); y = y1; } diff.y = y - y * my; diff.z = Math.abs(parseFloat(y * mz) / 4.0); // bottom-left var v = this.originalVertex(a); v.y = diff.y; v.z += diff.z; this.setVertex(a, v); // upper-left v = this.originalVertex(b); v.y -= diff.y; v.z -= diff.z; this.setVertex(b, v); // bottom-right v = this.originalVertex(c); v.y = diff.y; v.z += diff.z; this.setVertex(c, v); // upper-right v = this.originalVertex(d); v.y -= diff.y; v.z -= diff.z; this.setVertex(d, v); } }); /** * creates the action with duration * @param {Number} duration * @return {cc.FlipY3D} */ cc.FlipY3D.create = function (duration) { var action = new cc.FlipY3D(); action.initWithDuration(duration); return action; }; /** * cc.Lens3D action * @class * @extends cc.FlipX3D */ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{ /* lens center position */ _position:null, _radius:0, /** lens effect. Defaults to 0.7 - 0 means no effect, 1 is very strong effect */ _lensEffect:0, /** lens is concave. (true = concave, false = convex) default is convex i.e. false */ _concave:false, _dirty:false, ctor:function () { cc.GridAction.prototype.ctor.call(this); this._position = cc._pConst(0, 0); this._radius = 0; this._lensEffect = 0; this._concave = false; this._dirty = false; }, /** * Get lens center position * @return {Number} */ getLensEffect:function () { return this._lensEffect; }, /** * Set lens center position * @param {Number} lensEffect */ setLensEffect:function (lensEffect) { this._lensEffect = lensEffect; }, /** * Set whether lens is concave * @param {Boolean} concave */ setConcave:function (concave) { this._concave = concave; }, /** * get Position * @return {cc.Point} */ getPosition:function () { return this._position; }, /** * set Position * @param {cc.Point} position */ setPosition:function (position) { if (!cc.pointEqualToPoint(position, this._position)) { this._position._x = position.x; this._position._y = position.y; this._dirty = true; } }, /** * initializes the action with center position, radius, a grid size and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {cc.Point} position * @param {Number} radius * @return {Boolean} */ initWithDuration:function (duration, gridSize, position, radius) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { this.setPosition(position); this._radius = radius; this._lensEffect = 0.7; this._dirty = true; return true; } return false; }, update:function (time) { if (this._dirty) { var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height; var locRadius = this._radius, locLensEffect = this._lensEffect; var locPos = cc.p(0, 0); var vect = cc.p(0, 0); var v, r, l, new_r, pre_log; for (var i = 0; i < locGridSizeWidth + 1; ++i) { for (var j = 0; j < locGridSizeHeight + 1; ++j) { locPos.x = i; locPos.y = j; v = this.originalVertex(locPos); vect.x = this._position.x - v.x; vect.y = this._position.y - v.y; r = cc.pLength(vect); if (r < locRadius) { r = locRadius - r; pre_log = r / locRadius; if (pre_log == 0) pre_log = 0.001; l = Math.log(pre_log) * locLensEffect; new_r = Math.exp(l) * locRadius; r = cc.pLength(vect); if (r > 0) { vect.x = vect.x / r; vect.y = vect.y / r; vect.x = vect.x * new_r; vect.y = vect.y * new_r; v.z += cc.pLength(vect) * locLensEffect; } } this.setVertex(locPos, v); } } this._dirty = false; } } }); /** * creates the action with center position, radius, a grid size and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {cc.Point} position * @param {Number} radius * @return {cc.Lens3D} */ cc.Lens3D.create = function (duration, gridSize, position, radius) { var action = new cc.Lens3D(); action.initWithDuration(duration, gridSize, position, radius); return action; }; /** * cc.Ripple3D action * @class * @extends cc.Grid3DAction */ cc.Ripple3D = cc.Grid3DAction.extend(/** @lends cc.Ripple3D# */{ /* center position */ _position:null, _radius:null, _waves:null, _amplitude:null, _amplitudeRate:null, ctor:function () { cc.GridAction.prototype.ctor.call(this); this._position = cc._pConst(0, 0); this._radius = 0; this._waves = 0; this._amplitude = 0; this._amplitudeRate = 0; }, /** * get center position * @return {cc.Point} */ getPosition:function () { return this._position; }, /** * set center position * @param {cc.Point} position */ setPosition:function (position) { this._position._x = position.x; this._position._y = position.y; }, /** * get Amplitude * @return {Number} */ getAmplitude:function () { return this._amplitude; }, /** * set Amplitude * @param {Number} amplitude */ setAmplitude:function (amplitude) { this._amplitude = amplitude; }, /** * get Amplitude rate * @return {*} */ getAmplitudeRate:function () { return this._amplitudeRate; }, /** * get amplitude rate * @param {Number} amplitudeRate */ setAmplitudeRate:function (amplitudeRate) { this._amplitudeRate = amplitudeRate; }, /** * initializes the action with radius, number of waves, amplitude, a grid size and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {cc.Point} position * @param {Number} radius * @param {Number} waves * @param {Number} amplitude * @return {Boolean} */ initWithDuration:function (duration, gridSize, position, radius, waves, amplitude) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { this.setPosition(position); this._radius = radius; this._waves = waves; this._amplitude = amplitude; this._amplitudeRate = 1.0; return true; } return false; }, update:function (time) { var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height; var locPos = cc.p(0, 0), locRadius = this._radius; var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate; var v, r, tempPos = cc.p(0, 0); for (var i = 0; i < (locGridSizeWidth + 1); ++i) { for (var j = 0; j < (locGridSizeHeight + 1); ++j) { locPos.x = i; locPos.y = j; v = this.originalVertex(locPos); tempPos.x = this._position.x - v.x; tempPos.y = this._position.y - v.y; r = cc.pLength(tempPos); if (r < locRadius) { r = locRadius - r; var rate = Math.pow(r / locRadius, 2); v.z += (Math.sin(time * Math.PI * locWaves * 2 + r * 0.1) * locAmplitude * locAmplitudeRate * rate); } this.setVertex(locPos, v); } } } }); /** * creates the action with radius, number of waves, amplitude, a grid size and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {cc.Point} position * @param {Number} radius * @param {Number} waves * @param {Number} amplitude * @return {cc.Ripple3D} */ cc.Ripple3D.create = function (duration, gridSize, position, radius, waves, amplitude) { var action = new cc.Ripple3D(); action.initWithDuration(duration, gridSize, position, radius, waves, amplitude); return action; }; /** * cc.Shaky3D action * @class * @extends cc.Grid3DAction */ cc.Shaky3D = cc.Grid3DAction.extend(/** @lends cc.Shaky3D# */{ _randRange:null, _shakeZ:null, ctor:function () { cc.GridAction.prototype.ctor.call(this); this._randRange = 0; this._shakeZ = false; }, /** * initializes the action with a range, shake Z vertices, a grid and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} range * @param {Boolean} shakeZ * @return {Boolean} */ initWithDuration:function (duration, gridSize, range, shakeZ) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { this._randRange = range; this._shakeZ = shakeZ; return true; } return false; }, update:function (time) { var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height; var locRandRange = this._randRange, locShakeZ = this._shakeZ, locP = cc.p(0, 0); var v; for (var i = 0; i < (locGridSizeWidth + 1); ++i) { for (var j = 0; j < (locGridSizeHeight + 1); ++j) { locP.x = i; locP.y = j; v = this.originalVertex(locP); v.x += (cc.rand() % (locRandRange * 2)) - locRandRange; v.y += (cc.rand() % (locRandRange * 2)) - locRandRange; if (locShakeZ) v.z += (cc.rand() % (locRandRange * 2)) - locRandRange; this.setVertex(locP, v); } } } }); /** * creates the action with a range, shake Z vertices, a grid and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} range * @param {Boolean} shakeZ * @return {cc.Shaky3D} */ cc.Shaky3D.create = function (duration, gridSize, range, shakeZ) { var action = new cc.Shaky3D(); action.initWithDuration(duration, gridSize, range, shakeZ); return action; }; /** * cc.Liquid action * @class * @extends cc.Grid3DAction */ cc.Liquid = cc.Grid3DAction.extend(/** @lends cc.Liquid# */{ _waves:null, _amplitude:null, _amplitudeRate:null, ctor:function () { cc.GridAction.prototype.ctor.call(this); this._waves = 0; this._amplitude = 0; this._amplitudeRate = 0; }, /** * get amplitude * @return {Number} */ getAmplitude:function () { return this._amplitude; }, /** * set amplitude * @param {Number} amplitude */ setAmplitude:function (amplitude) { this._amplitude = amplitude; }, /** * get amplitude rate * @return {Number} */ getAmplitudeRate:function () { return this._amplitudeRate; }, /** * set amplitude rate * @param {Number} amplitudeRate */ setAmplitudeRate:function (amplitudeRate) { this._amplitudeRate = amplitudeRate; }, /** * initializes the action with amplitude, a grid and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} waves * @param {Number} amplitude * @return {Boolean} */ initWithDuration:function (duration, gridSize, waves, amplitude) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { this._waves = waves; this._amplitude = amplitude; this._amplitudeRate = 1.0; return true; } return false; }, update:function (time) { var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0); var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate; var v; for (var i = 1; i < locSizeWidth; ++i) { for (var j = 1; j < locSizeHeight; ++j) { locPos.x = i; locPos.y = j; v = this.originalVertex(locPos); v.x = (v.x + (Math.sin(time * Math.PI * locWaves * 2 + v.x * .01) * locAmplitude * locAmplitudeRate)); v.y = (v.y + (Math.sin(time * Math.PI * locWaves * 2 + v.y * .01) * locAmplitude * locAmplitudeRate)); this.setVertex(locPos, v); } } } }); /** * creates the action with amplitude, a grid and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} waves * @param {Number} amplitude * @return {cc.Liquid} */ cc.Liquid.create = function (duration, gridSize, waves, amplitude) { var action = new cc.Liquid(); action.initWithDuration(duration, gridSize, waves, amplitude); return action; }; /** * cc.Waves action * @class * @extends cc.Grid3DAction */ cc.Waves = cc.Grid3DAction.extend(/** @lends cc.Waves# */{ _waves:null, _amplitude:null, _amplitudeRate:null, _vertical:null, _horizontal:null, ctor:function () { cc.GridAction.prototype.ctor.call(this); this._waves = 0; this._amplitude = 0; this._amplitudeRate = 0; this._vertical = false; this._horizontal = false; }, /** * get amplitude * @return {Number} */ getAmplitude:function () { return this._amplitude; }, /** * set amplitude * @param {Number} amplitude */ setAmplitude:function (amplitude) { this._amplitude = amplitude; }, /** * get amplitude rate * @return {Number} */ getAmplitudeRate:function () { return this._amplitudeRate; }, /** * set amplitude rate * @param {Number} amplitudeRate */ setAmplitudeRate:function (amplitudeRate) { this._amplitudeRate = amplitudeRate; }, /** * initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} waves * @param {Number} amplitude * @param {Boolean} horizontal * @param {Boolean} vertical * @return {Boolean} */ initWithDuration:function (duration, gridSize, waves, amplitude, horizontal, vertical) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { this._waves = waves; this._amplitude = amplitude; this._amplitudeRate = 1.0; this._horizontal = horizontal; this._vertical = vertical; return true; } return false; }, update:function (time) { var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0); var locVertical = this._vertical, locHorizontal = this._horizontal; var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate; var v; for (var i = 0; i < locSizeWidth + 1; ++i) { for (var j = 0; j < locSizeHeight + 1; ++j) { locPos.x = i; locPos.y = j; v = this.originalVertex(locPos); if (locVertical) v.x = (v.x + (Math.sin(time * Math.PI * locWaves * 2 + v.y * .01) * locAmplitude * locAmplitudeRate)); if (locHorizontal) v.y = (v.y + (Math.sin(time * Math.PI * locWaves * 2 + v.x * .01) * locAmplitude * locAmplitudeRate)); this.setVertex(locPos, v); } } } }); /** * initializes the action with amplitude, horizontal sin, vertical sin, a grid and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {Number} waves * @param {Number} amplitude * @param {Boolean} horizontal * @param {Boolean} vertical * @return {cc.Waves} */ cc.Waves.create = function (duration, gridSize, waves, amplitude, horizontal, vertical) { var action = new cc.Waves(); action.initWithDuration(duration, gridSize, waves, amplitude, horizontal, vertical); return action; }; /** @brief */ /** * cc.Twirl action * @class * @extends cc.Grid3DAction */ cc.Twirl = cc.Grid3DAction.extend({ /* twirl center */ _position:null, _twirls:null, _amplitude:null, _amplitudeRate:null, ctor:function () { cc.GridAction.prototype.ctor.call(this); this._position = cc._pConst(0, 0); this._twirls = 0; this._amplitude = 0; this._amplitudeRate = 0; }, /** * get twirl center * @return {cc.Point} */ getPosition:function () { return this._position; }, /** * set twirl center * @param {cc.Point} position */ setPosition:function (position) { this._position._x = position.x; this._position._y = position.y; }, /** * get amplitude * @return {Number} */ getAmplitude:function () { return this._amplitude; }, /** * set amplitude * @param {Number} amplitude */ setAmplitude:function (amplitude) { this._amplitude = amplitude; }, /** * get amplitude rate * @return {Number} */ getAmplitudeRate:function () { return this._amplitudeRate; }, /** * set amplitude rate * @param {Number} amplitudeRate */ setAmplitudeRate:function (amplitudeRate) { this._amplitudeRate = amplitudeRate; }, /** initializes the action with center position, number of twirls, amplitude, a grid size and duration */ initWithDuration:function (duration, gridSize, position, twirls, amplitude) { if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) { this.setPosition(position); this._twirls = twirls; this._amplitude = amplitude; this._amplitudeRate = 1.0; return true; } return false; }, update:function (time) { var c = this._position; var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0); var amp = 0.1 * this._amplitude * this._amplitudeRate; var locTwirls = this._twirls; var v, a, dX, dY, avg = cc.p(0, 0); for (var i = 0; i < (locSizeWidth + 1); ++i) { for (var j = 0; j < (locSizeHeight + 1); ++j) { locPos.x = i; locPos.y = j; v = this.originalVertex(locPos); avg.x = i - (locSizeWidth / 2.0); avg.y = j - (locSizeHeight / 2.0); a = cc.pLength(avg) * Math.cos(Math.PI / 2.0 + time * Math.PI * locTwirls * 2) * amp; dX = Math.sin(a) * (v.y - c.y) + Math.cos(a) * (v.x - c.x); dY = Math.cos(a) * (v.y - c.y) - Math.sin(a) * (v.x - c.x); v.x = c.x + dX; v.y = c.y + dY; this.setVertex(locPos, v); } } } }); /** * creates the action with center position, number of twirls, amplitude, a grid size and duration * @param {Number} duration * @param {cc.Size} gridSize * @param {cc.Point} position * @param {Number} twirls * @param {Number} amplitude * @return {cc.Twirl} */ cc.Twirl.create = function (duration, gridSize, position, twirls, amplitude) { var action = new cc.Twirl(); action.initWithDuration(duration, gridSize, position, twirls, amplitude); return action; };
module.exports={A:{A:{"1":"E A B","2":"H D EB","132":"G"},B:{"1":"C p x J L N I"},C:{"1":"0 1 2 3 4 5 6 8 9 ZB BB F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y XB RB"},D:{"1":"0 1 2 3 4 5 6 8 9 F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y LB GB FB bB a HB IB JB"},E:{"1":"F K H D G E A B C KB CB MB NB OB PB QB z SB"},F:{"1":"0 7 E B C J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w TB UB VB WB z AB YB"},G:{"1":"G CB aB DB cB dB eB fB gB hB iB jB kB lB"},H:{"1":"mB"},I:{"1":"BB F a nB oB pB qB DB rB sB"},J:{"1":"D A"},K:{"1":"7 A B C M z AB"},L:{"1":"a"},M:{"1":"y"},N:{"1":"A B"},O:{"1":"tB"},P:{"1":"F K uB vB"},Q:{"1":"wB"},R:{"1":"xB"}},B:2,C:"CSS Generated content for pseudo-elements"};
module.exports = { mixins: [ "canonical", "og-title", "og-description", "og-site", "og-image", "favicon" ], getLink: function (meta) { if (meta.twitter && meta.twitter.player) { return { href: meta.twitter.player.value, type: CONFIG.T.text_html, rel: [CONFIG.R.player, CONFIG.R.twitter], "aspect-ratio": meta.twitter.player.width / meta.twitter.player.height }; } else { return { href: meta.video_src, type: meta.video_type || CONFIG.T.maybe_text_html, rel: CONFIG.R.player, "aspect-ratio": meta.video_width / meta.video_height }; } }, tests: [{ page: 'http://www.livestream.com/guide/livetv', selector: '.thumbnail' }, { skipMixins: [ "canonical" ] }, "http://www.livestream.com/28thwcars/" ] };
/** * User * @namespace crowdsource.user.services */ (function () { 'use strict'; angular .module('crowdsource.user.services') .factory('User', User); User.$inject = ['$http', 'HttpService']; function User($http, HttpService) { var baseUrl = HttpService.apiPrefix + '/users/'; return { getProfile: getProfile, getPublicProfile: getPublicProfile, updateProfile: updateProfile, getCountries: getCountries, getPreferences: getPreferences, getCities: getCities, getJobTitles: getJobTitles, listUsernames: listUsernames, updatePreferences: updatePreferences, setOnline: setOnline, create_or_update_aws: create_or_update_aws, get_aws_account: get_aws_account, removeAWSAccount: removeAWSAccount, listWorkers: listWorkers, retrieveRequesterBlackList: retrieveRequesterBlackList, retrieveRequesterListEntries: retrieveRequesterListEntries, createRequesterBlackList: createRequesterBlackList, deleteRequesterListEntry: deleteRequesterListEntry, createRequesterListEntry: createRequesterListEntry, createGroupWithMembers: createGroupWithMembers, listFavoriteGroups: listFavoriteGroups, getClients: getClients, getToken: getToken, isProfileComplete: isProfileComplete, updatePaymentInfo: updatePaymentInfo, getFinancialData: getFinancialData, updateCreditCard: updateCreditCard, updateBankInfo: updateBankInfo, getNotifications: getNotifications, isHandleUnique: isHandleUnique, updateHandle: updateHandle, getAvailableWorkerCount: getAvailableWorkerCount, isWhitelisted: isWhitelisted }; function getProfile(username) { var settings = { url: '/api/profile/', method: 'GET' }; return HttpService.doRequest(settings); } function getPublicProfile(handle) { var settings = { url: '/api/profile/' + handle + '/public/', method: 'GET' }; return HttpService.doRequest(settings); } function isHandleUnique(handle) { var settings = { url: '/api/profile/is-handle-unique/?handle=' + handle, method: 'GET' }; return HttpService.doRequest(settings); } function getNotifications() { var settings = { url: '/api/user/notifications/', method: 'GET' }; return HttpService.doRequest(settings); } function getFinancialData() { var settings = { url: '/api/profile/financial/', method: 'GET' }; return HttpService.doRequest(settings); } //default-credit-card function updateCreditCard(data) { var settings = { url: '/api/profile/default-credit-card/', method: 'PUT', data: data }; return HttpService.doRequest(settings); } function updateBankInfo(data) { var settings = { url: '/api/profile/default-bank/', method: 'PUT', data: data }; return HttpService.doRequest(settings); } function updateProfile(username, data) { var settings = { url: '/api/profile/' + username + '/', method: 'PUT', data: JSON.stringify(data) }; return HttpService.doRequest(settings); } function updateHandle(handle) { var settings = { url: '/api/profile/update-handle/', method: 'PUT', data: { handle: handle } }; return HttpService.doRequest(settings); } function getCountries() { var settings = { url: "/api/country/", method: 'GET' }; return HttpService.doRequest(settings); } function getCities() { var settings = { url: "/api/city/", method: 'GET' }; return HttpService.doRequest(settings); } function getJobTitles() { return $http.get('/static/js/user/data/job_titles.json'); } function listUsernames(pattern) { var settings = { url: '/api/user/list-username/?pattern=' + pattern, method: 'GET' }; return HttpService.doRequest(settings); } function updatePreferences(username, data) { var settings = { url: '/api/preferences/' + username + '/', method: 'PUT', data: data }; return HttpService.doRequest(settings); } function getPreferences() { var settings = { url: '/api/preferences/', method: 'GET' }; return HttpService.doRequest(settings); } function setOnline() { var settings = { url: '/api/user/online/', method: 'POST' }; return HttpService.doRequest(settings); } function create_or_update_aws(data) { var settings = { url: '/api/mturk-account', method: 'POST', data: data }; return HttpService.doRequest(settings); } function get_aws_account() { var settings = { url: '/api/mturk-account', method: 'GET' }; return HttpService.doRequest(settings); } function removeAWSAccount() { var settings = { url: '/api/mturk-account/remove', method: 'DELETE' }; return HttpService.doRequest(settings); } function getAccessList(type) { } function isProfileComplete() { var settings = { url: '/api/profile/is-complete/', method: 'GET' }; return HttpService.doRequest(settings); } function listWorkers(pattern) { var settings = { url: '/api/user/list-username/?pattern=' + pattern, method: 'GET' }; return HttpService.doRequest(settings); } function retrieveRequesterBlackList() { var settings = { url: '/api/requester-access-group/retrieve-global/', method: 'GET' }; return HttpService.doRequest(settings); } function retrieveRequesterListEntries(group) { var settings = { url: '/api/worker-access-entry/list-by-group/?group=' + group, method: 'GET' }; return HttpService.doRequest(settings); } function createRequesterBlackList() { var settings = { url: '/api/requester-access-group/', method: 'POST', data: { "name": "Global blacklist", "type": 2, "is_global": true } }; return HttpService.doRequest(settings); } function createGroupWithMembers(data) { var settings = { url: '/api/requester-access-group/create-with-entries/', method: 'POST', data: data }; return HttpService.doRequest(settings); } function deleteRequesterListEntry(entry_id) { var settings = { url: '/api/worker-access-entry/' + entry_id + '/', method: 'DELETE' }; return HttpService.doRequest(settings); } function createRequesterListEntry(data) { var settings = { url: '/api/worker-access-entry/', method: 'POST', data: data }; return HttpService.doRequest(settings); } function listFavoriteGroups() { var settings = { url: '/api/requester-access-group/list-favorites/', method: 'GET' }; return HttpService.doRequest(settings); } function getClients(data) { var settings = { url: '/api/user/authenticate/', method: 'POST', data: data }; return HttpService.doRequest(settings); } function getToken(data) { var settings = { url: '/api/oauth2-ng/token/', method: 'POST', data: data }; return HttpService.doRequest(settings); } function updatePaymentInfo(data) { var settings = { url: '/api/profile/stripe/', method: 'POST', data: data }; return HttpService.doRequest(settings); } function getAvailableWorkerCount() { var settings = { url: '/api/user/available-workers/', method: 'GET' }; return HttpService.doRequest(settings); } function isWhitelisted() { var settings = { url: '/api/user/is-whitelisted/', method: 'GET' }; return HttpService.doRequest(settings); } } })();
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { chainPropTypes } from '@material-ui/utils'; import { generateUtilityClasses, isHostComponent } from '@material-ui/unstyled'; import SliderUnstyled, { SliderValueLabelUnstyled, sliderUnstyledClasses, getSliderUtilityClass } from '@material-ui/unstyled/SliderUnstyled'; import useThemeProps from '../styles/useThemeProps'; import experimentalStyled from '../styles/experimentalStyled'; import { alpha, lighten, darken } from '../styles/colorManipulator'; import capitalize from '../utils/capitalize'; import { jsx as _jsx } from "react/jsx-runtime"; export const sliderClasses = _extends({}, sliderUnstyledClasses, generateUtilityClasses('MuiSlider', ['colorPrimary', 'colorSecondary', 'thumbColorPrimary', 'thumbColorSecondary'])); export const SliderRoot = experimentalStyled('span', {}, { name: 'MuiSlider', slot: 'Root', overridesResolver: (props, styles) => { const { styleProps } = props; const marks = styleProps.marksProp === true && styleProps.step !== null ? [...Array(Math.floor((styleProps.max - styleProps.min) / styleProps.step) + 1)].map((_, index) => ({ value: styleProps.min + styleProps.step * index })) : styleProps.marksProp || []; const marked = marks.length > 0 && marks.some(mark => mark.label); return _extends({}, styles.root, styles[`color${capitalize(styleProps.color)}`], marked && styles.marked, styleProps.orientation === 'vertical' && styles.vertical, styleProps.track === 'inverted' && styles.trackInverted, styleProps.track === false && styles.trackFalse); } })(({ theme, styleProps }) => _extends({ height: 2, width: '100%', boxSizing: 'content-box', padding: '13px 0', display: 'inline-block', position: 'relative', cursor: 'pointer', touchAction: 'none', color: theme.palette.primary.main, WebkitTapHighlightColor: 'transparent' }, styleProps.color === 'secondary' && { color: theme.palette.secondary.main }, { [`&.${sliderClasses.disabled}`]: { pointerEvents: 'none', cursor: 'default', color: theme.palette.grey[400] } }, styleProps.orientation === 'vertical' && { width: 2, height: '100%', padding: '0 13px' }, { // The primary input mechanism of the device includes a pointing device of limited accuracy. '@media (pointer: coarse)': _extends({ // Reach 42px touch target, about ~8mm on screen. padding: '20px 0' }, styleProps.orientation === 'vertical' && { padding: '0 20px' }), '@media print': { colorAdjust: 'exact' } }, styleProps.marked && _extends({ marginBottom: 20 }, styleProps.orientation === 'vertical' && { marginBottom: 'auto', marginRight: 20 }), { [`& .${sliderClasses.valueLabelCircle}`]: { display: 'flex', alignItems: 'center', justifyContent: 'center', width: 32, height: 32, borderRadius: '50% 50% 50% 0', backgroundColor: 'currentColor', transform: 'rotate(-45deg)' }, [`& .${sliderClasses.valueLabelLabel}`]: { color: theme.palette.primary.contrastText, transform: 'rotate(45deg)', textAlign: 'center' }, [`&.${sliderClasses.dragging}`]: { [`& .${sliderClasses.thumb}, & .${sliderClasses.track}`]: { transition: 'none' } } })); export const SliderRail = experimentalStyled('span', {}, { name: 'MuiSlider', slot: 'Rail', overridesResolver: (props, styles) => styles.rail })(({ styleProps }) => _extends({ display: 'block', position: 'absolute', width: '100%', height: 2, borderRadius: 1, backgroundColor: 'currentColor', opacity: 0.38 }, styleProps.orientation === 'vertical' && { height: '100%', width: 2 }, styleProps.track === 'inverted' && { opacity: 1 })); export const SliderTrack = experimentalStyled('span', {}, { name: 'MuiSlider', slot: 'Track', overridesResolver: (props, styles) => styles.track })(({ theme, styleProps }) => _extends({ display: 'block', position: 'absolute', height: 2, borderRadius: 1, backgroundColor: 'currentColor', transition: theme.transitions.create(['left', 'width'], { duration: theme.transitions.duration.shortest }) }, styleProps.orientation === 'vertical' && { width: 2 }, styleProps.track === false && { display: 'none' }, styleProps.track === 'inverted' && { backgroundColor: // Same logic as the LinearProgress track color theme.palette.mode === 'light' ? lighten(theme.palette.primary.main, 0.62) : darken(theme.palette.primary.main, 0.5) })); export const SliderThumb = experimentalStyled('span', {}, { name: 'MuiSlider', slot: 'Thumb', overridesResolver: (props, styles) => { const { styleProps } = props; return _extends({}, styles.thumb, styles[`thumbColor${capitalize(styleProps.color)}`]); } })(({ theme, styleProps }) => _extends({ position: 'absolute', width: 12, height: 12, marginLeft: -6, marginTop: -5, boxSizing: 'border-box', borderRadius: '50%', outline: 0, backgroundColor: 'currentColor', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: theme.transitions.create(['box-shadow', 'left'], { duration: theme.transitions.duration.shortest }), '&::after': { position: 'absolute', content: '""', borderRadius: '50%', // reach 42px hit target (2 * 15 + thumb diameter) left: -15, top: -15, right: -15, bottom: -15 }, [`&:hover, &.${sliderClasses.focusVisible}`]: { boxShadow: `0px 0px 0px 8px ${alpha(theme.palette.primary.main, 0.16)}`, '@media (hover: none)': { boxShadow: 'none' } }, [`&.${sliderClasses.active}`]: { boxShadow: `0px 0px 0px 14px ${alpha(theme.palette.primary.main, 0.16)}` }, [`&.${sliderClasses.disabled}`]: _extends({ width: 8, height: 8, marginLeft: -4, marginTop: -3 }, styleProps.orientation === 'vertical' && { marginLeft: -3, marginBottom: -4 }, { '&:hover': { boxShadow: 'none' } }) }, styleProps.orientation === 'vertical' && { marginLeft: -5, marginBottom: -6 }, styleProps.color === 'secondary' && { [`&:hover, &.${sliderClasses.focusVisible}`]: { boxShadow: `0px 0px 0px 8px ${alpha(theme.palette.secondary.main, 0.16)}` }, [`&.${sliderClasses.active}`]: { boxShadow: `0px 0px 0px 14px ${alpha(theme.palette.secondary.main, 0.16)}` } })); export const SliderValueLabel = experimentalStyled(SliderValueLabelUnstyled, {}, { name: 'MuiSlider', slot: 'ValueLabel', overridesResolver: (props, styles) => styles.valueLabel })(({ theme }) => _extends({ // IE 11 centering bug, to remove from the customization demos once no longer supported left: 'calc(-50% - 4px)', [`&.${sliderClasses.valueLabelOpen}`]: { transform: 'scale(1) translateY(-10px)' }, zIndex: 1 }, theme.typography.body2, { fontSize: theme.typography.pxToRem(12), lineHeight: 1.2, transition: theme.transitions.create(['transform'], { duration: theme.transitions.duration.shortest }), top: -34, transformOrigin: 'bottom center', transform: 'scale(0)', position: 'absolute' })); export const SliderMark = experimentalStyled('span', {}, { name: 'MuiSlider', slot: 'Mark', overridesResolver: (props, styles) => styles.mark })(({ theme, styleProps }) => _extends({ position: 'absolute', width: 2, height: 2, borderRadius: 1, backgroundColor: 'currentColor' }, styleProps.markActive && { backgroundColor: theme.palette.background.paper, opacity: 0.8 })); export const SliderMarkLabel = experimentalStyled('span', {}, { name: 'MuiSlider', slot: 'MarkLabel', overridesResolver: (props, styles) => styles.markLabel })(({ theme, styleProps }) => _extends({}, theme.typography.body2, { color: theme.palette.text.secondary, position: 'absolute', top: 26, transform: 'translateX(-50%)', whiteSpace: 'nowrap' }, styleProps.orientation === 'vertical' && { top: 'auto', left: 26, transform: 'translateY(50%)' }, { '@media (pointer: coarse)': _extends({ top: 40 }, styleProps.orientation === 'vertical' && { left: 31 }) }, styleProps.markLabelActive && { color: theme.palette.text.primary })); SliderRoot.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * @ignore */ children: PropTypes.node, /** * @ignore */ styleProps: PropTypes.shape({ 'aria-label': PropTypes.string, 'aria-labelledby': PropTypes.string, 'aria-valuetext': PropTypes.string, classes: PropTypes.object, color: PropTypes.oneOf(['primary', 'secondary']), defaultValue: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]), disabled: PropTypes.bool, getAriaLabel: PropTypes.func, getAriaValueText: PropTypes.func, isRtl: PropTypes.bool, marks: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.node, value: PropTypes.number.isRequired })), PropTypes.bool]), max: PropTypes.number, min: PropTypes.number, name: PropTypes.string, onChange: PropTypes.func, onChangeCommitted: PropTypes.func, orientation: PropTypes.oneOf(['horizontal', 'vertical']), scale: PropTypes.func, step: PropTypes.number, track: PropTypes.oneOf(['inverted', 'normal', false]), value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]), valueLabelDisplay: PropTypes.oneOf(['auto', 'off', 'on']), valueLabelFormat: PropTypes.oneOfType([PropTypes.func, PropTypes.string]) }) }; const extendUtilityClasses = styleProps => { const { color, classes = {} } = styleProps; return _extends({}, classes, { root: clsx(classes.root, getSliderUtilityClass(`color${capitalize(color)}`), classes[`color${capitalize(color)}`]), thumb: clsx(classes.thumb, getSliderUtilityClass(`thumbColor${capitalize(color)}`), classes[`thumbColor${capitalize(color)}`]) }); }; const shouldSpreadStyleProps = Component => { return !Component || !isHostComponent(Component); }; const Slider = /*#__PURE__*/React.forwardRef(function Slider(inputProps, ref) { const props = useThemeProps({ props: inputProps, name: 'MuiSlider' }); const { components = {}, componentsProps = {}, color = 'primary' } = props, other = _objectWithoutPropertiesLoose(props, ["components", "componentsProps", "color"]); const styleProps = _extends({}, props, { color }); const classes = extendUtilityClasses(styleProps); return /*#__PURE__*/_jsx(SliderUnstyled, _extends({}, other, { components: _extends({ Root: SliderRoot, Rail: SliderRail, Track: SliderTrack, Thumb: SliderThumb, ValueLabel: SliderValueLabel, Mark: SliderMark, MarkLabel: SliderMarkLabel }, components), componentsProps: _extends({}, componentsProps, { root: _extends({}, componentsProps.root, shouldSpreadStyleProps(components.Root) && { styleProps: _extends({}, componentsProps.root?.styleProps, { color }) }), thumb: _extends({}, componentsProps.thumb, shouldSpreadStyleProps(components.Thumb) && { styleProps: _extends({}, componentsProps.thumb?.styleProps, { color }) }) }), classes: classes, ref: ref })); }); process.env.NODE_ENV !== "production" ? Slider.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The label of the slider. */ 'aria-label': chainPropTypes(PropTypes.string, props => { const range = Array.isArray(props.value || props.defaultValue); if (range && props['aria-label'] != null) { return new Error('Material-UI: You need to use the `getAriaLabel` prop instead of `aria-label` when using a range slider.'); } return null; }), /** * The id of the element containing a label for the slider. */ 'aria-labelledby': PropTypes.string, /** * A string value that provides a user-friendly name for the current value of the slider. */ 'aria-valuetext': chainPropTypes(PropTypes.string, props => { const range = Array.isArray(props.value || props.defaultValue); if (range && props['aria-valuetext'] != null) { return new Error('Material-UI: You need to use the `getAriaValueText` prop instead of `aria-valuetext` when using a range slider.'); } return null; }), /** * @ignore */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'primary' */ color: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]), /** * The components used for each slot inside the Slider. * Either a string to use a HTML element or a component. * @default {} */ components: PropTypes.shape({ Mark: PropTypes.elementType, MarkLabel: PropTypes.elementType, Rail: PropTypes.elementType, Root: PropTypes.elementType, Thumb: PropTypes.elementType, Track: PropTypes.elementType, ValueLabel: PropTypes.elementType }), /** * The props used for each slot inside the Slider. * @default {} */ componentsProps: PropTypes.object, /** * The default value. Use when the component is not controlled. */ defaultValue: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]), /** * If `true`, the component is disabled. * @default false */ disabled: PropTypes.bool, /** * If `true`, the active thumb doesn't swap when moving pointer over a thumb while dragging another thumb. * @default false */ disableSwap: PropTypes.bool, /** * Accepts a function which returns a string value that provides a user-friendly name for the thumb labels of the slider. * * @param {number} index The thumb label's index to format. * @returns {string} */ getAriaLabel: PropTypes.func, /** * Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider. * * @param {number} value The thumb label's value to format. * @param {number} index The thumb label's index to format. * @returns {string} */ getAriaValueText: PropTypes.func, /** * Indicates whether the theme context has rtl direction. It is set automatically. * @default false */ isRtl: PropTypes.bool, /** * Marks indicate predetermined values to which the user can move the slider. * If `true` the marks are spaced according the value of the `step` prop. * If an array, it should contain objects with `value` and an optional `label` keys. * @default false */ marks: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.shape({ label: PropTypes.node, value: PropTypes.number.isRequired })), PropTypes.bool]), /** * The maximum allowed value of the slider. * Should not be equal to min. * @default 100 */ max: PropTypes.number, /** * The minimum allowed value of the slider. * Should not be equal to max. * @default 0 */ min: PropTypes.number, /** * Name attribute of the hidden `input` element. */ name: PropTypes.string, /** * Callback function that is fired when the slider's value changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (any). * **Warning**: This is a generic event not a change event. * @param {number | number[]} value The new value. * @param {number} activeThumb Index of the currently moved thumb. */ onChange: PropTypes.func, /** * Callback function that is fired when the `mouseup` is triggered. * * @param {object} event The event source of the callback. **Warning**: This is a generic event not a change event. * @param {number | number[]} value The new value. */ onChangeCommitted: PropTypes.func, /** * The component orientation. * @default 'horizontal' */ orientation: PropTypes.oneOf(['horizontal', 'vertical']), /** * A transformation function, to change the scale of the slider. * @default (x) => x */ scale: PropTypes.func, /** * The granularity with which the slider can step through values. (A "discrete" slider.) * The `min` prop serves as the origin for the valid values. * We recommend (max - min) to be evenly divisible by the step. * * When step is `null`, the thumb can only be slid onto marks provided with the `marks` prop. * @default 1 */ step: PropTypes.number, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * Tab index attribute of the hidden `input` element. */ tabIndex: PropTypes.number, /** * The track presentation: * * - `normal` the track will render a bar representing the slider value. * - `inverted` the track will render a bar representing the remaining slider value. * - `false` the track will render without a bar. * @default 'normal' */ track: PropTypes.oneOf(['inverted', 'normal', false]), /** * The value of the slider. * For ranged sliders, provide an array with two values. */ value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.number), PropTypes.number]), /** * Controls when the value label is displayed: * * - `auto` the value label will display when the thumb is hovered or focused. * - `on` will display persistently. * - `off` will never display. * @default 'off' */ valueLabelDisplay: PropTypes.oneOf(['auto', 'off', 'on']), /** * The format function the value label's value. * * When a function is provided, it should have the following signature: * * - {number} value The value label's value to format * - {number} index The value label's index to format * @default (x) => x */ valueLabelFormat: PropTypes.oneOfType([PropTypes.func, PropTypes.string]) } : void 0; export default Slider;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.detectScrollType = detectScrollType; exports.getNormalizedScrollLeft = getNormalizedScrollLeft; // Source from https://github.com/alitaheri/normalize-scroll-left var cachedType; /** * Based on the jquery plugin https://github.com/othree/jquery.rtl-scroll-type * * Types of scrollLeft, assuming scrollWidth=100 and direction is rtl. * * Type | <- Most Left | Most Right -> | Initial * ---------------- | ------------ | ------------- | ------- * default | 0 | 100 | 100 * negative (spec*) | -100 | 0 | 0 * reverse | 100 | 0 | 0 * * Edge 85: default * Safari 14: negative * Chrome 85: negative * Firefox 81: negative * IE 11: reverse * * spec* https://drafts.csswg.org/cssom-view/#dom-window-scroll */ function detectScrollType() { if (cachedType) { return cachedType; } var dummy = document.createElement('div'); var container = document.createElement('div'); container.style.width = '10px'; container.style.height = '1px'; dummy.appendChild(container); dummy.dir = 'rtl'; dummy.style.fontSize = '14px'; dummy.style.width = '4px'; dummy.style.height = '1px'; dummy.style.position = 'absolute'; dummy.style.top = '-1000px'; dummy.style.overflow = 'scroll'; document.body.appendChild(dummy); cachedType = 'reverse'; if (dummy.scrollLeft > 0) { cachedType = 'default'; } else { dummy.scrollLeft = 1; if (dummy.scrollLeft === 0) { cachedType = 'negative'; } } document.body.removeChild(dummy); return cachedType; } // Based on https://stackoverflow.com/a/24394376 function getNormalizedScrollLeft(element, direction) { var scrollLeft = element.scrollLeft; // Perform the calculations only when direction is rtl to avoid messing up the ltr bahavior if (direction !== 'rtl') { return scrollLeft; } var type = detectScrollType(); switch (type) { case 'negative': return element.scrollWidth - element.clientWidth + scrollLeft; case 'reverse': return element.scrollWidth - element.clientWidth - scrollLeft; default: return scrollLeft; } }